0% found this document useful (0 votes)
152 views

Java Codes 1 Invert

This document contains summaries of several Java programs that perform basic operations like checking if a number is even or odd, positive or negative, finding the sum of even and odd numbers in an array, determining the largest of three numbers, swapping two numbers, and incrementing the digits of a number. The programs demonstrate using conditionals, loops, arrays, and other basic Java constructs to solve common mathematical and logical problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
152 views

Java Codes 1 Invert

This document contains summaries of several Java programs that perform basic operations like checking if a number is even or odd, positive or negative, finding the sum of even and odd numbers in an array, determining the largest of three numbers, swapping two numbers, and incrementing the digits of a number. The programs demonstrate using conditionals, loops, arrays, and other basic Java constructs to solve common mathematical and logical problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 175

JAVA PROGRAMMING QUESTIONS AND ANSWERS

Java Program to Check Whether a Given Number is Even or Odd


1. import java.util.Scanner;
2. public class Odd_Even
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number you want to check:");
9. n = s.nextInt();
10. if(n % 2 == 0)
11. {
12. System.out.println("The given number "+n+" is Even ");
13. }
14. else
15. {
16. System.out.println("The given number "+n+" is Odd ");
17. }
18. }
19. }
Output:-
Enter the number you want to check:15
The given number 15 is Odd
Java Program to Find the Sum of Even and Odd Numbers
1. import java.util.Scanner;
2. public class Sum_Odd_Even
3. {
4. public static void main(String[] args)
5. {
6. int n, sumE = 0, sumO = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number of elements in array:");
9. n = s.nextInt();
10. int[] a = new int[n];
11. System.out.println("Enter the elements of the array:");
12. for(int i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. for(int i = 0; i < n; i++)
17. {
18. if(a[i] % 2 == 0)
19. {
20. sumE = sumE + a[i];
21. }
22. else
23. {
24. sumO = sumO + a[i];
25. }
26. }
27. System.out.println("Sum of Even Numbers:"+sumE);
28. System.out.println("Sum of Odd Numbers:"+sumO);
29. }
30. }
Output:-
Enter the number of elements in array:6
Enter the elements of the array:
1
3
2
6
7
9
Sum of Even Numbers:8
Sum of Odd Numbers:20
Java Program to Check Whether a Number is Positive or Negative
1. import java.util.Scanner;
2. public class Postive_Negative
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number you want to check:");
9. n = s.nextInt();
10. if(n > 0)
11. {
12. System.out.println("The given number "+n+" is Positive");
13. }
14. else if(n < 0)
15. {
16. System.out.println("The given number "+n+" is Negative");
17. }
18. else
19. {
20. System.out.println("The given number "+n+" is neither Positive nor Negative
");
21. }
22. }
23. }
Output:-
Enter the number you want to check:6
The given number 6 is Positive
Java Program to Find the Largest Number Among Three Numbers
1. import java.util.Scanner;
2. public class Biggest_Number
3. {
4. public static void main(String[] args)
5. {
6. int x, y, z;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first number:");
9. x = s.nextInt();
10. System.out.print("Enter the second number:");
11. y = s.nextInt();
12. System.out.print("Enter the third number:");
13. z = s.nextInt();
14. if(x > y && x > z)
15. {
16. System.out.println("Largest number is:"+x);
17. }
18. else if(y > z)
19. {
20. System.out.println("Largest number is:"+y);
21. }
22. else
23. {
24. System.out.println("Largest number is:"+z);
25. }
26.
27. }
28. }
Output:-
Enter the first number:10
Enter the second number:17
Enter the third number:15
Largest number is:17
Java Program to Swap Two Numbers
/*
* Java program to read two integers M and N and to swap their values.
* Using Temporary variables.
*/
import java.util.Scanner;
public class Swap_Integers
{
public static void main(String args[])
{
int m, n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
m = s.nextInt();
System.out.print("Enter the second number:");
n = s.nextInt();
temp = m;
m = n;
n = temp;
System.out.println("After Swapping");
System.out.println("First number:"+m);
System.out.println("Second number:"+n);
}
}
Output:-
Enter the first number:5
Enter the second number:7
After Swapping
First number:7
Second number:5
/*
* Swap Two Numbers in Java without using any Temporary Variable
*/
import java.util.Scanner;

public class Swap_Integers


{
public static void main(String args[])
{
int m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
m = s.nextInt();
System.out.print("Enter the second number:");
n = s.nextInt();
m = m + n;
n = m - n;
m = m - n;
System.out.println("After Swapping");
System.out.println("First number:"+m);
System.out.println("Second number:"+n);
}
}
Output:-
Enter the first number: 4
Enter the second number: 5
After Swapping
First number: 5
Second number:4
Java Program to Find the Number of Integers Divisible by 5
1. import java.util.Scanner;
2. public class Check_Divisiblity
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. if(n % 5 == 0)
11. {
12. System.out.println(n+" is divisible by 5");
13. }
14. else
15. {
16. System.out.println(n+" is not divisible by 5");
17. }
18. }
19. }
Output:-
Enter any number:45
45 is divisible by 5

Enter any number:16


16 is not divisible by 5
Java Program to Check if Two Numbers are Equal
1. import java.util.Scanner;
2. public class Equal_Integer
3. {
4. public static void main(String[] args)
5. {
6. int m, n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first number:");
9. m = s.nextInt();
10. System.out.print("Enter the second number:");
11. n = s.nextInt();
12. if(m == n)
13. {
14. System.out.println(m+" and "+n+" are equal ");
15. }
16. else
17. {
18. System.out.println(m+" and "+n+" are not equal ");
19. }
20. }
21. }
Output:-
Enter the first number:5
Enter the second number:7
5 and 7 are not equal

Enter the first number:6


Enter the second number:6
6 and 6 are equal
Sum of Digits Program in Java
1. import java.util.Scanner;
2. public class Digit_Sum
3. {
4. public static void main(String args[])
5. {
6. int m, n, sum = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number:");
9. m = s.nextInt();
10. while(m > 0)
11. {
12. n = m % 10;
13. sum = sum + n;
14. m = m / 10;
15. }
16. System.out.println("Sum of Digits:"+sum);
17. }
18. }
Output:-
Enter the number:456
Sum of Digits:15
Java Program to Find Sum of Digits of a Number using Recursion
1. import java.util.Scanner;
2. public class Digit_Sum
3. {
4. int sum = 0;
5. public static void main(String[] args)
6. {
7. int n;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the number:");
10. n = s.nextInt();
11. Digit_Sum obj = new Digit_Sum();
12. int a = obj.add(n);
13. System.out.println("Sum:"+a);
14. }
15. int add(int n)
16. {
17. sum = n % 10;
18. if(n == 0)
19. {
20. return 0;
21. }
22. else
23. {
24. return sum + add(n / 10);
25. }
26.
27. }
28. }
Output:-
Enter the number:345
Sum:12
Java Program to Extract Digits from a Given Number
1. import java.util.Scanner;
2. public class Extract_Digits
3. {
4. public static void main(String args[])
5. {
6. int n, m, a, i = 1, counter = 0;
7. Scanner s=new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. m = n;
11. while(n > 0)
12. {
13. n = n / 10;
14. counter++;
15. }
16. while(m > 0)
17. {
18. a = m % 10;
19. System.out.println("Digits at position "+counter+":"+a);
20. m = m / 10;
21. counter--;
22. }
23. }
24. }
Output:-
Enter any number:5678
Digits at position 4:8
Digits at position 3:7
Digits at position 2:6
Digits at position 1:5
Java Program to Increment by 1 to all the Digits of a Given Integer
1. import java.util.Scanner;
2. public class Increment_Digits
3. {
4. public static void main(String[] args)
5. {
6. int n, m = 0, a;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. while(n > 0)
11. {
12. a = n % 10;
13. a++;
14. m = m * 10 + a;
15. n = n / 10;
16. }
17. n = m;
18. m = 0;
19. while(n > 0)
20. {
21. a = n % 10;
22. m = m * 10 + a;
23. n = n / 10;
24. }
25. System.out.println("Result:"+m);
26. }
27. }
Output:-
Enter any number:4567
Result:5678
Java Program to Perform Arithmetic Operations
1. import java.util.Scanner;
2. public class Calculate
3. {
4. public static void main(String[] args)
5. {
6. int m, n, opt, add, sub, mul;
7. double div;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter first number:");
10. m = s.nextInt();
11. System.out.print("Enter second number:");
12. n = s.nextInt();
13. while(true)
14. {
15. System.out.println("Enter 1 for addition");
16. System.out.println("Enter 2 for subtraction");
17. System.out.println("Enter 3 for multiplication");
18. System.out.println("Enter 4 for division");
19. System.out.println("Enter 5 to Exit");
20. opt = s.nextInt();
21. switch(opt)
22. {
23. case 1:
24. add = m + n;
25. System.out.println("Result:"+add);
26. break;
27.
28. case 2:
29. sub = m - n;
30. System.out.println("Result:"+sub);
31. break;
32.
33. case 3:
34. mul = m * n;
35. System.out.println("Result:"+mul);
36. break;
37.
38. case 4:
39. div = (double)m / n;
40. System.out.println("Result:"+div);
41. break;
42.
43. case 5:
44. System.exit(0);
45. }
46. }
47. }
48. }
Output:-
Enter first number:5
Enter second number:2
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter 5 to Exit
4
Result:2.5
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter 5 to Exit
3
Result:10
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter 5 to Exit
5
Java Program to Print Binary Equivalent of an Integer using Recursion
1. import java.util.Scanner;
2. public class Binary_Recursion
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number:");
9. n = s.nextInt();
10. Binary_Recursion obj = new Binary_Recursion();
11. String m = obj.Binary(n);
12. System.out.println("Answer:"+m);
13. }
14. String Binary(int x)
15. {
16. if(x > 0)
17. {
18. int a = x % 2;
19. x = x / 2;
20. return a + "" + Binary(x);
21. }
22. return "";
23. }
24. }
Output:-
Enter the number:19
Answer:11001
Java Program to Print Multiplication Table
1. import java.util.Scanner;
2. public class Multiplication_Table
3. {
4. public static void main(String[] args)
5. {
6. Scanner s = new Scanner(System.in);
7. System.out.print("Enter number:");
8. int n=s.nextInt();
9. for(int i=1; i <= 10; i++)
10. {
11. System.out.println(n+" * "+i+" = "+n*i);
12. }
13. }
14. }
Output:-
Enter number:7
7*1=7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Java Program to Read a Grade and Display the Equivalent Description
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class Grade_Description
5. {
6. public static void main(String[] args) throws IOException
7. {
8. char a;
9. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
10. System.out.print("Enter grade of the student:");
11. a = (char) bf.read();
12. if(a == 'A' || a == 'a')
13. {
14. System.out.println("Student has got marks between above 80 out of 100.");
15. }
16. else if(a == 'B' || a == 'b')
17. {
18. System.out.println("Student has got marks above 60 but less than equal to 80
out of 100.");
19. }
20. else if(a == 'C' || a == 'c')
21. {
22. System.out.println("Student has got marks above 40 but less than equal to 60
out of 100.");
23. }
24. else
25. {
26. System.out.println("Student has failed");
27. }
28. }
29. }
Output:-
Enter grade of the student:B
Student has got marks above 60 but less than equal to 80 out of 100.
Java Program to Check Whether a Character is a Vowel, Consonant or Digit
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. import java.util.Scanner;
5. public class Vowel_Consonant
6. {
7. public static void main(String[] args) throws Exception
8. {
9. char n;
10. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
11. System.out.print("Enter the character you want to check:");
12. n = (char) bf.read();
13. switch(n)
14. {
15. case 'a':
16. System.out.println("The given character "+n+" is vowel");
17. break;
18.
19. case 'e':
20. System.out.println("The given character "+n+" is vowel");
21. break;
22.
23. case 'i':
24. System.out.println("The given character "+n+" is vowel");
25. break;
26.
27. case 'o':
28. System.out.println("The given character "+n+" is vowel");
29. break;
30.
31. case 'u':
32. System.out.println("The given character "+n+" is vowel");
33. break;
34.
35. default:
36. System.out.println("The given character "+n+" is consonant");
37. break;
38. }
39. }
40. }
Output:-
Enter the character you want to check:b
The given character b is consonant
Java Program to Check Whether a Given Alphabets are Uppercase or Lowercase or
Digits
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class Alphabet_Check
5. {
6. public static void main(String args[]) throws IOException
7. {
8. char m;
9. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
10. System.out.print("Enter any alphabet:");
11. m = (char) bf.read();
12. if(m >= 97 && m <= 123)
13. {
14. System.out.println("Lower Case");
15. }
16. else if(m >= 65 && m <= 96)
17. {
18. System.out.println("Upper Case");
19. }
20. else if(m >= 48 && m <= 57)
21. {
22. System.out.println("Digit");
23. }
24. }
25. }
Output:-
Enter any alphabet:B
Upper Case

Enter any alphabet:z


Lower Case

Enter any alphabet:9


Digit
Java Program to Accept the Height of a Person and Categorize as Taller, Dwarf &
Average
1. import java.util.Scanner;
2. public class Height_Category
3. {
4. public static void main(String args[])
5. {
6. int m;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the height:");
9. m = s.nextInt();
10. if(m > 175)
11. {
12. System.out.println("The person is tall.");
13. }
14. else if(m > 155 && m <= 175)
15. {
16. System.out.println("The person has average height.");
17. }
18. else
19. {
20. System.out.println("The person is dwarf.");
21. }
22. }
23. }
Output:-
Enter the height:175
The person has average height.
Java Program to Find Prime Numbers in a Given Range
import java.util.Scanner;
public class Prime
{
public static void main(String args[])
{
int s1, s2, s3, flag = 0, i, j;
Scanner s = new Scanner(System.in);
System.out.println ("Enter the lower limit :");
s1 = s.nextInt();
System.out.println ("Enter the upper limit :");
s2 = s.nextInt();
System.out.println ("The prime numbers in between the entered limits are :");
for(i = s1; i <= s2; i++)
{
for( j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = 0;
break;
}
else
{
flag = 1;
}
}
if(flag == 1)
{
System.out.println(i);
}
}
}
}
Output:-
Enter the lower limit :
2
Enter the upper limit :
20
The prime numbers in between the entered limits are :
3
5
7
11
13
17
19
Prime Number Program in Java
/*
* Java Program to Check Whether a Number is Prime or not using For Loop
*/

import java.util.Scanner;
public class CheckPrime
{
public static void main(String args[])
{
int j, num, flag = 0;
System.out.print("Enter the number :");
Scanner s = new Scanner(System.in);
num = s.nextInt();
for( j = 2; j < num; j++)
{
if(num % j == 0)
{
flag = 0;
break;
}
else
{
flag = 1;
}
}
if(flag == 1)
{
System.out.println(""+num+" is a prime number.");
}
else
{
System.out.println(""+num+" is not a prime number.");
}
}
}
Output:-
Enter a number:
7
7 is a prime number
Enter a number:
12
12 is not a prime number
import java.util.Scanner;
public class Checkprime
{
public static void main(String[] args)
{
int i = 1, num, flag=0;
System.out.print("Enter the number :");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num <= 1)
{
System.out.println("The number is not prime");
return;
}
while (i <= num / 2)
{
if (num % i == 0)
{
flag++;
}
i++;
}
if (flag > 1)
{
System.out.println(""+num+" is not a prime number.");
}
else
{
System.out.println(""+num+" is a prime number.");
}
}
}
Output:-
Enter a number:
13
13 is a prime number
Enter a number:
16
16 is not a prime number
import java.util.Scanner;
public class Prime
{
public static void main(String args[])
{
int s1, s2, s3, flag = 0, i, j;
Scanner s = new Scanner(System.in);
System.out.println ("Enter the lower limit :");
s1 = s.nextInt();
System.out.println ("Enter the upper limit :");
s2 = s.nextInt();
System.out.println ("The prime numbers in between the entered limits are :");
for(i = s1; i <= s2; i++)
{
for( j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = 0;
break;
}
else
{
flag = 1;
}
}
if(flag == 1)
{
System.out.println(i);
}
}
}
}
Output:-
Enter the lower limit :
2
Enter the upper limit :
20
The prime numbers in between the entered limits are :
3
5
7
11
13
17
19
Java Program to Check whether a Number is Prime or Not using Recursion
1. import java.util.Scanner;
2. public class Prime
3. {
4. public static void main(String[] args)
5. {
6. int n, x;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. Prime obj = new Prime();
11. x = obj.prime(n, 2);
12. if(x == 1)
13. {
14. System.out.println(n+" is prime number");
15. }
16. else
17. {
18. System.out.println(n+" is not prime number");
19. }
20. }
21. int prime(int y,int i)
22. {
23. if(i < y)
24. {
25. if(y % i != 0)
26. {
27. return(prime(y, ++i));
28. }
29. else
30. {
31. return 0;
32. }
33. }
34. return 1;
35. }
36. }
Output:-
Enter any number:17
17 is prime number
Java Program to Check Whether a Given Number is Perfect Number
1. import java.util.Scanner;
2. public class Perfect
3. {
4. public static void main(String[] args)
5. {
6. int n, sum = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. n = s.nextInt();
10. for(int i = 1; i < n; i++)
11. {
12. if(n % i == 0)
13. {
14. sum = sum + i;
15. }
16. }
17. if(sum == n)
18. {
19. System.out.println("Given number is a perfect number");
20. }
21. else
22. {
23. System.out.println("Given number is not a perfect number");
24. }
25. }
26. int divisor(int x)
27. {
28. return x;
29. }
30. }
Output:-
Enter the number: 6
Given number is a perfect numbe
Enter the number: 34
Given number is not a perfect number
Java Program to Check Armstrong Number
import java.util.Scanner;
public class ArmStrong
{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a number:");
n = s.nextInt();
a = n;
c = n;
while(a > 0)
{
a = a / 10;
count++;
}
while(n > 0)
{
b = n % 10;
sum = (int) (sum+Math.pow(b, count));
n = n / 10;
}
if(sum == c)
{
System.out.println(c+ " is an Armstrong number");
}
else
{
System.out.println(c+ " is not an Armstrong number");
}
}
}
Output:-
Enter a number: 371
371 is an Armstrong number

Enter a number: 150


150 is not an Armstrong number
Java Program to Print Armstrong Number between 1 to 1000
1. public class Armstrong
2. {
3. public static void main(String[] args)
4. {
5. int n, count = 0, a, b, c, sum = 0;
6. System.out.print("Armstrong numbers from 1 to 1000:");
7. for(int i = 1; i <= 1000; i++)
8. {
9. n = i;
10. while(n > 0)
11. {
12. b = n % 10;
13. sum = sum + (b * b * b);
14. n = n / 10;
15. }
16. if(sum == i)
17. {
18. System.out.print(i+" ");
19. }
20. sum = 0;
21. }
22. }
23. }
Output:-
Armstrong numbers from 1 to 1000:1 153 370 371 407
Java Program to Reverse a Number
/*
* Java program to reverse a number using While Loop
*/

import java.util.Scanner;
public class Reverse_Number
{
public static void main(String args[])
{
int m, n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
m = s.nextInt();
while(m > 0)
{
n = m % 10;
sum = sum * 10 + n;
m = m / 10;
}
System.out.println("Reverse of a Number is "+sum);
}
}
Output:-
Enter the number:
323441

Reverse of a Number is 144323


Enter the number
42394

Reverse of a Number is 49324


/*
* Java program to reverse a number using For Loop
*/

import java.util.Scanner;

public class ReverseNumber


{
public static void main(String[] args)
{
int m, n, reversed = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number: ");
m = s.nextInt();
for (; m != 0; m /= 10) {
n = m % 10;
reversed = reversed * 10 + n;
}
System.out.println("Reversed Number: " + reversed);
}
}
Output:-
Enter the number:
323441

Reversed Number: 144323


/*
* Java program to reverse a number using Recursion
*/

import static java.lang.StrictMath.pow;


import java.util.Scanner;
public class Reverse_Recursion
{
public static void main(String[] args)
{
int n, count = 0, m;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
n = s.nextInt();
m = n;
while(m > 0)
{
count++;
m = m / 10;
}
Reverse_Recursion obj = new Reverse_Recursion();
int a = obj.reverse(n, count);
System.out.println("Reverse:"+a);
}
int reverse(int x, int length)
{
if(length == 1)
{
return x;
}
else
{
int b = x % 10;
x = x / 10;
return (int) ((b * pow(10, length - 1)) + reverse(x, --length));
}
}
}
Output:-
Enter the number:467
Reverse:764
Java Program to Check Whether a Number is Palindrome or Not
/*
* Java Program to Check Number is Palindrome or Not using While Loop.
*/

import java.util.Scanner;
public class Palindrome
{
public static void main(String args[])
{
int n, m, rev = 0, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
n = s.nextInt();
m = n;
while(n > 0)
{
x = n % 10;
rev = rev * 10 + x;
n = n / 10;
}
if(rev == m)
{
System.out.println(" "+m+" is a palindrome number");
}
else
{
System.out.println(" "+m+" is not a palindrome number");
}
}
}
Output:-
Enter the number: 515
515 is a palindrome number.
Enter the number: 145
145 is not a palindrome number.
/*
*Java Program to check number is Palindrome or Not using recursion
*/

import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
int num, reverse = 0, rem, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
num = s.nextInt();
if (isPalindrome(num, reverse) == num)
System.out.println (num + " is a Palindrome");
else
System.out.println (num + " is not a Palindrome");
}
static int isPalindrome(int num, int rev)
{
if(num == 0)
return rev;
int rem = num % 10;
rev = rev * 10 + rem;
return isPalindrome(num / 10, rev);
}
}
Output:-
Enter the number: 1551
1551 is a palindrome number.
Enter the number: 537
537 is not a palindrome number.
Java Program to Reverse a Number and Find its Sum using do-while Loop
1. import java.util.Scanner;
2. public class Use_Do_While
3. {
4. public static void main(String[] args)
5. {
6. int n, a, m = 0, sum = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. do
11. {
12. a = n % 10;
13. m = m * 10 + a;
14. sum = sum + a;
15. n = n / 10;
16. }
17. while( n > 0);
18. System.out.println("Reverse:"+m);
19. System.out.println("Sum of digits:"+sum);
20. }
21. }
Output:-
Enter any number:456
Reverse:654
Sum of digits:15
Java Program to Reverse a Number using Recursion
1. import static java.lang.StrictMath.pow;
2. import java.util.Scanner;
3. public class Reverse_Recursion
4. {
5. public static void main(String[] args)
6. {
7. int n, count = 0, m;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the number:");
10. n = s.nextInt();
11. m = n;
12. while(m > 0)
13. {
14. count++;
15. m = m / 10;
16. }
17. Reverse_Recursion obj = new Reverse_Recursion();
18. int a = obj.reverse(n, count);
19. System.out.println("Reverse:"+a);
20. }
21. int reverse(int x, int length)
22. {
23. if(length == 1)
24. {
25. return x;
26. }
27. else
28. {
29. int b = x % 10;
30. x = x / 10;
31. return (int) ((b * pow(10, length - 1)) + reverse(x, --length));
32. }
33. }
34. }
Output:-
Enter the number:467
Reverse:764
Java Program to Reverse a Number without using Recursion
1. //Java Program to Reverse a Given Number Without Using Recursion
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class ReverseNumber {
7. // Function to reverse the number without using recursion
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. try {
12. System.out.println("Enter a number");
13. n = Integer.parseInt(br.readLine());
14. } catch (Exception e) {
15. System.out.println("An error occurred");
16. return;
17. }
18. int rev,i,s;
19. rev = 0;
20. for(i=n; i!=0; i/=10){
21. rev= rev*10+(i%10);
22. }
23. System.out.println("The reverse is " + rev);
24. }
25. }
Output:-
Enter a number
214224
The reverse is 422412
Java Program to Print First N Natural Numbers using Recursion
1. import java.util.Scanner;
2. public class Natural
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any number:");
9. n = s.nextInt();
10. Natural obj = new Natural();
11. System.out.print("Natural numbers till "+n+" :");
12. obj.natural(n,1);
13.
14.
15. }
16. int natural(int y, int i)
17. {
18. if(i <= y)
19. {
20. System.out.print(i+" ");
21. return(natural(y,++i));
22. }
23. return 1;
24. }
25. }
Output:-
Enter any number:8
Natural numbers till 8 :1 2 3 4 5 6 7 8
Sum of Natural Numbers using Recursion in Java
1. import java.util.Scanner;
2. public class Sum_Numbers
3. {
4. int sum = 0, j = 0;
5. public static void main(String[] args)
6. {
7. int n;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the no. of elements you want:");
10. n = s.nextInt();
11. int a[] = new int[n];
12. System.out.print("Enter all the elements you want:");
13. for(int i = 0; i < n; i++)
14. {
15. a[i] = s.nextInt();
16. }
17. Sum_Numbers obj = new Sum_Numbers();
18. int x = obj.add(a, a.length, 0);
19. System.out.println("Sum:"+x);
20. }
21. int add(int a[], int n, int i)
22. {
23. if(i < n)
24. {
25. return a[i] + add(a, n, ++i);
26. }
27. else
28. {
29. return 0;
30. }
31. }
32. }
Output:-
1. Enter the no. of elements you want:6
2. Enter all the elements you want:2
3. 3
4. 5
5. 6
6. 7
7. 1
8. Sum:24

Java Program to Find Sum of Natural Numbers using While Loop


1. public class Natural
2. {
3. public static void main(String args[])
4. {
5. int x, i = 1 ;
6. int sum = 0;
7. System.out.println("Enter Number of items :");
8. Scanner s = new Scanner(System.in);
9. x = s.nextInt();
10. while(i <= x)
11. {
12. sum = sum +i;
13. i++;
14. }
15. System.out.println("Sum of "+x+" numbers is :"+sum);
16. }
17. }
Output:-
Enter Number of items :
55
Sum of 55 numbers is :1540
For Loop Program in Java
/*
* Java Program to Print 1 to 10 Numbers using For Loop
*/

public class For_Loop


{
public static void main(String[] args)
{
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}
}
Output:-
1
2
3
4
5
6
7
8
9
10
Java Program to Print the First n Square Numbers
1. //Java Program to Print the First n square Numbers
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class PrintNSquareNumbers {
7. // Function to read n and display the numbers
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. System.out.println("Enter the value of n");
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. if(n<=0){
19. System.out.println("n should be greater than zero");
20. return;
21. }
22. System.out.println("First " + n + " square numbers are ");
23. int i;
24. for(i=1; i<=n; i++){
25. System.out.print(i*i + " ");
26. }
27. }
28. }
Output:-
Enter the value of n
15
First 15 square numbers are
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225
Java Program to Find the Sum of n Square Numbers
1. //Java Program to Find the Sum of n Square Numbers
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class SumOfNSquareNumbers {
7. // Function to read n and display the sum
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. System.out.println("Enter the value of n");
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. if(n<0){
19. System.out.println("n cannot take negative values");
20. return;
21. }
22. double sum = n*(n+1)*(2*n+1)/6;
23. System.out.println("The sum of first " + n + " squared numbers is " + sum);
24. }
25. }
Output:-
Enter the value of n
15
The sum of first 15 squared numbers is 1240.0
Java Program to Find the Sum of n Cube Numbers
1. //Java Program to Find the Sum of n Cube Numbers
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class SumOfNCubeNumbers {
7. // Function to read n and display the sum
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. System.out.println("Enter the value of n");
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. if(n<0){
19. System.out.println("n cannot take negative values");
20. return;
21. }
22. double sum = Math.pow(n*(n+1)/2,2);
23. System.out.println("The sum of first " + n + " cube numbers is " + sum);
24. }
25. }
Output:-
Enter the value of n
15
The sum of first 15 cube numbers is 14400.0
Java Program to Check Whether a Given Year is a Leap Year
import java.util.Scanner;
public class Check_Leap_Year
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter any year:");
int year = s.nextInt();
boolean flag = false;
if(year % 400 == 0)
{
flag = true;
}
else if (year % 100 == 0)
{
flag = false;
}
else if(year % 4 == 0)
{
flag = true;
}
else
{
flag = false;
}
if(flag)
{
System.out.println("Year "+year+" is a Leap Year");
}
else
{
System.out.println("Year "+year+" is not a Leap Year");
}
}
}
Output:-
Enter any year:
1800
1800 is not a Leap Year
Enter any year:
2000
2000 is a Leap Year
Java Program to Extract Last Two Digits of a Given Year
1. import java.util.Scanner;
2. public class Extract_Digit
3. {
4. public static void main(String[] args)
5. {
6. int x, y, i = 0;
7. String z = "";
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter Year:");
10. x = s.nextInt();
11. while(i < 2)
12. {
13. y = x % 10;
14. z = y + "" +z;
15. x = x / 10;
16. i++;
17. }
18. System.out.println("Last two digits:"+z);
19. }
20. }
Output:-
Enter Year:2014
Last two digits:14
Java Program to Convert Days into Years, Months and Days
1. import java.util.Scanner;
2. public class Year_Week_Day
3. {
4. public static void main(String args[])
5. {
6. int m, year, week, day;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number of days:");
9. m = s.nextInt();
10. year = m / 365;
11. m = m % 365;
12. System.out.println("No. of years:"+year);
13. week = m / 7;
14. m = m % 7;
15. System.out.println("No. of weeks:"+week);
16. day = m;
17. System.out.println("No. of days:"+day);
18. }
19. }
Output:-
Enter the number of days:756
No. of years:2
No. of weeks:3
No. of days:5
Java Program without using the Main() Function
1. public class Without_Main
2. {
3. static
4. {
5. System.out.println("Hello World!!");
6. System.exit(0);
7. }
8. //Does not work with JDK7
9. }
Output:-
Hello World!!
Java Program to Print Statement without Semicolon
1. public class Print_Without_Semicolon
2. {
3. public static void main(String[] args)
4. {
5. int i = 0;
6. if(System.out.printf("Sanfoundary!! ") == null) {}
7. for(i = 1; i < 2; System.out.println("Hello World."))
8. {
9. i++;
10. }
11. }
12. }
Output:-
Sanfoundary!! Hello World.
Java Program to Print Semicolon without using Semicolon
1. import java.util.Scanner;
2. public class Semicolon
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. char a;
8. n = 59;
9. a = (char) n;
10. System.out.println(a);
11. }
12. }
Output:-
;
Java Program to Display the ATM Transaction
1. import java.util.Scanner;
2. public class ATM_Transaction
3. {
4. public static void main(String args[] )
5. {
6. int balance = 5000, withdraw, deposit;
7. Scanner s = new Scanner(System.in);
8. while(true)
9. {
10. System.out.println("Automated Teller Machine");
11. System.out.println("Choose 1 for Withdraw");
12. System.out.println("Choose 2 for Deposit");
13. System.out.println("Choose 3 for Check Balance");
14. System.out.println("Choose 4 for EXIT");
15. System.out.print("Choose the operation you want to perform:");
16. int n = s.nextInt();
17. switch(n)
18. {
19. case 1:
20. System.out.print("Enter money to be withdrawn:");
21. withdraw = s.nextInt();
22. if(balance >= withdraw)
23. {
24. balance = balance - withdraw;
25. System.out.println("Please collect your money");
26. }
27. else
28. {
29. System.out.println("Insufficient Balance");
30. }
31. System.out.println("");
32. break;
33.
34. case 2:
35. System.out.print("Enter money to be deposited:");
36. deposit = s.nextInt();
37. balance = balance + deposit;
38. System.out.println("Your Money has been successfully depsited");
39. System.out.println("");
40. break;
41.
42. case 3:
43. System.out.println("Balance : "+balance);
44. System.out.println("");
45. break;
46.
47. case 4:
48. System.exit(0);
49. }
50. }
51. }
52. }
Output:-
Automated Teller Machine
Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for EXIT
Choose the operation you want to perform:1
Enter money to be withdrawn:2000
Please collect your money

Automated Teller Machine


Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for EXIT
Choose the operation you want to perform:3
Balance : 3000

Automated Teller Machine


Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for EXIT
Choose the operation you want to perform:4
Java Program to Get IP Address
1. import java.net.InetAddress;
2. public class IP_Address
3. {
4. public static void main(String args[]) throws Exception
5. {
6. InetAddress IP = InetAddress.getLocalHost();
7. System.out.println("IP of my system is := "+IP.getHostAddress());
8. }
9. }
Output:-
IP of my system is := 127.0.1.1
Java Program to Illustrate how User Authentication is Done
1. import java.util.Scanner;
2. public class User_Authentication
3. {
4. public static void main(String args[])
5. {
6. String username, password;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter username:");//username:user
9. username = s.nextLine();
10. System.out.print("Enter password:");//password:user
11. password = s.nextLine();
12. if(username.equals("user") && password.equals("user"))
13. {
14. System.out.println("Authentication Successful");
15. }
16. else
17. {
18. System.out.println("Authentication Failed");
19. }
20. }
21. }
Output:-
Enter username:user
Enter password:user
Authentication Successful

Enter username:abcd
Enter password:1234
Authentication Failed
Java Program to Shutdown Computer in Linux
1. import java.io.IOException;
2. import java.util.Scanner;
3. public class Shutdown_System
4. {
5. public static void main(String args[]) throws IOException
6. {
7. int sec;
8. String operatingSystem = System.getProperty("os.name");
9. System.out.println("Name of Operating System:"+operatingSystem);
10. if(operatingSystem.equals("Linux"))
11. {
12. Runtime runtime = Runtime.getRuntime();
13. Scanner s = new Scanner(System.in);
14. System.out.print("Enter the no. of seconds after which you want your
computer to shutdown:");
15. sec = s.nextInt();
16. Process proc = runtime.exec("shutdown -h -t "+sec);
17. System.exit(0);
18. }
19. else
20. {
21. System.out.println("Unsupported operating system.");
22. }
23. }
24. }
Output:-
Name of Operating System:Linux
Enter the no. of seconds after which you want your computer to shutdown:5
Factorial Program in Java
/*
* Java program to find the factorial of a given number using for loop.
*/

import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{
int n, fact = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter the Number: ");
n = s.nextInt();
for(int i = 1; i <= n; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+n+" is "+fact);
}
}
Output:-
Enter the Number: 8
Factorial of 8 is 40320
// Java program to calculate factorial of a number using while loop

import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{
int n;
System.out.println("Enter the number: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
long fact = 1;
int i = 1;
while(i<=n)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
}
Output:-
Enter the number: 7
Factorial of 7 is: 5040
/*
* Java program to find the factorial of a number using Recursion
*/

import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{
int n, mul;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
n = s.nextInt();
Factorial obj = new Factorial();
mul = obj.fact(n);
System.out.println("Factorial of "+n+" :"+mul);
}
int fact(int x)
{
if(x > 1)
{
return(x * fact(x - 1));
}
return 1;
}
}
Output:-
Enter the number: 9
The Factorial of 9 is 362880
Java Program to Find the Factorial of a Number Without Recursion
1. import java.util.Scanner;
2. public class Factorial
3. {
4. public static void main(String[] args)
5. {
6. int n, mul = 1;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any integer:");
9. n = s.nextInt();
10. for(int i = 1; i <= n; i++)
11. {
12. mul = mul * i;
13. }
14. System.out.println("Factorial of "+n+" :"+mul);
15. }
16. }
Output:-
Enter any integer:8
Factorial of 8 :40320
Fibonacci Series Program in Java
/*
* Fibonacci Series in Java using For Loop
*/
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
}
}
}
Output:-
Enter value of n: 5
Fibonacci Series: 0 1 1 2 3
/*
* Fibonacci Series in Java using While Loop
*/

import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1, i = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
while(i<=n)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
i++;
}
}
}
Output:-
Enter value of n: 8
Fibonacci Series: 0 1 1 2 3 5 8 13
/*
* Java Program to Implement Efficient O(log n) Fibonacci generator
*/

import java.util.Scanner;
import java.math.BigInteger;

/** Class FibonacciGenerator **/


public class FibonacciGenerator
{
/** function to generate nth fibonacci number **/
public void genFib(long n)
{
BigInteger arr1[][] = {{BigInteger.ONE, BigInteger.ONE},
{BigInteger.ONE, BigInteger.ZERO}};
if (n == 0)
System.out.println("\nFirst Fibonacci number = 0");
else
{
power(arr1, n - 1);
System.out.println("\n"+ n +" th Fibonacci number = "+ arr1[0][0]);
}
}
/** function raise matrix to power n recursively **/
private void power(BigInteger arr1[][], long n)
{
if (n == 0 || n == 1)
return;
BigInteger arr2[][] = {{BigInteger.ONE, BigInteger.ONE},
{BigInteger.ONE, BigInteger.ZERO}};
power(arr1, n / 2);
multiply(arr1, arr1);
if (n % 2 != 0)
multiply(arr1, arr2);
}
/** function to multiply two 2 d matrices **/
private void multiply(BigInteger arr1[][], BigInteger arr2[][])
{
BigInteger x = (arr1[0][0].multiply(arr2[0][0])).add(arr1[0][1].multiply(arr2[1][0]));
BigInteger y = (arr1[0][0].multiply(arr2[0][1])).add(arr1[0][1].multiply(arr2[1][1]));
BigInteger z = (arr1[1][0].multiply(arr2[0][0])).add(arr1[1][1].multiply(arr2[1][0]));
BigInteger w = (arr1[1][0].multiply(arr2[0][1])).add(arr1[1][1].multiply(arr2[1][1]));
arr1[0][0] = x;
arr1[0][1] = y;
arr1[1][0] = z;
arr1[1][1] = w;
}
/** Main function **/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Efficient Fibonacci Generator\n");
System.out.println("Enter number n to find nth fibonacci number\n");
long n = scan.nextLong();
FibonacciGenerator fg = new FibonacciGenerator();
fg.genFib(n);
}
}
Output:-
Efficient Fibonacci Generator

Enter number n to find nth fibonacci number

1000

1000 th Fibonacci number =


43466557686937456435688527675040625802564660517371780
402481729089536555417949051890403879840079255169295922593080322634775209689
62323
987332247116164299644090653318793829896964992851600370447613779516684922887
5
Java Program to Print First 100 Fibonacci Numbers
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
System.out.print("Fibonacci Series:");
for(int i = 1; i <= 100; i++)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
}
}
}
Output:-
Fibonacci Series:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309
3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141
267914296 433494437 701408733 1134903170 1836311903 -1323752223 512559680 -
811192543 -298632863 -1109825406 -1408458269 1776683621 368225352 2144908973 -
1781832971 363076002 -1418756969 -1055680967 1820529360 764848393 -1709589543 -
944741150 1640636603 695895453 -1958435240 -1262539787 1073992269 -188547518
885444751 696897233 1582341984 -2015728079 -433386095 1845853122 1412467027 -
1036647147 375819880 -660827267 -285007387 -945834654 -1230842041 2118290601
887448560 -1289228135 -401779575 -1691007710 -2092787285 511172301 -1581614984 -
1070442683 1642909629 572466946 -2079590721 -1507123775 708252800 -798870975 -
90618175 -889489150
Java Program to Implement Efficient O(log n) Fibonacci Generator
1. /**
2. ** Java Program to Implement Efficient O(log n) Fibonacci generator
3. **/
4.
5. import java.util.Scanner;
6. import java.math.BigInteger;
7.
8. /** Class FibonacciGenerator **/
9. public class FibonacciGenerator
10. {
11. /** function to generate nth fibonacci number **/
12. public void genFib(long n)
13. {
14. BigInteger arr1[][] = {{BigInteger.ONE, BigInteger.ONE}, {BigInteger.ONE,
BigInteger.ZERO}};
15. if (n == 0)
16. System.out.println("\nFirst Fibonacci number = 0");
17. else
18. {
19. power(arr1, n - 1);
20. System.out.println("\n"+ n +" th Fibonacci number = "+ arr1[0][0]);
21. }
22. }
23. /** function raise matrix to power n recursively **/
24. private void power(BigInteger arr1[][], long n)
25. {
26. if (n == 0 || n == 1)
27. return;
28. BigInteger arr2[][] = {{BigInteger.ONE, BigInteger.ONE}, {BigInteger.ONE,
BigInteger.ZERO}};
29. power(arr1, n / 2);
30. multiply(arr1, arr1);
31. if (n % 2 != 0)
32. multiply(arr1, arr2);
33. }
34. /** function to multiply two 2 d matrices **/
35. private void multiply(BigInteger arr1[][], BigInteger arr2[][])
36. {
37. BigInteger x =
(arr1[0][0].multiply(arr2[0][0])).add(arr1[0][1].multiply(arr2[1][0]));
38. BigInteger y =
(arr1[0][0].multiply(arr2[0][1])).add(arr1[0][1].multiply(arr2[1][1]));
39. BigInteger z =
(arr1[1][0].multiply(arr2[0][0])).add(arr1[1][1].multiply(arr2[1][0]));
40. BigInteger w =
(arr1[1][0].multiply(arr2[0][1])).add(arr1[1][1].multiply(arr2[1][1]));
41. arr1[0][0] = x;
42. arr1[0][1] = y;
43. arr1[1][0] = z;
44. arr1[1][1] = w;
45. }
46. /** Main function **/
47. public static void main(String[] args)
48. {
49. Scanner scan = new Scanner(System.in);
50. System.out.println("Efficient Fibonacci Generator\n");
51. System.out.println("Enter number n to find nth fibonacci number\n");
52. long n = scan.nextLong();
53. FibonacciGenerator fg = new FibonacciGenerator();
54. fg.genFib(n);
55. }
56. }
Output:-
Efficient Fibonacci Generator

Enter number n to find nth fibonacci number

1000
1000 th Fibonacci number =
43466557686937456435688527675040625802564660517371780
402481729089536555417949051890403879840079255169295922593080322634775209689
62323
987332247116164299644090653318793829896964992851600370447613779516684922887
5
Java Program to Convert Binary to Decimal
/*
* Java Program to Convert Binary to Decimal
*/

import java.util.Scanner;
class Binary_Decimal
{
Scanner scan;
int num;
void getVal()
{
System.out.println("Binary to Decimal");
scan = new Scanner(System.in);
System.out.println("\nEnter the number :");
num = Integer.parseInt(scan.nextLine(), 2);
}
void convert()
{
String decimal = Integer.toString(num);
System.out.println("Decimal Value is : " + decimal);
}
}
class MainClass
{
public static void main(String args[])
{
Binary_Decimal obj = new Binary_Decimal();
obj.getVal();
obj.convert();
}
}
Output:-
Binary to Decimal

Enter the number :


1010
Decimal Value is : 10
Java Program to Convert Binary to Hexadecimal
1. import java.util.Scanner;
2. class Binary_Hexa
3. {
4. Scanner scan;
5. int num;
6. void getVal()
7. {
8. System.out.println("Binary to HexaDecimal");
9. scan = new Scanner(System.in);
10. System.out.println("\nEnter the number :");
11. num = Integer.parseInt(scan.nextLine(), 2);
12. }
13. void convert()
14. {
15. String hexa = Integer.toHexString(num);
16. System.out.println("HexaDecimal Value is : " + hexa);
17. }
18. }
19. class Main_Class
20. {
21. public static void main(String... q)
22. {
23. Binary_Hexa obj = new Binary_Hexa();
24. obj.getVal();
25. obj.convert();
26. }
27. }
Output:-
Binary to HexaDecimal

Enter the number :


1010
HexaDecimal Value is : a
Java Program to Convert Binary to Octal
1. import java.util.Scanner;
2. class Binary_Octal
3. {
4. Scanner scan;
5. int num;
6. void getVal()
7. {
8. System.out.println("Binary to Octal");
9. scan = new Scanner(System.in);
10. System.out.println("\nEnter the number :");
11. num = Integer.parseInt(scan.nextLine(), 2);
12. }
13. void convert()
14. {
15. String octal = Integer.toOctalString(num);
16. System.out.println("Octal Value is : " + octal);
17. }
18. }
19. class Main_Class
20. {
21. public static void main(String... d)
22. {
23. Binary_Octal obj = new Binary_Octal();
24. obj.getVal();
25. obj.convert();
26. }
27. }
Output:-
Binary to Octal

Enter the number :


1010
Octal Value is : 12
Java Program to Convert Binary to Gray Code using Recursion
1. import static java.lang.StrictMath.pow;
2. import java.util.Scanner;
3. public class Binary_Gray_Recursion
4. {
5. public static void main(String[] args)
6. {
7. int n, result = 0;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter Binary number:");
10. n = s.nextInt();
11. Binary_Gray_Recursion obj = new Binary_Gray_Recursion();
12. result = obj.GrayCode(n, 0);
13. System.out.println("Gray Code:"+result);
14. }
15. int GrayCode(int x,int i)
16. {
17. int a, b, result = 0;
18. if(x != 0)
19. {
20. a = x % 10;
21. x = x / 10;
22. b = x % 10;
23. if((a & ~ b) == 1 || (~ a & b) == 1)
24. {
25. result = (int) (result + pow(10,i));
26. }
27. return GrayCode(x, ++i) + result;
28. }
29. return 0;
30. }
31. }
Output:-
Enter Binary number:1001
Gray Code:1101
Java Program to Convert Binary to Gray Code without Recursion
1. import static java.lang.StrictMath.pow;
2. import java.util.Scanner;
3. public class Binary_Gray
4. {
5. public static void main(String[] args)
6. {
7. int a, b, x, result = 0, i = 0;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter Binary number:");
10. x = s.nextInt();
11. while(x != 0)
12. {
13. a = x % 10;
14. x = x / 10;
15. b = x % 10;
16. if((a & ~ b) == 1 || (~ a & b) == 1)
17. {
18. result = (int) (result + pow(10,i));
19. }
20. i++;
21. }
22. System.out.println("Gray Code:"+result);
23. }
24. }
Output:-
Enter Binary number:1001
Gray Code:1101
Java Program to Convert Octal to Binary
1. import java.util.Scanner;
2. class Octal_Binary
3. {
4. Scanner scan;
5. int num;
6. void getVal()
7. {
8. System.out.println("Octal to Binary");
9. scan = new Scanner(System.in);
10.
11. System.out.println("\nEnter the number :");
12. num = Integer.parseInt(scan.nextLine(), 8);
13. }
14.
15. void convert()
16. {
17. String binary = Integer.toBinaryString(num);
18. System.out.println("Binary Value is : " + binary);
19. }
20. }
21. class MainClass
22. {
23. public static void main(String args[])
24. {
25. Octal_Binary obj = new Octal_Binary();
26. obj.getVal();
27. obj.convert();
28. }
29. }
Output:-
Octal to Binary

Enter the number :


10
Binary Value is : 1000
Java Program to Convert Octal to Decimal
1. import java.util.Scanner;
2. class Octal_Decimal
3. {
4. Scanner scan;
5. int num;
6. void getVal()
7. {
8. System.out.println("Octal to Decimal");
9. scan = new Scanner(System.in);
10. System.out.println("\nEnter the number :");
11. num = Integer.parseInt(scan.nextLine(), 8);
12. }
13. void convert()
14. {
15. String decimal = Integer.toString(num);
16. System.out.println("Decimal Value is : " + decimal);
17. }
18. }
19. class MainClass
20. {
21. public static void main(String args[])
22. {
23. Octal_Decimal obj = new Octal_Decimal();
24. obj.getVal();
25. obj.convert();
26. }
27. }
Output:-
Octal to Decimal

Enter the number :


10
Decimal Value is : 8
Java Program to Convert Decimal to Binary, Octal and Hexadecimal
1. class Convert
2. {
3. Scanner scan;
4. int num;
5. void getVal()
6. {
7. System.out.println("Decimal to HexaDecimal,Octal and Binary");
8. scan = new Scanner(System.in);
9. System.out.println("\nEnter the number :");
10. num = Integer.parseInt(scan.nextLine());
11. }
12. void convert()
13. {
14. String hexa = Integer.toHexString(num);
15. System.out.println("HexaDecimal Value is : " + hexa);
16. String octal = Integer.toOctalString(num);
17. System.out.println("Octal Value is : " + octal);
18. String binary = Integer.toBinaryString(num);
19. System.out.println("Binary Value is : " + binary);
20. }
21. }
22. class Decimal_Conversion
23. {
24. public static void main(String args[])
25. {
26. Convert obj = new Convert();
27. obj.getVal();
28. obj.convert();
29. }
30. }
Output:-
Decimal to HexaDecimal,Octal and Binary

Enter the number :


121
HexaDecimal Value is : 79
Octal Value is : 171
Binary Value is : 1111001
Java Program to Convert Decimal to Binary using Recursion
1. import java.util.Scanner;
2. public class Convert
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. String x;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter any decimal number:");
10. n = s.nextInt();
11. Convert obj = new Convert();
12. x = obj.binary(n);
13. System.out.println("Binary number:"+x);
14. }
15. String binary(int y)
16. {
17. int a;
18. if(y > 0)
19. {
20. a = y % 2;
21. return (binary(y / 2) + "" +a);
22. }
23. return "";
24. }
25. }
Output:-
Enter any decimal number:25
Binary number:11001
Java Program to Convert Hexadecimal to Binary
1. import java.util.Scanner;
2. class Hexa_Binary
3. {
4. Scanner scan;
5. int num;
6. void getVal()
7. {
8. System.out.println("HexaDecimal to Binary");
9. scan = new Scanner(System.in);
10. System.out.println("\nEnter the number :");
11. num = Integer.parseInt(scan.nextLine(), 16);
12. }
13. void convert()
14. {
15. String binary = Integer.toBinaryString(num);
16. System.out.println("Binary Value is : " + binary);
17. }
18. }
19. class MainClass
20. {
21. public static void main(String args[])
22. {
23. Hexa_Binary obj = new Hexa_Binary();
24. obj.getVal();
25. obj.convert();
26. }
27. }
Output:-
HexaDecimal to Binary

Enter the number :


20
Binary Value is : 100000
Hexadecimal to Decimal in Java
1. /*
2. * Hexadecimal to Decimal Conversion in Java
3. */
4.
5. import java.util.Scanner;
6. class Hexa_Decimal
7. {
8. Scanner scan;
9. int num;
10. void getVal()
11. {
12. System.out.println("HexaDecimal to Decimal");
13. scan = new Scanner(System.in);
14. System.out.println("Enter the number :");
15. num = Integer.parseInt(scan.nextLine(), 16);
16. }
17. void convert()
18. {
19. String decimal = Integer.toString(num);
20. System.out.println("Decimal Value is : " + decimal);
21. }
22. }
23. class Hexa_Decimal_Main
24. {
25. public static void main(String args[])
26. {
27. Hexa_Decimal obj = new Hexa_Decimal();
28. obj.getVal();
29. obj.convert();
30. }
31. }
Output:-
HexaDecimal to Decimal
Enter the number :
12
Decimal Value is : 18
Java Program to Convert Fahrenheit to Celsius
1. import java.util.Scanner;
2. public class Fahrenheit_Celsius
3. {
4. public static void main(String[] args)
5. {
6. double celsius, fahrenheit;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter temperature in Fahrenheit:");
9. fahrenheit = s.nextDouble();
10. celsius = (fahrenheit-32)*(0.5556);
11. System.out.println("Temperature in Celsius:"+celsius);
12. }
13. }
Output:-
Enter temperature in Fahrenheit:15
Temperature in Celsius:-9.4452
Java Program to Print Diamond Pattern
1. /*
2. * Diamond Pattern Program in Java
3. */
4.
5. import java.util.Scanner;
6. public class Diamond
7. {
8. public static void main(String args[])
9. {
10. int n, i, j, space = 1;
11. System.out.print("Enter the number of rows: ");
12. Scanner s = new Scanner(System.in);
13. n = s.nextInt();
14. space = n - 1;
15. for (j = 1; j <= n; j++)
16. {
17. for (i = 1; i <= space; i++)
18. {
19. System.out.print(" ");
20. }
21. space--;
22. for (i = 1; i <= 2 * j - 1; i++)
23. {
24. System.out.print("*");
25. }
26. System.out.println("");
27. }
28. space = 1;
29. for (j = 1; j <= n - 1; j++)
30. {
31. for (i = 1; i <= space; i++)
32. {
33. System.out.print(" ");
34. }
35. space++;
36. for (i = 1; i <= 2 * (n - j) - 1; i++)
37. {
38. System.out.print("*");
39. }
40. System.out.println("");
41. }
42. }
43. }
Output:-
Enter the number of rows: 5

*
***
*****
*******
*********
***********
*************
***************
*************
***********
*********
*******
*****
***
*
Enter the number of rows: 5
*
***
*****
*******
*********
*******
*****
***
*
Java Program to Print Floyd’s Triangle
/*
* Java Program to Print Floyd’s Triangle using for loop
*/

import java.util.Scanner;

class Floyd
{
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows of floyd's triangle you want");
n = in.nextInt();
System.out.println("Floyd's triangle :-");
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}
}
}
Output:-
Enter the number of rows of floyd's triangle you want
5
Floyd's triangle :-
1
23
456
7 8 9 10
11 12 13 14 15
Enter the number of rows: 12
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
Java Program to Print Pascal’s Triangle
//Java program to print Pascal's Triangle of a given size.

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PascalTriangle {
// Function to calculate factorial of a number
static int factorial(int n)
{
int fact = 1;
int i;
for(i=1; i<n; i++)
{
fact*=i;
}
return i;
}
// Function to display the pascal triangle
static void display(int n)
{
int i;
int coefficient;
int line;
for(line=1;line<=n;line++)
{
for(i=0;i<=line;i++)
{
System.out.print((factorial(line)/factorial(line-i) * factorial(i)) + " ");
}
System.out.println();
}
}
// main Function to read user input
public static void main(String[] args){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("Enter the size");
try {
n = Integer.parseInt(br.readLine());
}
catch(Exception e){
System.out.println("Invalid Input");
return;
}
System.out.println("The Pascal's Triangle is");
display(n);
}
}
Output:-
Enter the size
4
The Pascal's Triangle is
1
11
121
1331
Enter the size
12
The Pascal's Triangle is
1
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
Star Pattern Program in Java
1. //Java Program to Print * in Triangular Pattern
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Pattern2 {
7. // Function to display the pattern
8. public static void main(String[] args) {
9. int i,j,k,n;
10. System.out.println("Enter the number of lines");
11. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. System.out.println("The triangular pattern is");
19. int space = n-2;
20. for(i=1; i<=n; i++){
21. for(k=space;k>=0;k--){
22. System.out.print(" ");
23. }
24. space--;
25. for(j = 1; j<=i; j++){
26. System.out.print("* ");
27. }
28. System.out.println();
29. }
30. }
31. }
Output:-
Case 1 (Simple Test Case):

Enter the number of lines


8
The triangular pattern is
*
**
***
****
*****
******
*******
********
Pyramid Program in Java
1. //Java Program to Print 1,2,3,4...in Triangular Pattern
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Pattern1 {
7. // Function to display the pattern
8. public static void main(String[] args) {
9. int i,j,k,n;
10. System.out.println("Enter the number of lines");
11. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. System.out.println("The triangular pattern is");
19. int space = n-2;
20. for(i=1; i<=n; i++){
21. for(k=space;k>=0;k--){
22. System.out.print(" ");
23. }
24. space--;
25. for(j = 1; j<=i; j++){
26. System.out.print(j + " ");
27. }
28. System.out.println();
29. }
30. }
31. }
Output:-
Case 1 (Simple Test Case):

Enter the number of lines


10
The triangular pattern is
1
12
123
1234
12345
123456
1234567
12345678
123456789
1 2 3 4 5 6 7 8 9 10
Java Program to Print the Multiplication Table in a Triangle Form
1. //Java Program to Print the Multiplication Table in Triangular Form
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class TableInTriangularForm {
7. // Function to print tables in triangular form
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. System.out.println("Enter the value of n");
12. try{
13. n = Integer.parseInt(br.readLine());
14. }catch(Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. int i,j;
19. System.out.println("The table in triangular form is");
20. for(i=1; i<=n; i++){
21. System.out.printf("%2d ",i);
22. }
23. System.out.println();
24. for(i=1; i<=n; i++){
25. for(j=1; j<=i; j++){
26. System.out.printf("%2d ",i*j);
27. }
28. System.out.println();
29. }
30. }
31. }
Output:-
Enter the value of n
10
The table in triangular form is
1 2 3 4 5 6 7 8 9 10
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100
Java Program to Convert Integer Values into Binary
1. import java.util.Scanner;
2. public class Decimal_Binary
3. {
4. public static void main(String[] args)
5. {
6. int n, m;
7. String x = "";
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the Decimal Number:");
10. n = s.nextInt();
11. while(n > 0)
12. {
13. int a = n % 2;
14. x = a + x;
15. n = n / 2;
16. }
17. System.out.println(x);
18. }
19. }
Output:-
Enter the Decimal Number:19
10011
Java Program to Convert Integer Values into Byte, Character, Float
1. import java.util.Scanner;
2. public class Integer_Conversion
3. {
4. public static void main(String[] args)
5. {
6. int a;
7. byte b;
8. char c;
9. float d;
10. Scanner s = new Scanner(System.in);
11. System.out.print("Enter any integer:");
12. a = s.nextInt();
13. b = (byte) a;
14. System.out.println("Conversion into byte:"+b);
15. c = (char) a;
16. System.out.println("Conversion into char:"+c);
17. d = a;
18. System.out.println("Conversion into float:"+d);
19. }
20. }
Output:-
Enter any integer:97
Conversion into byte:97
Conversion into char:a
Conversion into float:97.0
Java Program to Convert Long Values into Byte
1. import java.util.Scanner;
2. public class Long_Byte
3. {
4. public static void main(String[] args)
5. {
6. long a;
7. byte b;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter any long value:");
10. a = s.nextLong();
11. b = (byte) a;
12. System.out.println("Conversion into byte:"+b);
13. }
14. }
Output:-
Enter any long value:12548
Conversion into byte:4
Java Program to Illustrate use of Binary Literals
1. import java.util.Scanner;
2. public class Binary_Literal
3. {
4. public static void main(String[] args)
5. {
6. byte aB = 0b00100001;
7. short aS = 0b10100010100;
8. int a1 = 0b10110;
9. int a2 = 0b101;
10. int a3 = 0b1011;
11. int aI=a2+a3;
12. System.out.println("Byte value:"+aB);
13. System.out.println("Short value:"+aS);
14. System.out.println("Integer value:"+a1);
15. System.out.println("Result:"+aI);
16. }
17. }
Output:-
Byte value:33
Short value:1300
Integer value:22
Result:16
Java Program to use Underscores in Numeric Literal
1. import java.util.Scanner;
2. public class Underscore_Numeric
3. {
4. public static void main(String[] args)
5. {
6. // int a1 = _52; Invalid; cannot put underscores at the start of a
literal
7. int a2 = 5_2; // OK (decimal literal)
8. System.out.println(a2);
9. // int a3 = 52_; Invalid; cannot put underscores at the end of a literal
10. int a4 = 5_______2; // OK (decimal literal)
11. System.out.println(a4);
12. // int a5 = 0_x52; Invalid; cannot put underscores in the 0x radix
prefix
13. // int a6 = 0x_52; Invalid; cannot put underscores at the beginning of
a number
14. int a7 = 0x5_2; // OK (hexadecimal literal)
15. System.out.println(a7);
16. // int a8 = 0x52_; Invalid; cannot put underscores at the end of a
number
17. int a9 = 0_52; // OK (octal literal)
18. System.out.println(a9);
19. int a10 = 05_2; // OK (octal literal)
20. System.out.println(a10);
21. // int a11 = 052_; Invalid; cannot put underscores at the end of a
number
22. // float b1 = 3_.1415F; Invalid; cannot put underscores adjacent to a
decimal point
23. // float b2 = 3._1415F; Invalid; cannot put underscores adjacent to a
decimal point
24. float b3 = 3.1_415F; // OK (float literal)
25. System.out.println(b3);
26. // long c1 = 9999_L; Invalid; cannot put underscores prior to an L
suffix
27. long c2 = 99_99L; // OK (long literal)
28. System.out.println(c2);
29. }
30. }
Output:-
52
52
82
42
42
3.1415
9999
Java Program to Perform Arithmetic Operations
/*
* Java Program to Perform Arithmetic Operations
*/

import java.util.Scanner;
public class Arithmetic_Operators
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
while(true)
{
System.out.println("");
System.out.println("Enter the two numbers to perform operations ");
System.out.print("Enter the first number : ");
int x = s.nextInt();
System.out.print("Enter the second number : ");
int y = s.nextInt();
System.out.println("Choose the operation you want to perform ");
System.out.println("Choose 1 for ADDITION");
System.out.println("Choose 2 for SUBTRACTION");
System.out.println("Choose 3 for MULTIPLICATION");
System.out.println("Choose 4 for DIVISION");
System.out.println("Choose 5 for MODULUS");
System.out.println("Choose 6 for EXIT");
int n = s.nextInt();
switch(n)
{
case 1:
int add;
add = x + y;
System.out.println("Addition of Two Numbers : "+add);
break;

case 2:
int sub;
sub = x - y;
System.out.println("Subtraction of Two Numbers : "+sub);
break;

case 3:
int mul;
mul = x * y;
System.out.println("Multiplication of Two Numbers : "+mul);
break;

case 4:
float div;
div = (float) x / y;
System.out.print("Division of Two Numbers : "+div);
break;
case 5:
int mod;
mod = x % y;
System.out.println("Modulus of Two Numbers : "+mod);
break;

case 6:
System.exit(0);
}
}
}
}
Output:-

Test case 1 (Addition): In this case, the values “12” and “45” were entered, and we will
execute the addition operation.
$ javac Arithmetic_Operators.java
$ java Arithmetic_Operators

Enter the two numbers to perform operations


Enter the first number : 12
Enter the second number : 45
Choose the operation you want to perform
Choose 1 for ADDITION
Choose 2 for SUBTRACTION
Choose 3 for MULTIPLICATION
Choose 4 for DIVISION
Choose 5 for MODULUS
Choose 6 for EXIT
1
Addition of Two Numbers : 57
Test case 2 (Subtraction): The values “50” and “30” were entered as input for this case, and
we will perform the subtraction operation.
$ javac Arithmetic_Operators.java
$ java Arithmetic_Operators

Enter the two numbers to perform operations


Enter the first number : 50
Enter the second number : 30
Choose the operation you want to perform
Choose 1 for ADDITION
Choose 2 for SUBTRACTION
Choose 3 for MULTIPLICATION
Choose 4 for DIVISION
Choose 5 for MODULUS
Choose 6 for EXIT
2
Subtraction of Two Numbers : 20
Test case 3 (Multiplication): In this case, the numbers “56” and “42” were entered as input,
and the multiplication operation will be performed.
$ javac Arithmetic_Operators.java
$ java Arithmetic_Operators

Enter the two numbers to perform operations


Enter the first number : 56
Enter the second number : 42
Choose the operation you want to perform
Choose 1 for ADDITION
Choose 2 for SUBTRACTION
Choose 3 for MULTIPLICATION
Choose 4 for DIVISION
Choose 5 for MODULUS
Choose 6 for EXIT
3
Multiplication of Two Numbers : 2352
Test case 4 (Division): In this case, the numbers “30” and “5” were entered as input, and the
division operation will be performed.
$ javac Arithmetic_Operators.java
$ java Arithmetic_Operators

Enter the two numbers to perform operations


Enter the first number : 30
Enter the second number : 5
Choose the operation you want to perform
Choose 1 for ADDITION
Choose 2 for SUBTRACTION
Choose 3 for MULTIPLICATION
Choose 4 for DIVISION
Choose 5 for MODULUS
Choose 6 for EXIT
4
Division of Two Numbers : 6
Test case 5 (Modulus): In this case, the numbers “30” and “5” were entered as input, and the
modulus operation will be performed.
$ javac Arithmetic_Operators.java
$ java Arithmetic_Operators
Enter the two numbers to perform operations
Enter the first number : 30
Enter the second number : 4
Choose the operation you want to perform
Choose 1 for ADDITION
Choose 2 for SUBTRACTION
Choose 3 for MULTIPLICATION
Choose 4 for DIVISION
Choose 5 for MODULUS
Choose 6 for EXIT
5
Modulus of Two Numbers : 2
Java Program to Perform Relational Operations
1. import java.util.Scanner;
2. public class Relational_Operators
3. {
4. public static void main(String args[])
5. {
6. Scanner s= new Scanner(System.in);
7. System.out.print("Enter first integer:");
8. int a = s.nextInt();
9. System.out.print("Enter second integer:");
10. int b = s.nextInt();
11. System.out.println("a == b : " + (a == b) );
12. System.out.println("a != b : " + (a != b) );
13. System.out.println("a > b : " + (a > b) );
14. System.out.println("a < b : " + (a < b) );
15. System.out.println("b >= a : " + (b >= a) );
16. System.out.println("b <= a : " + (b <= a) );
17. }
18. }
Output:-
Enter first integer:25
Enter second integer:30
a == b : false
a != b : true
a > b : false
a < b : true
b >= a : true
b <= a : false
Java Program to Illustrate Use of Various Boolean Operators
1. import java.util.Scanner;
2. public class Boolean_Operators
3. {
4. public static void main(String args[])
5. {
6. Scanner s = new Scanner(System.in);
7. System.out.print("Enter a:");
8. boolean a = s.nextBoolean();
9. System.out.print("Enter b:");
10. boolean b = s.nextBoolean();
11. boolean c = a | b;
12. boolean d = a & b;
13. boolean e = a ^ b;
14. boolean f = (!a & b) | (a & !b);
15. boolean g = !a;
16. System.out.println("a = " + a);
17. System.out.println("b = " + b);
18. System.out.println("a|b = " + c);
19. System.out.println("a&b = " + d);
20. System.out.println("a^b = " + e);
21. System.out.println("!a&b|a&!b = " + f);
22. System.out.println("!a = " + g);
23. }
24. }
Output:-
Enter a:true
Enter b:false
a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false
Java Program to Find Largest of Three Numbers using Ternary Operator
1. import java.util.Scanner;
2. public class Largest_Ternary
3. {
4. public static void main(String[] args)
5. {
6. int a, b, c, d;
7. Scanner s = new Scanner(System.in);
8. System.out.println("Enter all three numbers:");
9. a = s.nextInt();
10. b = s.nextInt();
11. c = s.nextInt();
12. d = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
13. System.out.println("Largest Number:"+d);
14. }
15. }
Output:-
Enter all three numbers:
5
6
7
Largest Number:7
Java Program to Illustrate Use of Pre and Post Increment and Decrement Operators
1. import java.util.Scanner;
2. public class Increment_Decrement
3. {
4. public static void main(String[] args)
5. {
6. int a, b, c, d, e;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter any integer a:");
9. a = s.nextInt();
10. b = ++a;
11. System.out.println("Result after Pre Increment a:"+a);
12. System.out.println("Result after Pre Increment b:"+b);
13. c = a++;
14. System.out.println("Result after Pre Increment a:"+a);
15. System.out.println("Result after Post Increment c:"+c);
16. d = --a;
17. System.out.println("Result after Pre Increment a:"+a);
18. System.out.println("Result after Pre Decrement d:"+d);
19. e = a--;
20. System.out.println("Result after Pre Increment a:"+a);
21. System.out.println("Result after Post Decrement e:"+e);
22. }
23. }
Output:-
Enter any integer a:12
Result after Pre Increment a:13
Result after Pre Increment b:13
Result after Pre Increment a:14
Result after Post Increment c:13
Result after Pre Increment a:13
Result after Pre Decrement d:13
Result after Pre Increment a:12
Result after Post Decrement e:13
Java Program to Add Two Complex Numbers
1. //Java Program to Add Two Complex Numbers
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class ComplexNumbers {
7. // Main function to read two complex numbers and add them
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double i1,j1,i2,j2;
11. System.out.println("Enter the real part and
12. imaginary part of the first complex number");
13. try{
14. i1=Double.parseDouble(br.readLine());
15. j1=Double.parseDouble(br.readLine());
16. }catch (Exception e){
17. System.out.println("An error occurred");
18. return;
19. }
20. System.out.println("Enter the real part and
21. imaginary part of the second complex number");
22. try{
23. i2=Double.parseDouble(br.readLine());
24. j2=Double.parseDouble(br.readLine());
25. }catch (Exception e){
26. System.out.println("An error occurred");
27. return;
28. }
29. System.out.println("The first complex number is "
30. + i1 + " + i(" + j1 + ")");
31. System.out.println("The second complex number is "
32. + i2 + " + i(" + j2 + ")");
33. System.out.println("The sum of the two complex numbers is "
34. + (i1 + i2) + " + i(" + (j1 + j2) + ")");
35. }
36. }
Output:-
Enter the real part and imaginary part of the first complex number
4
6
Enter the real part and imaginary part of the second complex number
-5
2
The first complex number is 4.0 + i(6.0)
The second complex number is -5.0 + i(2.0)
The sum of the two complex numbers is -1.0 + i(8.0)
Java Program to Find Power of a Number
import java.util.Scanner;
public class Power
{
public static void main(String args[])
{
int x;
double y,z;
System.out.print("Enter any number: ");
Scanner s = new Scanner(System.in);
x = s.nextInt();
y = Math.pow(x , 2);
z = Math.pow(x , 3);
System.out.println("Square of "+x+":"+y);
System.out.println("Cube of "+x+":"+z);
}
}
Output:-
Enter any number: 5
Square of 5:25.0
Cube of 5:125.0
Power Function in Java
1. // Java Program to Implement the pow() Function
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Power {
7. // Function to calculate power of x raised to n
8. static double pow(double x, int n){
9. if(n<0){
10. return pow(1/x,-n);
11. }
12. if(n==1)
13. return x;
14. else if(n%2 == 0){
15. double y = pow(x,n/2);
16. return y*y;
17. }
18. double y = pow(x,n/2);
19. return y*y*x;
20. }
21. // Function to read user input
22. public static void main(String[] args) {
23. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
24. double x;
25. int n;
26. try {
27. System.out.println("Enter the number");
28. x = Double.parseDouble(br.readLine());
29. System.out.println("Enter the exponent (in integer)");
30. n = Integer.parseInt(br.readLine());
31. } catch (Exception e) {
32. System.out.println("An error occurred");
33. return;
34. }
35. double result = pow(x,n);
36. System.out.printf(x + " raised to " + n + " is %f", result);
37. }
38. }
Output:-
Case 1 (Simple Test Case):

Enter the number


3.5
Enter the exponent (in integer)
5
3.5 raised to 5 is 525.218750

Case 2 (Simple Test Case - another example):

Enter the number


2
Enter the exponent (in integer)
-2
2.0 raised to -2 is 0.250000
Java Program to Find Product of Two Numbers using Recursion
1. import java.util.Scanner;
2. public class Multiply_Recursion
3. {
4. public static void main(String[] args)
5. {
6. int[] a = new int[2];
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first number:");
9. a[0] = s.nextInt();
10. System.out.print("Enter the second number:");
11. a[1] = s.nextInt();
12. Multiply_Recursion obj = new Multiply_Recursion();
13. int mul = obj.multiply(a,0);
14. System.out.println("Answer:"+mul);
15. }
16. int multiply(int x[], int i)
17. {
18. if(i < 2)
19. {
20. return x[i] * multiply(x, ++i);
21. }
22. else
23. {
24. return 1;
25. }
26. }
27. }
Output:-
Enter the first number:6
Enter the second number:4
Answer:24
Java Program to Implement the sin() Function
1. // Java Program to Implement the cos() Function(approximately)
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Sine {
7. // Function to calculate and display sine of an angle
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double x;
11. try {
12. System.out.println("Enter the angle whose sine is to be
13. calculated in degrees");
14. x = Double.parseDouble(br.readLine());
15. } catch (Exception e) {
16. System.out.println("An error occurred");
17. return;
18. }
19. double y;
20. y = x*Math.PI/180;
21. int n = 10;
22. int i,j,fac;
23. double sine = 0;
24. for(i=0; i<=n; i++){
25. fac = 1;
26. for(j=2; j<=2*i+1; j++){
27. fac*=j;
28. }
29. sine+=Math.pow(-1.0,i)*Math.pow(y,2*i+1)/fac;
30. }
31. System.out.format("The sine of " + x + " is %f",sine);
32. }
33. }
Output:-
Enter the angle whose sine is to be calculated in degrees
30
The sine of 30.0 is 0.500000

Case 2 (Simple Test Case - another example):

Enter the angle whose sine is to be calculated in degrees


60
The sine of 60.0 is 0.866025
Java Program to Implement the cos() Function
1.
// Java Program to Implement the cos() Function(approximately)
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Cosine {
7. // Function to read user input and calculate the cosine of the angle
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double x;
11. try {
12. System.out.println("Enter the angle whose cosine is to be
13. calculated in degrees");
14. x = Double.parseDouble(br.readLine());
15. } catch (Exception e) {
16. System.out.println("An error occurred");
17. return;
18. }
19. double y;
20. y = x*Math.PI/180;
21. int n = 10;
22. int i,j,fac;
23. double cosine = 0;
24. for(i=0; i<=n; i++){
25. fac = 1;
26. for(j=2; j<=2*i; j++){
27. fac*=j;
28. }
29. cosine+=Math.pow(-1.0,i)*Math.pow(y,2*i)/fac;
30. }
31. System.out.format("The cosine of " + x + " is %f",cosine);
32. }
33. }
Output:-
Enter the angle whose cosine is to be calculated in degrees
45
The cosine of 45.0 is 0.707107

Case 2 (Simple Test Case - another example):

Enter the angle whose cosine is to be calculated in degrees


75
The cosine of 75.0 is 0.258819
Java Program to Find the Roots of a Quadratic Equation
1. //Java Program to Find the Roots of a Quadratic Equation
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Quadratic {
7. // Function to find and display the roots of the equation.
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double a,b,c;
11. try{
12. System.out.println("Enter the coefficients of the quadratic equation");
13. a = Double.parseDouble(br.readLine());
14. b = Double.parseDouble(br.readLine());
15. c = Double.parseDouble(br.readLine());
16. }catch (Exception e){
17. System.out.println("An error occurred");
18. return;
19. }
20. double determinant = Math.pow(b,2) - 4*a*c;
21. if(determinant > 0){
22. System.out.println("Roots are " + (-b+Math.sqrt(determinant))/(2*a)
23. + " and " + (-b-Math.sqrt(determinant))/(2*a));
24. }else if (determinant == 0){
25. System.out.println("Roots are " + -b/(2*a));
26. }
27. else{
28. System.out.println("Roots are " + -b/(2*a) + "+i" +
29. Math.sqrt(-determinant)/(2*a) + " and "
30. + -b/(2*a) + "-i" + Math.sqrt(-determinant)/(2*a));
31. }
32. }
33. }
Output:-

Case 1 (Simple Test Case - Real and Unequal Roots):

Enter the coefficients of the quadratic equation


1
-5
6
Roots are 3.0 and 2.0

Case 2 (Simple Test Case - Real and Equal Roots):

Enter the coefficients of the quadratic equation


1
-2
1
Roots are 1.0

Case 3 (Simple Test Case - Imaginary roots):

Enter the coefficients of the quadratic equation


1
1
1
Roots are -0.5+i0.8660254037844386 and -0.5-i0.8660254037844386
Java Program to Calculate Simple Interest
1. import java.util.Scanner;
2. public class Simple_Interest
3. {
4. public static void main(String args[])
5. {
6. float p, r, t;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the Principal : ");
9. p = s.nextFloat();
10. System.out.print("Enter the Rate of interest : ");
11. r = s.nextFloat();
12. System.out.print("Enter the Time period : ");
13. t = s.nextFloat();
14. float si;
15. si = (r * t * p) / 100;
16. System.out.print("The Simple Interest is : " + si);
17. }
18. }
Output:-
Enter the Principal : 20202
Enter the Rate of interest : 2.5
Enter the Time period : 3
The Simple Interest is : 1515.15
Java Program to Find the Sum of the Series 1/1+1/2+1/3+…1/N
1. //Java Program to Find the Sum of the Series 1/1+1/2+1/3+...1/N
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Series80 {
7. // Function to find the sum of the series
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. try{
12. System.out.println("Enter the number of terms in the series");
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. double sum = 0;
19. double i;
20. for(i=1; i<=n;i++){
21. sum +=(1/i);
22. }
23. System.out.println("The sum is " + sum);
24. }
25. }
Output:-
Enter the number of terms in the series
34
The sum is 4.118209990445433
Java Program to Find the Sum of the Series 1/1+1/4+1/9+…1/N^2
1. //Java Program to Find the Sum of the Series 1/1+1/4+1/9+...1/N^2
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Series81 {
7. // Function to find the sum of the series
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. int n;
11. try{
12. System.out.println("Enter the number of terms in the series");
13. n = Integer.parseInt(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. double sum = 0;
19. double i;
20. for(i=1; i<=n;i++){
21. sum +=(1/(Math.pow(i,2)));
22. }
23. System.out.println("The sum is " + sum);
24. }
25. }
Output:-
Enter the number of terms in the series
34
The sum is 1.6159505883765848
Java Program to Add the nth Square Series
1. import java.util.Scanner;
2. public class Square_Series
3. {
4. public static void main(String[] args)
5. {
6. int n, sum = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.println("Given series:1^2 + 2^2 + 3^2......... +n^2");
9. System.out.print("Enter value of n:");
10. n = s.nextInt();
11. for(int i = 1; i <= n; i++)
12. {
13. sum = sum + i * i;
14. }
15. System.out.println("Sum of series:"+sum);
16. }
17. }
Output:-
Given series:1^2 + 2^2 + 3^2......... +n^2
Enter value of n:5
Sum of series:55
Java Program to Generate Harmonic Series
1. import java.util.Scanner;
2. class Harmonic
3. {
4. public static void main(String... a)
5. {
6. System.out.print("Enter any number : ");
7. Scanner s = new Scanner(System.in);
8. int num = s.nextInt();
9. System.out.print("The Harmonic Series is : ");
10. double result = 0.0;
11. while(num > 0)
12. {
13. result = result + (double) 1 / num;
14. num--;
15. System.out.print(result +" ");
16. }
17. System.out.println("");
18. System.out.println("Output of Harmonic Series is "+result);
19. }
20. }
Output:-

Enter any number : 5


The Harmonic Series is : 0.2 0.45 0.7833333333333333 1.2833333333333332
2.283333333333333
Output of Harmonic Series is 2.283333333333333
Java Program to Find the Area of a Circle
1. /*
2. * Java program to find the area of a circle
3. */
4.
5. public class Circle
6. {
7. public static void main(String[] args)
8. {
9. int r;
10. double pi = 3.14, area;
11. Scanner s = new Scanner(System.in);
12. System.out.print("Enter radius of circle: ");
13. r = s.nextInt();
14. area = pi * r * r;
15. System.out.println("Area of circle: "+area);
16. }
17. }
Output:-
Enter radius of circle: 22
Area of circle: 1519.76
Java Program to Find the Area of a Triangle
1.
//Java Program to Find the Area of a Triangle Using Heron's formula
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class HeronsFormula {
7. // Function to calculate area using Heron's Formula
8. static void area(double a, double b, double c){
9. double s = (a+b+c)/2;
10. s = s*(s-a)*(s-b)*(s-c);
11. System.out.println("Area of the triangle is " + Math.sqrt(s));
12. }
13. // Function to read user input
14. public static void main(String[] args) {
15. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16. double a,b,c;
17. System.out.println("Enter the three sides of the triangle");
18. try{
19. a = Double.parseDouble(br.readLine());
20. b = Double.parseDouble(br.readLine());
21. c = Double.parseDouble(br.readLine());
22. }catch (Exception e){
23. System.out.println("An error occurred");
24. return;
25. }
26. if(a<0 || b<0 || c<0){
27. System.out.println("Invalid Input");
28. return;
29. }
30. area(a,b,c);
31. }
32. }
Output:-
Enter the three sides of the triangle
14
56
43
Area of the triangle is 127.31236192923294
Java Program to Find the Area of Parallelogram
1.
//Java Program to Find the Area of a Parallelogram
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class AreaOfAParallelogram {
7. // Function to calculate the area of a parallelogram
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double base,height;
11. System.out.println("Enter the base and the height of the parallelogram");
12. try{
13. base=Double.parseDouble(br.readLine());
14. height=Double.parseDouble(br.readLine());
15. }catch (Exception e){
16. System.out.println("An error occurred");
17. return;
18. }
19. if(base<=0 || height<=0){
20. System.out.println("Wrong Input");
21. return;
22. }
23. System.out.println("Area = " + base*height );
24. }
25. }
Output:-
Enter the base and the height of the parallelogram
8.34
5.678
Area = 47.35452
Java Program to Find the Area of Rhombus
1. //Java Program to Find the Area of a Rhombus
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class AreaOfARhombus {
7. // Function to calculate the area of a rhombus
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double l1,l2;
11. System.out.println("Enter the length of the diagonals of the rhombus");
12. try{
13. l1=Double.parseDouble(br.readLine());
14. l2=Double.parseDouble(br.readLine());
15. }catch (Exception e){
16. System.out.println("An error occurred");
17. return;
18. }
19. if(l1<=0 || l2<=0){
20. System.out.println("Wrong input");
21. return;
22. }
23. System.out.println("Area = " + (l1*l2)/2 );
24. }
25. }
Output:-
Enter the length of the diagonals of the rhombus
23
45
Area = 517.5
Java Program to Find the Area of Trapezium
1. //Java Program to Find the Area of a Trapezium
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class AreaOfATrapezium {
7. // Function to find area of a trapezium
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double l1,l2,height;
11. System.out.println("Enter the length of the two parallel sides
12. and the height of the trapezium");
13. try{
14. l1=Double.parseDouble(br.readLine());
15. l2=Double.parseDouble(br.readLine());
16. height=Double.parseDouble(br.readLine());
17. }catch (Exception e){
18. System.out.println("An error occurred");
19. return;
20. }
21. if(l1<=0 || l2<=0 || height<=0){
22. System.out.println("Wrong Input");
23. }
24. System.out.println("Area = " + (l1+l2)*height/2 );
25. }
26. }
Output:-
Enter the length of the two parallel sides and the height of the trapezium
13.765
23.555
8.0
Area = 149.28
Java Program to Find Volume and Surface Area of Cone
1. //Java Program to Find the Surface Area and Volume of a Cone
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Cone {
7. // Function to calculate and print the surface area and volume of a cone
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double radius,height;
11. System.out.println("Enter the radius and
12. height of the right circular cone");
13. try{
14. radius=Double.parseDouble(br.readLine());
15. height=Double.parseDouble(br.readLine());
16. }catch (Exception e){
17. System.out.println("An error occurred");
18. return;
19. }
20. if(radius<=0 || height<=0){
21. System.out.println("Wrong Input");
22. return;
23. }
24. double slantheight = Math.sqrt(Math.pow(radius,2) + Math.pow(height,2));
25. System.out.println("Volume = " + (Math.PI*Math.pow(radius,2)*height/3));
26. System.out.println("Surface area = " + ((Math.PI*radius*slantheight)
27. + (Math.PI*radius*radius)));
28. }
29. }
Output:-
Enter the radius and height of the right circular cone
3.42
12
Volume = 146.98129725379061
Surface area = 170.81027853689216
Java Program to Find Volume and Surface Area of Cuboids
1. //Java Program to Find the Surface Area and Volume of a Cuboid
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Cuboid {
7. // Function to calculate the Surface Area and Volume of a Cuboid
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double length,breadth,height;
11. System.out.println("Enter the length, breadth and height of the cuboid");
12. try{
13. length=Double.parseDouble(br.readLine());
14. breadth=Double.parseDouble(br.readLine());
15. height=Double.parseDouble(br.readLine());
16. }catch (Exception e){
17. System.out.println("An error occurred");
18. return;
19. }
20. if(length<=0 || breadth<=0 || height<=0){
21. System.out.println("Wrong Input");
22. return;
23. }
24. System.out.println("Volume = " + length*breadth*height);
25. System.out.println("Surface area = " +
26. 2*(length*breadth + breadth*height + height*length));
27. }
28. }
Output:-
Enter the length, breadth and height of the cuboid
12
9.76
5.68
Volume = 665.2416
Surface area = 481.4336
Java Program to Find Volume and Surface Area of Sphere
1. //Java Program to Find the Surface Area and Volume of a Sphere
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class Sphere {
7. // Function to calculate and print the surface area and volume of a sphere
8. public static void main(String[] args) {
9. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10. double radius;
11. System.out.println("Enter the radius of the sphere");
12. try{
13. radius=Double.parseDouble(br.readLine());
14. }catch (Exception e){
15. System.out.println("An error occurred");
16. return;
17. }
18. if(radius<=0){
19. System.out.println("Wrong Input");
20. return;
21. }
22. System.out.println("Volume = " + (4*Math.pow(radius,3)*Math.PI)/3);
23. System.out.println("Surface area = " + (4*Math.PI*Math.pow(radius,2)));
24. }
25. }
Output:-
Enter the radius of the sphere
4.55
Volume = 394.56885292638566
Surface area = 260.15528764377075
Java Program to Find the Perimeter of a Circle, Rectangle and Triangle
1. import java.util.Scanner;
2. public class Perimeter
3. {
4. int r, l, b, s1, s2, s3;
5. double pi = 3.14,perimeter;
6. Scanner s = new Scanner(System.in);
7. void circle()
8. {
9. System.out.print("Enter radius of circle:");
10. r = s.nextInt();
11. perimeter = 2 * pi * r;
12. System.out.println("Perimeter of circle:"+perimeter);
13. }
14. void rectangle()
15. {
16. System.out.print("Enter length of rectangle:");
17. l = s.nextInt();
18. System.out.print("Enter breadth of rectangle:");
19. b = s.nextInt();
20. perimeter = 2 * (l + b);
21. System.out.println("Perimeter of rectangle:"+perimeter);
22. }
23. void triangle()
24. {
25. System.out.print("Enter length of first side of triangle:");
26. s1 = s.nextInt();
27. System.out.print("Enter length of second side of triangle:");
28. s2 = s.nextInt();
29. System.out.print("Enter length of third side of triangle:");
30. s3 = s.nextInt();
31. perimeter = s1 + s2 + s3;
32. System.out.println("Perimeter of triangle:"+perimeter);
33. }
34. public static void main(String[] args)
35. {
36. Perimeter obj = new Perimeter();
37. obj.circle();
38. obj.rectangle();
39. obj.triangle();
40. }
41. }
Output:-
Enter radius of circle:4
Perimeter of circle:25.12
Enter length of rectangle:5
Enter breadth of rectangle:6
Perimeter of rectangle:22.0
Enter length of first side of triangle:3
Enter length of second side of triangle:4
Enter length of third side of triangle:5
Perimeter of triangle:12.0
Java Program to Find the Area and Perimeter of Rectangle using Class
1. import java.util.Scanner;
2. public class Area_Perimeter
3. {
4. public static void main(String[] args)
5. {
6. int l, b, perimeter, area;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter length of rectangle:");
9. l = s.nextInt();
10. System.out.print("Enter breadth of rectangle:");
11. b = s.nextInt();
12. perimeter = 2 * (l + b);
13. System.out.println("Perimeter of rectangle:"+perimeter);
14. area = l * b;
15. System.out.println("Area of rectangle:"+area);
16. }
17. }
Output:-
Enter length of rectangle:4
Enter breadth of rectangle:5
Perimeter of rectangle:18
Area of rectangle:20
GCD Program in Java
1. import static java.lang.StrictMath.min;
2. import java.util.Scanner;
3. public class GCD
4. {
5. public static void main(String args[])
6. {
7. int a, b, hcf = 1;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter First Number:");
10. a = s.nextInt();
11. System.out.print("Enter Second Number:");
12. b = s.nextInt();
13. int n = min(a,b);
14. for(int i = 2; i < n; i++)
15. {
16. while(a % i == 0 && b % i==0)
17. {
18. hcf = hcf * i;
19. a = a / i;
20. b = b / i;
21. }
22. }
23. System.out.println("Greatest Common Divisor:"+hcf);
24. }
25. }
Output:-
Enter First Number:24
Enter Second Number:16
Greatest Common Divisor:8
Java Program to Find GCD and LCM of Two Numbers

//This is sample program to calculate the GCD and LCM of two given numbers
import java.util.Scanner;

public class GCD_LCM


{
static int gcd(int x, int y)
{
int r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number

r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}

static int lcm(int x, int y)


{
int a;
a = (x > y) ? x : y; // a is greater number
while(true)
{
if(a % x == 0 && a % y == 0)
return a;
++a;
}
}

public static void main(String args[])


{
Scanner input = new Scanner(System.in);
System.out.println("Enter the two numbers: ");
int x = input.nextInt();
int y = input.nextInt();

System.out.println("The GCD of two numbers is: " + gcd(x, y));


System.out.println("The LCM of two numbers is: " + lcm(x, y));
input.close();
}
}
Output:-
Enter the two numbers:
15
25
The GCD of two numbers is: 5
The LCM of two numbers is: 75

Enter the two numbers:


5
8
The GCD of two numbers is: 1
The LCM of two numbers is: 40
Java Program to Implement Euclid GCD Algorithm
1. /**
2. ** Java Program to Implement Euclid GCD Algorithm
3. **/
4.
5. import java.util.Scanner;
6.
7. /** Class EuclidGcd **/
8. public class EuclidGcd
9. {
10. /** Function to calculate gcd **/
11. public long gcd(long p, long q)
12. {
13. if (p % q == 0)
14. return q;
15. return gcd(q, p % q);
16. }
17. /** Main function **/
18. public static void main (String[] args)
19. {
20. Scanner scan = new Scanner(System.in);
21. System.out.println("Euclid GCD Algorithm Test\n");
22. /** Make an object of EuclidGcd class **/
23. EuclidGcd eg = new EuclidGcd();
24.
25. /** Accept two integers **/
26. System.out.println("Enter two integer numbers\n");
27. long n1 = scan.nextLong();
28. long n2 = scan.nextLong();
29. /** Call function gcd of class EuclidGcd **/
30. long gcd = eg.gcd(n1, n2);
31. System.out.println("\nGCD of "+ n1 +" and "+ n2 +" = "+ gcd);
32. }
33. }
Output:-
Enter two integer numbers

257184 800128

GCD of 257184 and 800128 = 28576


Java Program to find GCD and LCM of Two Numbers Using Euclid’s Algorithm
1. import java.util.Scanner;
2. public class Euclid
3. {
4. void gcd(long a, long b)
5. {
6. while (b > 0)
7. {
8. long temp = b;
9. b = a % b; // % is remainder
10. a = temp;
11. }
12. System.out.println("GCD is "+a);
13. }
14. void lcm(long a, long b)
15. {
16. long x = a;
17. long y = b;
18. while (b > 0)
19. {
20. long temp = b;
21. b = a % b; // % is remainder
22. a = temp;
23. }
24. long gcd = a;
25. long lcm = (x * (y / gcd));
26. System.out.println("LCM is "+ lcm);
27. }
28. public static void main(String... a)
29. {
30. Euclid abc = new Euclid();
31. System.out.println("Enter any two numbers to calculate GCD");
32. Scanner s = new Scanner(System.in);
33. long x = s.nextLong();
34. long y = s.nextLong();
35. abc.gcd(x, y);
36. System.out.println("Enter any two numbers to calculate LCM");
37. long l = s.nextLong();
38. long m = s.nextLong();
39. abc.lcm(l, m);
40. }
41. }
Output:-
Enter any two numbers to calculate GCD
6 50
GCD is 2
Enter any two numbers to calculate LCM
11 17
LCM is 187
Java Program to Find GCD of Two Numbers
/*
* GCD of Two Numbers in Java using Loops
*/

import static java.lang.StrictMath.min;


import java.util.Scanner;
public class GCD
{
public static void main(String args[])
{
int a, b, hcf = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter First Number:");
a = s.nextInt();
System.out.print("Enter Second Number:");
b = s.nextInt();
int n = min(a,b);
for(int i = 2; i < n; i++)
{
while(a % i == 0 && b % i==0)
{
hcf = hcf * i;
a = a / i;
b = b / i;
}
}
System.out.println("Greatest Common Divisor:"+hcf);
}
}
Output:-
Enter First Number:24
Enter Second Number:16
Greatest Common Divisor:8
Java Program to Find the Number of Elements in an Array
1. public class Length
2. {
3. public static void main(String[] args)
4. {
5. int a[] = {1,2,3,4,5};
6. int count = 0, i = 0, n;
7. try
8. {
9. while(a[i] != 'a')
10. {
11. count++;
12. i++;
13. }
14. }
15. catch(Exception e)
16. {
17. System.out.println("Number of elements in array:"+count);
18. }
19. n = a.length;
20. System.out.println("Number of elements(Using inbuilt method named
length):"+n);
21. }
22. }
Output:-
Number of elements in array:5
Number of elements(Using inbuilt method named length):5
Java Program to Find Largest Element in an Array
1. import java.util.Scanner;
2. public class Largest_Number
3. {
4. public static void main(String[] args)
5. {
6. int n, max;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter number of elements in the array:");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter elements of array:");
12. for(int i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. max = a[0];
17. for(int i = 0; i < n; i++)
18. {
19. if(max < a[i])
20. {
21. max = a[i];
22. }
23. }
24. System.out.println("Maximum value:"+max);
25. }
26. }
Output:-
Enter number of elements in the array:5
Enter elements of array:
4
2
3
6
1
Maximum value:6
Java Program to Find the Second Largest and Smallest Elements in an Array
1. import java.util.Scanner;
2. public class SecondLargest_Smallest
3. {
4. public static void main(String[] args)
5. {
6. int n, temp;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter no. of elements you want in array(Minimum 2):");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter all the elements:");
12. for (int i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. for (int i = 0; i < n; i++)
17. {
18. for (int j = i + 1; j < n; j++)
19. {
20. if (a[i] > a[j])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. System.out.println("Second Largest:"+a[n-2]);
29. System.out.println("Smallest:"+a[0]);
30. }
31. }
Output:-
Enter no. of elements you want in array(Minimum 2):8
Enter all the elements:
2
5
1
7
8
6
9
3
Second Largest:8
Smallest:1
Java Program to Find Local Maxima in an Array
1.
//Java Program to Find Local Maximas in an Array
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class LocalMaxima {
7. // Function to return the index of the local Maxima
8. static int localMaxima(int[] array){
9. int low,mid,high;
10. low = 0;
11. high = array.length-1;
12. int ans;
13. while(low<=high){
14. mid = (low + high)/2;
15. if((mid == 0 || array[mid-1] < array[mid])
16. && (mid == array.length-1 || array[mid+1] < array[mid])){
17. return mid;
18. }
19. else if(mid > 0 && array[mid-1] > array[mid]){
20. high = mid-1;
21. }
22. else{
23. low = mid+1;
24. }
25. }
26. return -1;
27. }
28.
29. // Function to read input
30. public static void main(String[] args) {
31. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
32. int size;
33. System.out.println("Enter the size of the array");
34. try {
35. size = Integer.parseInt(br.readLine());
36. } catch (Exception e) {
37. System.out.println("Invalid Input");
38. return;
39. }
40. int[] array = new int[size];
41. System.out.println("Enter array elements");
42. int i;
43. for (i = 0; i < array.length; i++) {
44. try {
45. array[i] = Integer.parseInt(br.readLine());
46. } catch (Exception e) {
47. System.out.println("An error occurred");
48. return;
49. }
50. }
51. int index = localMaxima(array);
52. System.out.println("The local maxima is " + array[index]);
53. }
54. }
Output:-
Case 1 (Positive test case - local maxima is not at the extreme ends):

Enter the size of the array


6
Enter array elements
1
2
3
4
5
-1
The local maxima is 5

Case 2 (Positive test case - local maxima is at the beginning of the array):

Enter the size of the array


8
Enter array elements
8
7
6
5
4
3
2
1
The local maxima is 8

Case 3 (Positive test case - local maxima is at the end of the array):

Enter the size of the array


6
Enter array elements
1
2
3
4
5
6
The local maxima is 6
Java Program to Remove Duplicate Elements from Array
1. //Java Program to Remove Duplicates in a Sorted Array
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class RemoveDuplicates {
7. // Function to remove the duplicates
8. static int removeDuplicates(int[] array){
9. int replaceIndex = 0;
10. int i,j;
11. for(i=0; i<array.length; i++){
12. for(j=i+1; j<array.length; j++){
13. if(array[j]!=array[i]){
14. break;
15. }
16. }
17. array[replaceIndex++] = array[i];
18. i = j-1;
19. }
20. return replaceIndex;
21. }
22. // Function to read user input
23. public static void main(String[] args) {
24. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
25. int size;
26. System.out.println("Enter the size of the array");
27. try {
28. size = Integer.parseInt(br.readLine());
29. } catch (Exception e) {
30. System.out.println("Invalid Input");
31. return;
32. }
33. int[] array = new int[size];
34. System.out.println("Enter array elements in sorted order");
35. int i;
36. for (i = 0; i < array.length; i++) {
37. try {
38. array[i] = Integer.parseInt(br.readLine());
39. } catch (Exception e) {
40. System.out.println("An error occurred");
41. return;
42. }
43. }
44. int index = removeDuplicates(array);
45. System.out.println("Array after removing duplicates is");
46. for(i=0; i<index; i++){
47. System.out.print(array[i] + " ");
48. }
49. }
50. }
Output:-
Case 1 (Positive Test Case - Involving Duplicates):

Enter the size of the array


6
Enter array elements in sorted order
1
2
2
3
3
4
Array after removing duplicates is
1234

Case 2 (Negative test Case - Without Duplicates):

Enter the size of the array


4
Enter array elements in sorted order
4
3
2
1
Array after removing duplicates is
4321

Case 3 (Positive Test Case - Another Example):

Enter the size of the array


7
Enter array elements in sorted order
1
3
3
3
4
5
6
Array after removing duplicates is
13456
Java Program to Merge Two Arrays
1. // Java Program to Merge Two Arrays in Order.
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6. import java.util.Arrays;
7.
8. public class InOrderMerge {
9. // Function to merge the arrays
10. static int[] mergeArrays(int[] arrayOne,int[] arrayTwo)
11. {
12. int totalLength=arrayOne.length +arrayTwo.length;
13. int[] c=new int[totalLength];
14. int j,k,index=0;
15. j=0;
16. k=0;
17. while((j!=arrayOne.length) && (k!=arrayTwo.length)){
18. if(arrayOne[j]<=arrayTwo[k])
19. {
20. c[index++]=arrayOne[j++];
21. }
22. else
23. {
24. c[index++]=arrayTwo[k++];
25. }
26. }
27. while(k!=arrayTwo.length)
28. {
29. c[index++]=arrayTwo[k++];
30. }
31. while(j!=arrayOne.length)
32. {
33. c[index++]=arrayOne[j++];
34. }
35. return c;
36. }
37. // Function to read input and display the output
38. public static void main(String[] args){
39. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
40. int m, n;
41. System.out.println("Enter the size of the two arrays");
42. try {
43. n = Integer.parseInt(br.readLine());
44. m = Integer.parseInt(br.readLine());
45. }
46. catch (IOException e)
47. {
48. System.out.println("Invalid input");
49. return;
50. }
51. int[] arrayOne = new int[n];
52. int[] arrayTwo = new int[m];
53. System.out.println("Enter the first array elements");
54. int i,j;
55. for(i=0; i<arrayOne.length; i++){
56. try {
57. arrayOne[i] = Integer.parseInt(br.readLine());
58. }
59. catch (IOException e)
60. {
61. System.out.println("Invalid array element. Enter it again");
62. i--;
63. }
64. }
65. System.out.println("Enter the second array elements");
66. for(i=0; i<arrayTwo.length; i++){
67. try {
68. arrayTwo[i] = Integer.parseInt(br.readLine());
69. }
70. catch (IOException e)
71. {
72. System.out.println("Invalid array element. Enter it again");
73. i--;
74. }
75. }
76. Arrays.sort(arrayOne);
77. Arrays.sort(arrayTwo);
78. int[] mergedArray=mergeArrays(arrayOne,arrayTwo);
79. System.out.println("The merged array is");
80. for(i=0;i<mergedArray.length;i++)
81. {
82. System.out.print(mergedArray[i]+" ");
83. }
84. }
85. }
Output:-
Case 1 (Simple Test Case):

Enter the size of the two arrays


5
5
Enter the first array elements
1
2
3
4
5
Enter the second array elements
2
3
6
7
8
The merged array is
1223345678

Case 2 (Simple Test Case - another example):

Enter the size of the two arrays


4
5
Enter the first array elements
89
45
32
6
Enter the second array elements
24
456
23
567
34
The merged array is
6 23 24 32 34 45 89 456 567
Java Program to Find Sum and Average of All Elements in an Array
1. import java.util.Scanner;
2. public class Sum_Average
3. {
4. public static void main(String[] args)
5. {
6. int n, sum = 0;
7. float average;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter no. of elements you want in array:");
10. n = s.nextInt();
11. int a[] = new int[n];
12. System.out.println("Enter all the elements:");
13. for(int i = 0; i < n ; i++)
14. {
15. a[i] = s.nextInt();
16. sum = sum + a[i];
17. }
18. System.out.println("Sum:"+sum);
19. average = (float)sum / n;
20. System.out.println("Average:"+average);
21. }
22. }
Ouput:-
Enter no. of elements you want in array:5
Enter all the elements:
4
7
6
9
3
Sum:29
Average:5.8
Java Program to Search Key Elements in an Array
1. import java.util.Scanner;
2. public class Search_Element
3. {
4. public static void main(String[] args)
5. {
6. int n, x, flag = 0, i = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter no. of elements you want in array:");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter all the elements:");
12. for(i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. System.out.print("Enter the element you want to find:");
17. x = s.nextInt();
18. for(i = 0; i < n; i++)
19. {
20. if(a[i] == x)
21. {
22. flag = 1;
23. break;
24. }
25. else
26. {
27. flag = 0;
28. }
29. }
30. if(flag == 1)
31. {
32. System.out.println("Element found at position:"+(i + 1));
33. }
34. else
35. {
36. System.out.println("Element not found");
37. }
38. }
39. }
Output:-
Enter no. of elements you want in array:7
Enter all the elements:
2
4
1
5
7
6
9
Enter the element you want to find:5
Element found at position:4
Java Program to Count the Number of Occurrence of an Element in an Array
1. import java.util.Scanner;
2. public class Count_Occurrence
3. {
4. public static void main(String[] args)
5. {
6. int n, x, count = 0, i = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter no. of elements you want in array:");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter all the elements:");
12. for(i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. System.out.print("Enter the element of which you want to count number of
occurrences:");
17. x = s.nextInt();
18. for(i = 0; i < n; i++)
19. {
20. if(a[i] == x)
21. {
22. count++;
23. }
24. }
25. System.out.println("Number of Occurrence of the Element:"+count);
26. }
27. }
Output:-
Enter no. of elements you want in array:5
Enter all the elements:
2
3
3
4
3
Enter the element of which you want to count number of occurrences:3
Number of Occurrence of the Element:3
Java Program to Find Union and Intersection of Two Arrays
1. // Java Program to Find the Union and Intersection of 2 Arrays.
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6. import java.util.Arrays;
7. import java.util.HashSet;
8. import java.util.Set;
9.
10. public class UnionAndIntersection {
11. // Function to find and display the union and intersection
12. static void displayUnionAndIntersection(int[] arrayOne,int[] arrayTwo){
13. Set<Integer> obj = new HashSet<>();
14. int i,j;
15. for(i=0; i<arrayOne.length; i++){
16. obj.add(arrayOne[i]);
17. }
18. for(j=0; j<arrayTwo.length; j++){
19. obj.add(arrayTwo[j]);
20. }
21. System.out.println("The union of both the arrays is");
22. for(Integer I: obj){
23. System.out.print(I + " ");
24. }
25. System.out.println();
26. obj.clear();
27. System.out.println("The intersection of both the arrays is");
28. for(i=0; i<arrayOne.length; i++){
29. obj.add(arrayOne[i]);
30. }
31. for(j=0; j<arrayTwo.length; j++){
32. if(obj.contains(arrayTwo[j]))
33. System.out.print(arrayTwo[j] + " ");
34. }
35. }
36. // Function to read the input
37. public static void main(String[] args) {
38. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
39. int m,n;
40. System.out.println("Enter the size of the two arrays");
41. try {
42. n = Integer.parseInt(br.readLine());
43. m = Integer.parseInt(br.readLine());
44. }
45. catch (IOException e)
46. {
47. System.out.println("Invalid input");
48. return;
49. }
50. int[] arrayOne = new int[n];
51. int[] arrayTwo = new int[m];
52. System.out.println("Enter the first array elements");
53. int i,j;
54. for(i=0; i<arrayOne.length; i++){
55. try {
56. arrayOne[i] = Integer.parseInt(br.readLine());
57. }
58. catch (IOException e)
59. {
60. System.out.println("Invalid array element. Enter it again");
61. i--;
62. }
63. }
64. System.out.println("Enter the second array elements");
65. for(i=0; i<arrayTwo.length; i++){
66. try {
67. arrayTwo[i] = Integer.parseInt(br.readLine());
68. }
69. catch (IOException e)
70. {
71. System.out.println("Invalid array element. Enter it again");
72. i--;
73. }
74. }
75. displayUnionAndIntersection(arrayOne,arrayTwo);
76. }
77. }
Output:-
Case 1 (Simple Test Case):

Enter the size of the two arrays


5
5
Enter the first array elements
1
2
3
4
5
Enter the second array elements
5
3
6
7
9
The union of both the arrays is
12345679
The intersection of both the arrays is
53

Case 2 (Simple Test Case - entirely different arrays):

Enter the size of the two arrays


4
4
Enter the first array elements
1
2
3
4
Enter the second array elements
6
7
8
9
The union of both the arrays is
12346789
The intersection of both the arrays is

Case 3 (Simple Test Case - entirely same arrays):

Enter the size of the two arrays


4
4
Enter the first array elements
1
2
3
4
Enter the second array elements
1
2
3
4
The union of both the arrays is
1234
The intersection of both the arrays is
1234
Java Program to Multiply Two Matrices
// This is sample program for matrix multiplication
// The complexity of the algorithm is O(n^3)

package com.sanfoundry.numerical;

import java.util.Scanner;

public class MatixMultiplication


{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the base of squared matrices");
n = input.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
System.out.println("Enter the elements of 1st martix row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
System.out.println("Enter the elements of 2nd martix row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = input.nextInt();
}
}
System.out.println("Multiplying the matrices...");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
input.close();
}
}
Output:-
Enter the base of squared matrices:
3
Enter the elements of 1st martix row wise:
123
456
789
Enter the elements of 2nd martix row wise:
234
567
891
Multiplying the matrices...
The product is:
36 42 21
81 96 57
126 150 93
Java Program to Display Lower Triangular Matrix
1. import java.util.Scanner;
2. public class Lower_Matrix
3. {
4. public static void main(String args[])
5. {
6. int a[][] = new int[5][5];
7. System.out.println("Enter the order of your Matrics ");
8. System.out.println("Enter the rows:");
9. Scanner sc = new Scanner(System.in);
10. int n = sc.nextInt();
11. System.out.println("Enter the columns:");
12. Scanner s = new Scanner(System.in);
13. int m = s.nextInt();
14. if(n == m)
15. {
16. System.out.println("Enter your elements:");
17. for(int i = 0; i < n; i++)
18. {
19. for(int j = 0; j < n; j++)
20. {
21.
22. Scanner ss = new Scanner(System.in);
23. a[i][j] = ss.nextInt();
24. System.out.print(" ");
25. }
26. }
27. System.out.println("You have entered:");
28. for(int i=0; i<n; i++)
29. {
30. for(int j=0;j<n;j++)
31. {
32. System.out.print(a[i][j] + " ");
33. }
34. System.out.println("");
35. }
36. System.out.println("The Lower Triangular Matrix is:");
37. for(int i=0;i<n;i++)
38. {
39. for(int j=0;j<n;j++)
40. {
41. if(i>=j)
42. {
43. System.out.print(a[i][j] +" ");
44. }
45. else
46. {
47. System.out.print("0"+" ");
48. }
49. }
50. System.out.println("");
51. }
52. }
53. else
54. {
55. System.out.println("you have entered improper order");
56. }
57. }
58. }
Output:-
Enter the order of your Matrics
Enter the rows:
3
Enter the columns:
3
Enter your elements:
1
2
3
4
5
6
7
8
9
You have entered:
123
456
789
The Lower Triangular Matrix is:
100
450
789
Java Program to Display Upper and Lower Triangular Matrix
1.
//Java Program to Display Upper/Lower Triangle of a Matrix
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class UpperAndLowerTriangle {
7. // Function to display upper and lower triangle
8. static void displayUpperAndLowerTriangle(int[][] matrix){
9. int order = matrix.length;
10. int i,j;
11. for(i=0; i<order; i++){
12. for(j=0; j<order;j++){
13. if((i+j) <order)
14. System.out.print(matrix[i][j] + "\t");
15. }
16. System.out.println();
17. }
18. for(i=0; i<order; i++){
19. for(j=0; j<order;j++){
20. if((i+j) >=order)
21. System.out.print(matrix[i][j] + "\t");
22. }
23. System.out.println();
24. }
25. }
26. // Function to read user input
27. public static void main(String[] args) {
28. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
29. int order;
30. System.out.println("Enter the order of the matrix");
31. try{
32. order = Integer.parseInt(br.readLine());
33. }
34. catch(Exception e){
35. System.out.println("An error occurred");
36. return;
37. }
38. int[][] matrix = new int[order][order];
39. System.out.println("Enter matrix elements");
40. int i,j;
41. for(i=0; i<order; i++){
42. for(j=0; j<order; j++){
43. try{
44. matrix[i][j] = Integer.parseInt(br.readLine());
45. }
46. catch(Exception e){
47. System.out.println("An error occurred");
48. return;
49. }
50. }
51. }
52. System.out.println("Tha matrix is");
53. for(i=0; i<order; i++){
54. for(j=0; j<order; j++){
55. System.out.print(matrix[i][j] + "\t");
56. }
57. System.out.println();
58. }
59. System.out.println("The upper and lower triangle is");
60. displayUpperAndLowerTriangle(matrix);
61. }
62. }
Output:-
Case 1 (Simple Test Case):

Enter the order of the matrix


4
Enter matrix elements
0
0
1
1
0
1
1
1
0
0
0
1
0
0
0
0
The matrix is
0 0 1 1
0 1 1 1
0 0 0 1
0 0 0 0
The upper and lower triangle is
0 0 1 1
0 1 1
0 0
0

1
0 1
0 0 0

Case 2 (Simple Test Case - another example):

Enter the order of the matrix


3
Enter matrix elements
1
2
3
4
5
6
7
8
9
The matrix is
1 2 3
4 5 6
7 8 9
The upper and lower triangle is
1 2 3
4 5
7

6
8 9
Java Program to Find the Sum and Product of Elements in a Row/Column
1. //Java Program to Find the Sum and Product of Elements in a Row/Column
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class SumAndProduct {
7. // Function to calculate sum and products
8. static void displayOutput(int[][] matrix)
9. {
10. int i,j,sumr,productr,sumc,productc;
11. System.out.println("\t\tSum Product");
12. for(i=0; i<matrix.length; i++){
13. sumr = sumc = 0;
14. productr = productc = 1;
15. for(j=0; j<matrix[i].length; j++){
16. sumr+=matrix[i][j];
17. sumc+=matrix[j][i];
18. productr*=matrix[i][j];
19. productc*=matrix[j][i];
20. }
21. System.out.format("%s %d %3d %2d\n","Row",i+1,sumr,productr);
22. System.out.format("%s %d %3d %2d\n","Col",i+1,sumc,productc);
23. }
24. }
25. // Function to read user input
26. public static void main(String[] args) {
27. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
28. int order;
29. System.out.println("Enter the order of the matrix");
30. try {
31. order = Integer.parseInt(br.readLine());
32. } catch (Exception e) {
33. System.out.println("An error occurred");
34. return;
35. }
36. int[][] matrix = new int[order][order];
37. System.out.println("Enter matrix elements");
38. int i, j;
39. for (i = 0; i < order; i++) {
40. for (j = 0; j < order; j++) {
41. try {
42. matrix[i][j] = Integer.parseInt(br.readLine());
43. } catch (Exception e) {
44. System.out.println("An error occurred");
45. return;
46. }
47. }
48. }
49. System.out.println("Tha matrix is");
50. for (i = 0; i < order; i++) {
51. for (j = 0; j < order; j++) {
52. System.out.print(matrix[i][j] + "\t");
53. }
54. System.out.println();
55. }
56. displayOutput(matrix);
57. }
58. }
Output:-
Case 1 (Simple Test Case):

Enter the order of the matrix


4
Enter matrix elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
The matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum Product
Row 1 10 24
Col 1 28 585
Row 2 26 1680
Col 2 32 1680
Row 3 42 11880
Col 3 36 3465
Row 4 58 43680
Col 4 40 6144
Java Program to Find Transpose of a Matrix
1. import java.util.Scanner;
2. public class Transpose
3. {
4. public static void main(String args[])
5. {
6. int i, j;
7. System.out.println("Enter total rows and columns: ");
8. Scanner s = new Scanner(System.in);
9. int row = s.nextInt();
10. int column = s.nextInt();
11. int array[][] = new int[row][column];
12. System.out.println("Enter matrix:");
13. for(i = 0; i < row; i++)
14. {
15. for(j = 0; j < column; j++)
16. {
17. array[i][j] = s.nextInt();
18. System.out.print(" ");
19. }
20. }
21. System.out.println("The above matrix before Transpose is ");
22. for(i = 0; i < row; i++)
23. {
24. for(j = 0; j < column; j++)
25. {
26. System.out.print(array[i][j]+" ");
27. }
28. System.out.println(" ");
29. }
30. System.out.println("The above matrix after Transpose is ");
31. for(i = 0; i < column; i++)
32. {
33. for(j = 0; j < row; j++)
34. {
35. System.out.print(array[j][i]+" ");
36. }
37. System.out.println(" ");
38. }
39. }
40. }
Output:-
Enter total rows and columns:
33
Enter matrix:
1
2
3
4
5
6
7
8
9
The above matrix before Transpose is
123
456
789
The above matrix after Transpose is
147
258
369
Java Program to Find the Determinant of a Matrix
1. //Java Program to Find the Modulus of a
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class ModulusOfAMatrix {
7. // Function to read array elements and calculate the determinant
8. public static void main(String[] args) {
9. BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
10. int order=3;
11. int[][] matrix=new int[3][3];
12. System.out.println("Enter the elements of 3x3 matrix");
13. int i,j;
14. for(i=0;i<matrix.length;i++){
15. for(j=0;j<matrix[i].length;j++){
16. try{
17. matrix[i][j]=Integer.parseInt(br.readLine());
18. }
19. catch(Exception e){
20. System.out.println("An error occured. Please retry");
21. return;
22. }
23. }
24. }
25. int determinant,x,y,z;
26. x=(matrix[0][0] * (matrix[1][1] * matrix[2][2]
27. - matrix[1][2] * matrix[2][1]));
28. y=(matrix[0][1] * (matrix[1][0] * matrix[2][2]
29. - matrix[1][2] * matrix[2][0]));
30. z=(matrix[0][2] * (matrix[1][0] * matrix[2][1]
31. - matrix[1][1] * matrix[2][0]));
32. determinant= x - y + z;
33. System.out.println("The modulus of the given matrix is "+ determinant);
34.
35. }
36. }
Output:-
Enter the elements of 3x3 matrix
1
2
3
4
5
6
7
8
9
The modulus of the given matrix is 0

Case 2 (Simple Test Case - another example):

Enter the elements of 3x3 matrix


12
43
5
23
56
7
45
2
65
The modulus of the given matrix is -19598
Java Program to Find Inverse of a Matrix
1. //This is sample program to find the inverse of a matrix
2.
3. import java.util.Scanner;
4.
5. public class Inverse
6. {
7. public static void main(String argv[])
8. {
9. Scanner input = new Scanner(System.in);
10. System.out.println("Enter the dimension of square matrix: ");
11. int n = input.nextInt();
12. double a[][]= new double[n][n];
13. System.out.println("Enter the elements of matrix: ");
14. for(int i=0; i<n; i++)
15. for(int j=0; j<n; j++)
16. a[i][j] = input.nextDouble();
17.
18. double d[][] = invert(a);
19.
20. System.out.println("The inverse is: ");
21. for (int i=0; i<n; ++i)
22. {
23. for (int j=0; j<n; ++j)
24. {
25. System.out.print(d[i][j]+" ");
26. }
27. System.out.println();
28. }
29. input.close();
30. }
31.
32. public static double[][] invert(double a[][])
33. {
34. int n = a.length;
35. double x[][] = new double[n][n];
36. double b[][] = new double[n][n];
37. int index[] = new int[n];
38. for (int i=0; i<n; ++i)
39. b[i][i] = 1;
40.
41. // Transform the matrix into an upper triangle
42. gaussian(a, index);
43.
44. // Update the matrix b[i][j] with the ratios stored
45. for (int i=0; i<n-1; ++i)
46. for (int j=i+1; j<n; ++j)
47. for (int k=0; k<n; ++k)
48. b[index[j]][k]
49. -= a[index[j]][i]*b[index[i]][k];
50.
51. // Perform backward substitutions
52. for (int i=0; i<n; ++i)
53. {
54. x[n-1][i] = b[index[n-1]][i]/a[index[n-1]][n-1];
55. for (int j=n-2; j>=0; --j)
56. {
57. x[j][i] = b[index[j]][i];
58. for (int k=j+1; k<n; ++k)
59. {
60. x[j][i] -= a[index[j]][k]*x[k][i];
61. }
62. x[j][i] /= a[index[j]][j];
63. }
64. }
65. return x;
66. }
67.
68. // Method to carry out the partial-pivoting Gaussian
69. // elimination. Here index[] stores pivoting order.
70.
71. public static void gaussian(double a[][], int index[])
72. {
73. int n = index.length;
74. double c[] = new double[n];
75.
76. // Initialize the index
77. for (int i=0; i<n; ++i)
78. index[i] = i;
79.
80. // Find the rescaling factors, one from each row
81. for (int i=0; i<n; ++i)
82. {
83. double c1 = 0;
84. for (int j=0; j<n; ++j)
85. {
86. double c0 = Math.abs(a[i][j]);
87. if (c0 > c1) c1 = c0;
88. }
89. c[i] = c1;
90. }
91.
92. // Search the pivoting element from each column
93. int k = 0;
94. for (int j=0; j<n-1; ++j)
95. {
96. double pi1 = 0;
97. for (int i=j; i<n; ++i)
98. {
99. double pi0 = Math.abs(a[index[i]][j]);
100. pi0 /= c[index[i]];
101. if (pi0 > pi1)
102. {
103. pi1 = pi0;
104. k = i;
105. }
106. }
107.
108. // Interchange rows according to the pivoting order
109. int itmp = index[j];
110. index[j] = index[k];
111. index[k] = itmp;
112. for (int i=j+1; i<n; ++i)
113. {
114. double pj = a[index[i]][j]/a[index[j]][j];
115.
116. // Record pivoting ratios below the diagonal
117. a[index[i]][j] = pj;
118.
119. // Modify other elements accordingly
120. for (int l=j+1; l<n; ++l)
121. a[index[i]][l] -= pj*a[index[j]][l];
122. }
123. }
124. }
125. }
Output:-
Enter the dimension of square matrix:
2
Enter the elements of matrix:
12
34
The Inverse is:
-1.9999999999999998 1.0
1.4999999999999998 -0.49999999999999994
Java Program to Check if it is a Sparse Matrix
1. //This is a sample program to check whether the matrix is sparse matrix or not
2. //The complexity of the code is O(n^2)
3. import java.util.Scanner;
4.
5. public class Sparsity_Matrix
6. {
7. public static void main(String args[])
8. {
9. Scanner sc = new Scanner(System.in);
10. System.out.println("Enter the dimensions of the matrix: ");
11. int m = sc.nextInt();
12. int n = sc.nextInt();
13. double[][] mat = new double[m][n];
14. int zeros = 0;
15. System.out.println("Enter the elements of the matrix: ");
16. for(int i=0; i<m; i++)
17. {
18. for(int j=0; j<n; j++)
19. {
20. mat[i][j] = sc.nextDouble();
21. if(mat[i][j] == 0)
22. {
23. zeros++;
24. }
25. }
26. }
27.
28. if(zeros > (m*n)/2)
29. {
30. System.out.println("The matrix is a sparse matrix");
31. }
32. else
33. {
34. System.out.println("The matrix is not a sparse matrix");
35. }
36.
37. sc.close();
38. }
39. }
Output:-
Enter the dimensions of the matrix:
23
Enter the elements of the matrix:
100
211
The matrix is not a sparse matrix

$ javac Sparsity_matrix.java
$ java Sparsity_matrix
Enter the dimensions of the matrix:
34
Enter the elements of the matrix:
1000
0100
0011
The matrix is a sparse matrix
Bitwise Operators in Java
1. import java.util.Scanner;
2. public class Bitwise_Operation
3. {
4. public static void main(String[] args)
5. {
6. int m, n, x, a;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter First number:");
9. m = s.nextInt();
10. System.out.print("Enter Second number:");
11. n = s.nextInt();
12. while(true)
13. {
14. System.out.println("");
15. System.out.println("Press 1 for Right Shift by 2:");
16. System.out.println("Press 2 for Left Shift by 2:");
17. System.out.println("Press 3 for Bitwise AND:");
18. System.out.println("Press 4 for Bitwise OR by 2:");
19. System.out.println("Press 5 for Bitwise Exclusive OR:");
20. System.out.println("Press 6 for Bitwise NOT:");
21. System.out.println("Press 7 to Exit:");
22. System.out.println("");
23. System.out.print("Option:");
24. x = s.nextInt();
25. switch(x)
26. {
27. case 1:
28. a = m << 2;
29. System.out.println("Result after left shift by 2:"+a);
30. break;
31.
32. case 2:
33. a = n >> 2;
34. System.out.println("Result after right shift by 2:"+a);
35. break;
36.
37. case 3:
38. a = m & n;
39. System.out.println("Result after bitwise AND:"+a);
40. break;
41.
42. case 4:
43. a = m | n;
44. System.out.println("Result after bitwise OR:"+a);
45. break;
46.
47. case 5:
48. a = m ^ n;
49. System.out.println("Result after bitwise Exclusive OR:"+a);
50. break;
51.
52. case 6:
53. a = ~ m;
54. System.out.println("Result after bitwise NOT:"+a);
55. break;
56.
57. case 7:
58. System.exit(0);
59. }
60. }
61. }
62. }
Output:-
Enter First number:5
Enter Second number:6

Press 1 for Right Shift by 2:


Press 2 for Left Shift by 2:
Press 3 for Bitwise AND:
Press 4 for Bitwise OR by 2:
Press 5 for Bitwise Exclusive OR:
Press 6 for Bitwise NOT:
Press 7 to Exit:

Option:3
Result after bitwise AND:4

Press 1 for Right Shift by 2:


Press 2 for Left Shift by 2:
Press 3 for Bitwise AND:
Press 4 for Bitwise OR by 2:
Press 5 for Bitwise Exclusive OR:
Press 6 for Bitwise NOT:
Press 7 to Exit:

Option:7
Java Program to Perform Addition Operation using Bitwise Operators
1. //This is sample program to perform addition operation using bitwise operators.
2. import java.util.Scanner;
3.
4. public class Bitwise_Addition
5. {
6. static int add(int x, int y)
7. {
8. int carry;
9. while(y!=0)
10. {
11. carry = x & y;
12. x = x ^ y;
13. y = carry << 1;
14. }
15. return x;
16. }
17. public static void main(String args[])
18. {
19. Scanner input = new Scanner(System.in);
20. System.out.println("Enter the numbers to be added:");
21. int x = input.nextInt();
22. int y = input.nextInt();
23. System.out.println("The Summation is: "+add(x, y));
24. input.close();
25. }
26. }
Output:-
Enter the numbers to be added:
15
16
The Summation is: 31
Java Program to Multiply Number by 4 using Bitwise Operators
1. import java.util.Scanner;
2. public class Multiply_Bitwise
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number:");
9. n = s.nextInt();
10. int mul = n << 2;
11. System.out.println("Answer:"+mul);
12. }
13. }
Output:-
Enter the number:5
Answer:20
Java Program to Check if Bit Position is Set to One or not
1. import java.util.Scanner;
2. public class Bit_Postion
3. {
4. public static void main(String[] args)
5. {
6. int n, m;
7. String x = "";
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter any Decimal Number:");
10. n = s.nextInt();
11. while(n > 0)
12. {
13. int a = n % 2;
14. x = a + x;
15. n = n / 2;
16. }
17. System.out.print("Enter the position where you want to check:");
18. int l = x.length();
19. m = s.nextInt();
20. if((l - m) >= 0 && (x.charAt(l - m) == '1'))
21. {
22. System.out.println("1 is present at given bit position");
23. }
24. else
25. {
26. System.out.println("0 is present at given bit position");
27. }
28. }
29. }
Output:-
Enter any Decimal Number:6
Enter the position where you want to check:2
1 is present at given bit position
Java Program to Convert Decimal to Binary and Count the Number of 1s
1. import java.util.Scanner;
2. public class Convert
3. {
4. public static void main(String[] args)
5. {
6. int n, count = 0, a;
7. String x = "";
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter any decimal number:");
10. n = s.nextInt();
11. while(n > 0)
12. {
13. a = n % 2;
14. if(a == 1)
15. {
16. count++;
17. }
18. x = a + "" + x;
19. n = n / 2;
20. }
21. System.out.println("Binary number:"+x);
22. System.out.println("No. of 1s:"+count);
23. }
24. }
Output:-
Enter any decimal number:25
Binary number:11001
No. of 1s:3
Java Program to Swap Two Numbers using Bitwise XOR Operation
1. import java.util.Scanner;
2. public class Swap_BitwiseXOR
3. {
4. public static void main(String args[])
5. {
6. int m, n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first number:");
9. m = s.nextInt();
10. System.out.print("Enter the second number:");
11. n = s.nextInt();
12. m = m ^ n;
13. n = m ^ n;
14. m = m ^ n;
15. System.out.println("After Swapping");
16. System.out.println("First number:"+m);
17. System.out.println("Second number:"+n);
18. }
19. }
Output:-
Enter the first number:6
Enter the second number:7
After Swapping
First number:7
Second number:6
Java Program to Count Set Bits using Bitwise Operations
1. import java.util.Scanner;
2. public class Count_One
3. {
4. public static void main(String[] args)
5. {
6. int n, m, count = 0;
7. String x = "";
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the Decimal Number:");
10. n = s.nextInt();
11. while(n > 0)
12. {
13. int a = n % 2;
14. x = a + x;
15. n = n / 2;
16. }
17. int l = x.length();
18. for(int i = 0; i < l; i++)
19. {
20. if(x.charAt(i) == '1')
21. {
22. count++;
23. }
24. }
25. System.out.println("No. of 1's are:"+count);
26. }
27. }
Output:-
Enter the Decimal Number:15
No. of 1's are:4
Java Program to Concatenate Two Strings
1. import java.util.Scanner;
2. public class String_Concatenate
3. {
4. public static void main(String[] args)
5. {
6. String a, b, c;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter first string:");
9. a = s.nextLine();
10. System.out.print("Enter second string:");
11. b = s.nextLine();
12. String_Concatenate obj = new String_Concatenate();
13. c = obj.concat(a, b);
14. System.out.println("New String:"+c);
15. }
16. String concat(String x, String y)
17. {
18. String z;
19. z = x + " " + y;
20. return z;
21. }
22. }
Output:-
Enter first string:hello
Enter second string:world
New String:hello world
Java Program to Remove All Adjacent Duplicates from String
1. // Java Program to Delete Adjacent Pairs of Repeated Characters.
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6. import java.util.Stack;
7.
8. public class AdjacentCharacters {
9. // Function to remove adjacent characters
10. static String removeAdjacentRepeatedCharacters(String str){
11. Stack<Character> stack = new Stack<>();
12. int i;
13. stack.push(str.charAt(0));
14. for(i=1; i<str.length(); i++){
15. if(stack.peek() == str.charAt(i)){
16. stack.pop();
17. continue;
18. }
19. stack.push(str.charAt(i));
20. }
21. StringBuffer obj = new StringBuffer();
22. while(!stack.isEmpty()){
23. obj.append(stack.pop());
24. }
25. return obj.reverse().toString();
26. }
27. // Function to read the input and display the output
28. public static void main(String[] args) {
29. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
30. String str;
31. System.out.println("Enter the string");
32. try {
33. str = br.readLine();
34. } catch (IOException e) {
35. System.out.println("An I/O error occurred");
36. return;
37. }
38. String newString =removeAdjacentRepeatedCharacters(str);
39. System.out.println("The new string is \"" + newString + "\"");
40. }
41. }
Output:-
Case 1 (Simple Test Case):

Enter the string


ABBCCCD
The new string is "ACD"

Case 2 (Simple Test Case - another example):

Enter the string


XYZ
The new string is "XYZ"
Java Program to Reverse Each Word in a String
1.
// Java Program to Reverse a String Word by Word in Place.
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class ReverseWordsInPlace {
7. // Function to reverse the string
8. static String reverseString(String str) {
9. String[] words = str.split(" ");
10. String rev = "";
11. int i, j;
12. for (i = 0; i < words.length; i++) {
13. StringBuffer sb = new StringBuffer(words[i]);
14. rev+=sb.reverse().toString();
15. rev+=" ";
16. }
17. return rev;
18. }
19. // Function to read the input and display the output
20. public static void main(String[] args) {
21. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
22. System.out.println("Enter the text string");
23. String str;
24. try{
25. str=br.readLine();
26. }
27. catch(Exception e){
28. System.out.println("Error reading input");
29. return;
30. }
31. String rev = reverseString(str);
32. System.out.println("The reverse of the string word by word in place is\n");
33. System.out.println(rev);
34. }
35. }
Output:-
Case 1 (Simple Test Case):

Enter the text string


We belong to Russia
The reverse of the string word by word in place is
eW gnoleb ot aissuR

Case 2 (Simple Test Case - another example):

Enter the text string


Hello I am Jane
The reverse of the string word by word in place is
olleH I ma enaJ
Java Program to Find the Largest and Smallest Word in a String
1. // Java program to Find the Largest and Smallest Word.
2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5.
6. public class LargestAndSmallestWord {
7. // Method to split the string and find the largest and smallest word
8. static void printLargestAndSmallestWord(String str){
9. String[] arr=str.split(" ");
10. int i=0;
11. int maxlength,minlength;
12. maxlength=Integer.MIN_VALUE;
13. minlength=Integer.MAX_VALUE;
14. String largest,smallest;
15. largest = smallest = "";
16. for(i=0;i<arr.length;i++){
17. if(arr[i].length() < minlength){
18. smallest=arr[i];
19. minlength=arr[i].length();
20. }
21. if(arr[i].length() > maxlength) {
22. largest=arr[i];
23. maxlength=arr[i].length();
24. }
25. }
26. System.out.println("The largest and smallest word is \"" + largest +
27. "\" and \"" + smallest + "\"");
28. }
29. // Main function to read the string
30. public static void main(String[] args) {
31. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
32. System.out.println("Enter the text string");
33. String str;
34. try{
35. str=br.readLine();
36. }
37. catch(Exception e){
38. System.out.println("Error reading input");
39. return;
40. }
41. printLargestAndSmallestWord(str);
42. }
43. }
Output:-
Case 1 (Simple Test Case):

Enter the text string


I am IronMan
The largest and smallest word is "IronMan" and "I"

Case 2 (Simple Test Case - another example):

Enter the text string


We belong to Russia
The largest and smallest word is "belong" and "We"
Java Program to Find the First Non-repeated Character in a String
1. // Java Program to Find the First non-repeated Character in a String.
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6.
7. public class NonRepeatedCharacter {
8. // Function to find the first non-repeating character
9. static int firstNonRepeatingCharacter(String str){
10. int[] arrayCount = new int[256];
11. int[] arrayIndex = new int[256];
12. int i;
13. for(i=0; i<str.length(); i++){
14. arrayCount[str.charAt(i)]++;
15. arrayIndex[str.charAt(i)] = i;
16. }
17. int index = Integer.MAX_VALUE;
18. for(i=0; i<256; i++){
19. if(arrayCount[i] == 1 && arrayIndex[i] < index)
20. index = arrayIndex[i];
21. }
22. return index;
23. }
24. // Function to read user input
25. public static void main(String[] args) {
26. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
27. String str;
28. System.out.println("Enter the string");
29. try {
30. str = br.readLine();
31. } catch (IOException e) {
32. System.out.println("An I/O error occurred");
33. return;
34. }
35. int index = firstNonRepeatingCharacter(str);
36. if(index < str.length())
37. System.out.println("First Non Repeating Character is "
38. + str.charAt(index));
39. else
40. System.out.println("Each character is repeated");
41. }
42. }
Output:-
Case 1 (Positive Test Case):

Enter the string


Hi this is Marry
First Non-Repeating Character is H
Case 2 (Positive Test Case - another example):

Enter the string


well well finally you are here
First Non-Repeating Character is f

Case 3 (Negative Test Case):

Enter the string


WellWell
Each character is repeated
Java Program to Count the Number of Unique Words
1. //Java Program to Find the Number of Unique Words
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6.
7. public class NumberOfUniqueWords {
8. // Function to calculate the number of unique words
9. static int calculateNoOfUniqueWords(String str) {
10. String[] words = str.split(" ");
11. boolean[] array = new boolean[words.length];
12. int j, i = 0;
13. int count = 0;
14. for (i = 0; i < words.length; i++) {
15. if (!array[i]) {
16. count++;
17. for (j = i + 1; j < words.length; j++) {
18. if (words[j].compareTo(words[i]) == 0) {
19. array[j] = true;
20. count--;
21. }
22. }
23. }
24. }
25. return count;
26. }
27. // Function to read input and display the output
28. public static void main(String[] args) {
29. BufferedReader br = new BufferedReader
30. (new InputStreamReader(System.in));
31. String str;
32. System.out.println("Enter the string");
33. try {
34. str = br.readLine();
35. } catch (IOException e) {
36. System.out.println("An I/O error occurred");
37. return;
38. }
39. int count = calculateNoOfUniqueWords(str);
40. System.out.println("Total number of unique words in \"" +
41. str + "\" are " + count);
42. }
43. }
Output:-
Case 1 (Average Case):

Enter the string


Java is great C++ is also great
Total number of unique words in "Java is great C++ is also great" are 3

Case 2 (Best Case):

Enter the string


I am am I
Total number of unique words in "I am am I" are 0

Case 3 (Worst Case):

Enter the string


We are here
Total number of unique words in "We are here" are 3
Java Program to Check if a Given String is Palindrome
public class Palindrome
{
public static void main(String args[])
{
String a, b = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter a string:");
a = s.nextLine();
int n = a.length();
for(int i = n - 1; i >= 0; i--)
{
b = b + a.charAt(i);
}
if(a.equalsIgnoreCase(b))
{
System.out.println(a+ " is a palindrome.");
}
else
{
System.out.println(a+ " is not a palindrome.");
}
}
}
Output:-
Enter a string: sanfoundry
sanfoundry is not a palindrome
Enter a string: racecar
racecar is a palindrome
Constructor Program in Java
/*
* Java program to demonstrate the use of Constructor
*/

public class Constructor


{
double width;
double height;
double depth;
Constructor()
{
System.out.println("Constructor without parameter");
width = 10;
height = 10;
depth = 10;
}
Constructor(int a, int b, int c)
{
System.out.println("Constructor with parameter");
width = a;
height = b;
depth = c;
}
double volume()
{
return width * height * depth;
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Constructor cuboid1 = new Constructor();
double vol;
vol = cuboid1.volume();
System.out.println("Volume is " + vol);
Constructor cuboid2 = new Constructor(8,11,9);
vol = cuboid2.volume();
System.out.println("Volume is " + vol);
}
}
Output:-
Constructor without parameter
Volume is 1000.0
Constructor with parameter
Volume is 792.0
Constructor Chaining Program in Java
/*
* Constructor Chaining Program in Java using this()
*/

public class ConstructorChaining


{
ConstructorChaining()
{
this(20);
System.out.println("Default constructor of class.");
}
ConstructorChaining(int x)
{
System.out.println("Parameterized (1 parameter) constructor of class.");
System.out.println("The value of x is "+x);
}
ConstructorChaining(int x, int y)
{
this();
System.out.println("Parameterized (2 parameters) constructor of class.");
System.out.println("The value of x and y is " + x + "and " + y + ". "
+ "The sum of x and y is " + (x + y) );
}
public static void main(String... a)
{
ConstructorChaining(11,12);
}
}
Output:-
Parameterized (1 parameter) constructor of class.
The value of x is 20
Default constructor of class.
Parameterized (2 parameters) constructor of class.
The value of x and y is 11and 12. The sum of x and y is 23
Java Program to Illustrate Use of Final Keyword
1. import java.util.Scanner;
2. class Figure
3. {
4. final int length = 5;
5. final int bredth = 4;
6. final void area()
7. {
8. int a = length * bredth;
9. System.out.println("Area:"+a);
10. }
11. }
12. class Rectangle extends Figure
13. {
14. final void rect()
15. {
16. System.out.println("This is rectangle");
17. }
18. }
19. final public class Final_Use extends Rectangle
20. {
21. public static void main(String[] args)
22. {
23. Final_Use obj = new Final_Use();
24. obj.rect();
25. obj.area();
26. }
27. }
Output:-
This is rectangle
Area:20
Java Program to Illustrate the Use of HashCode() Method
1. import java.util.HashMap;
2. public class HashDemo
3. {
4. public static void main(String a[])
5. {
6. HashMap<Price, String> hm = new HashMap<Price, String>();
7. hm.put(new Price("Banana", 20), "Banana");
8. hm.put(new Price("Apple", 40), "Apple");
9. hm.put(new Price("Orange", 30), "Orange"); //creating new object to use as key
to get value
10. Price key = new Price("Banana", 20);
11. System.out.println("Hashcode of the key: "+key.hashCode());
12. System.out.println("Value from map: "+hm.get(key));
13. }
14. }
15. class Price
16. {
17. private String item;
18. private int price;
19. public Price(String itm, int pr)
20. {
21. this.item = itm;
22. this.price = pr;
23. }
24. public int hashCode()
25. {
26. System.out.println("In hashcode");
27. int hashcode = 0;
28. hashcode = price*20;
29. hashcode += item.hashCode();
30. return hashcode;
31. }
32. public boolean equals(Object obj)
33. {
34. System.out.println("In equals");
35. if (obj instanceof Price)
36. {
37. Price pp = (Price) obj;
38. return (pp.item.equals(this.item) && pp.price == this.price);
39. }
40. else
41. {
42. return false;
43. }
44. }
45. public String getItem()
46. {
47. return item;
48. }
49. public void setItem(String item)
50. {
51. this.item = item;
52. }
53. public int getPrice()
54. {
55. return price;
56. }
57. public void setPrice(int price)
58. {
59. this.price = price;
60. }
61. public String toString()
62. {
63. return "item: "+item+" price: "+price;
64. }
65. }
Output:-
In hashcode
In hashcode
In hashcode
In hashcode
Hashcode of the key: 1982479637
In hashcode
In equals
Value from map: Banana
Java Program to Create a Method without Parameters and with Return Type
1. class Box
2. {
3. double width;
4. double height;
5. double depth;
6. double volume()
7. {
8. Scanner s = new Scanner(System.in);
9. System.out.print("enter width : ");
10. double width = s.nextDouble();
11. System.out.print("enter height : ");
12. double height = s.nextDouble();
13. System.out.print("enter depth: ");
14. double depth = s.nextDouble();
15. return width * height * depth;
16. }
17. }
18. class ReturnDemo
19. {
20. public static void main(String args[])
21. {
22. Box cuboid = new Box();
23. double vol;
24. vol = cuboid.volume();
25. System.out.println("Volume is " + vol);
26. }
27. }
Output:-
enter width : 10
enter height : 2
enter depth: 23
Volume is 460.0
Java Program to Check Whether Which One is Executed First, Static Block or the
Static Method
1. public class Demo
2. {
3. static
4. {
5. System.out.println("First static block");
6. }
7.
8. public Demo()
9. {
10. System.out.println("Constructor");
11. }
12.
13. public static String staticString = "Static Variable";
14.
15. static
16. {
17. System.out.println("Second static block and "+ staticString);
18. }
19. static
20. {
21. staticMethod();
22. System.out.println("Third static block");
23. }
24.
25. public static void staticMethod()
26. {
27. System.out.println("Static method");
28. }
29.
30. public static void staticMethod2()
31. {
32. System.out.println("Static method2");
33. }
34. public static void main(String[] args)
35. {
36. Demo obj = new Demo();
37. obj.staticMethod2();
38. }
39. }
Output:-
First static block
Second static block and Static Variable
Static method
Third static block
Constructor
Static method2
Java Program to Count Number of Objects Created for Class
1. public class Number_Objects
2. {
3. static int count=0;
4. Number_Objects()
5. {
6. count++;
7. }
8. public static void main(String[] args)
9. {
10. Number_Objects obj1 = new Number_Objects();
11. Number_Objects obj2 = new Number_Objects();
12. Number_Objects obj3 = new Number_Objects();
13. Number_Objects obj4 = new Number_Objects();
14. System.out.println("Number of objects created:"+count);
15. }
16. }
Output:-
Number of objects created:4
Passing and Returning Objects in Java
1. import java.util.Scanner;
2. public class Object_Pass_Return
3. {
4. int length, breadth, area;
5. Object_Pass_Return area1(Object_Pass_Return object1)
6. {
7. object1 = new Object_Pass_Return();
8. object1.length = this.length;
9. object1.breadth = this.breadth;
10. object1.area = object1.length * object1.breadth;
11. return object1;
12. }
13. Object_Pass_Return area2(Object_Pass_Return object2)
14. {
15. object2 = new Object_Pass_Return();
16. object2.length = this.length + 5;
17. object2.breadth = this.breadth + 6;
18. object2.area = object2.length * object2.breadth;
19. return object2;
20. }
21. public static void main(String[] args)
22. {
23. Object_Pass_Return obj = new Object_Pass_Return();
24. Scanner s = new Scanner(System.in);
25. System.out.print("Enter length:");
26. obj.length = s.nextInt();
27. System.out.print("Enter breadth:");
28. obj.breadth = s.nextInt();
29. Object_Pass_Return a = obj.area1(obj);
30. Object_Pass_Return b = obj.area2(obj);
31. System.out.println("Area:"+a.area);
32. System.out.println("Area:"+b.area);
33. }
34. }
Output:-
Enter length:5
Enter breadth:6
Area:30
Area:120
Java Program to Show the Nesting of Methods
1. import java.util.Scanner;
2. public class Nesting_Methods
3. {
4. int perimeter(int l, int b)
5. {
6. int pr = 12 * (l + b);
7. return pr;
8. }
9. int area(int l, int b)
10. {
11. int pr = perimeter(l, b);
12. System.out.println("Perimeter:"+pr);
13. int ar = 6 * l * b;
14. return ar;
15. }
16. int volume(int l, int b, int h)
17. {
18. int ar = area(l, b);
19. System.out.println("Area:"+ar);
20. int vol ;
21. vol = l * b * h;
22. return vol;
23. }
24. public static void main(String[] args)
25. {
26. Scanner s = new Scanner(System.in);
27. System.out.print("Enter length of cuboid:");
28. int l = s.nextInt();
29. System.out.print("Enter breadth of cuboid:");
30. int b = s.nextInt();
31. System.out.print("Enter height of cuboid:");
32. int h = s.nextInt();
33. Nesting_Methods obj = new Nesting_Methods();
34. int vol = obj.volume(l, b, h);
35. System.out.println("Volume:"+vol);
36. }
37. }
Output:-
Enter length of cuboid:5
Enter breadth of cuboid:6
Enter height of cuboid:7
Perimeter:132
Area:180
Volume:210
Java Program to Calculate Sum of Two Byte Values using Type Casting
1. import java.util.Scanner;
2. public class Byte_Sum
3. {
4. public static void main(String[] args)
5. {
6. byte a, b;
7. int x, y, z;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter first byte value:");
10. a = s.nextByte();
11. x = a;
12. System.out.print("Enter second byte value:");
13. b = s.nextByte();
14. y = b;
15. z = x + y;
16. System.out.println("Result:"+z);
17. }
18. }
Output:-
Enter first byte value:124
Enter second byte value:115
Result:239
Java Program to Find Area of Square, Rectangle and Circle using Method Overloading
1. class OverloadDemo
2. {
3. void area(float x)
4. {
5. System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
6. }
7. void area(float x, float y)
8. {
9. System.out.println("the area of the rectangle is "+x*y+" sq units");
10. }
11. void area(double x)
12. {
13. double z = 3.14 * x * x;
14. System.out.println("the area of the circle is "+z+" sq units");
15. }
16. }
17. class Overload
18. {
19. public static void main(String args[])
20. {
21. OverloadDemo ob = new OverloadDemo();
22. ob.area(5);
23. ob.area(11,12);
24. ob.area(2.5);
25. }
26. }
Output:-
the area of the square is 25.0 sq units
the area of the rectangle is 132.0 sq units
the area of the circle is 19.625 sq units
Java Program to use This Keyword in Inheritance Class
1. class Base
2. {
3. int x = 19;
4. }
5.
6. class Child extends Base
7. {
8. int x = 20;
9. void shows()
10. {
11. System.out.println("The base class data member (x) by Super Keyword :" +
super.x);
12. System.out.println("The child class data member :" + x);
13.
14. }
15. public static void main(String... a)
16. {
17. Child obj = new Child();
18. obj.shows();
19. }
20. }
Output:-
The base class data member (x)by Super Keyword :19
The child class data member :20
Java Program to use Super Keyword in Inheritance Class
1. class Base1
2. {
3. int x = 19;
4. }
5. class Base2 extends Base1
6. {
7. int x = 20;
8. }
9. class Child extends Base2
10. {
11. int x = 21;
12. void show()
13. {
14. System.out.println("Child Class-"+x);
15. System.out.println("Base1 class-"+super.x);
16. System.out.println("Accessing value of data member via This Keyword");
17. System.out.println("Base2 class-"+(((Base1)this).x));
18. }
19. public static void main(String... a)
20. {
21. Child obj = new Child();
22. obj.show();
23. }
24. }
Output:-
Child Class-21
Base1 class-20
Accessing value of data member via This Keyword
Base2 class-19
Java Program to Display Method Overriding in a Class using Inheritance Class
1. class Base
2. {
3. void showme()
4. {
5. System.out.println(" Base class method");
6. }
7. }
8. class Child extends Base
9. {
10. void showme()
11. {
12. System.out.println("Child class method");
13. }
14. public static void main(String... a)
15. {
16. Child obj = new Child();
17. obj.showme();
18. }
19. }
Output:-
Child class method
Java Program to Access Super Class in a Method Overriding
1. class Base
2. {
3. void get()
4. {
5. System.out.println(" Base class method via Super keyword");
6. }
7. }
8. class Child extends Base
9. {
10. void get()
11. {
12. super.get();
13. System.out.println("Child class method");
14. }
15. public static void main(String... a)
16. {
17. Child obj1 = new Child();
18. obj1.get();
19. }
20. }
Output:-
Base class method via Super keyword
Child class method
Interface Program in Java
/*
* Interface Program in Java
*/

import java.util.Scanner;

interface area
{
public void dimensions();
public void area();
}
public class Interface_Implementation implements area
{
int length,breadth,area;
public void dimensions()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter length:");
length=s.nextInt();
System.out.print("Enter breadth:");
breadth=s.nextInt();
}
public void area()
{
area=length*breadth;
System.out.print("Area:"+area);
}
public static void main(String[] args)
{
Interface_Implementation obj=new Interface_Implementation();
obj.dimensions();
obj.area();
}
}
Output:-
Enter length:6
Enter breadth:7
Area:42
Java Program to Handle the Exception Using Try and Multiple Catch Block
1. import java.io.FileInputStream;
2. import java.util.Scanner;
3.
4. public class Try_Catch
5. {
6. public static void main(String[] args)
7. {
8. int a=5,b=0,c,d,f;
9. try
10. {
11. Scanner s=new Scanner(System.in);
12. System.out.print("Enter a:");
13. a=s.nextInt();
14. System.out.print("Enter b:");
15. b=s.nextInt();
16. System.out.print("Enter c:");
17. c=s.nextInt();
18. d=a/b;
19. System.out.println(d);
20. f=a%c;
21. System.out.println(f);
22. FileInputStream fis = null;
23. /*This constructor FileInputStream(File filename)
24. * throws FileNotFoundException which is a checked
25. * exception*/
26. fis = new FileInputStream("B:/myfile.txt");
27. int k;
28. /*Method read() of FileInputStream class also throws
29. * a checked exception: IOException*/
30. while(( k = fis.read() ) != -1)
31. {
32. System.out.print((char)k);
33. }
34. /*The method close() closes the file input stream
35. * It throws IOException*/
36. fis.close();
37. }
38. catch(IndexOutOfBoundsException e)
39. {
40. System.out.println(e);
41. }
42. catch(NullPointerException e)
43. {
44. System.out.println(e);
45. }
46. catch(ArithmeticException e)
47. {
48. System.out.println(e);
49. }
50. catch(Exception e)
51. {
52. System.out.println(e);
53. }
54. }
55. }
Output:-
Enter a:4
Enter b:5
Enter c:6
0
4
java.io.FileNotFoundException: B:/myfile.txt (No such file or directory)
Java Program to Handle the User Defined Exception using Throw Keyword
1. import java.util.Scanner;
2.
3. class NegativeAmtException extends Exception
4. {
5. String msg;
6. NegativeAmtException(String msg)
7. {
8. this.msg=msg;
9. }
10. public String toString()
11. {
12. return msg;
13. }
14. }
15. public class User_Defined_Exception
16. {
17. public static void main(String[] args)
18. {
19. Scanner s=new Scanner(System.in);
20. System.out.print("Enter Amount:");
21. int a=s.nextInt();
22. try
23. {
24. if(a<0)
25. {
26. throw new NegativeAmtException("Invalid Amount");
27. }
28. System.out.println("Amount Deposited");
29. }
30. catch(NegativeAmtException e)
31. {
32. System.out.println(e);
33. }
34. }
35. }
Output:-
Enter Amount:-5
Invalid Amount
Java Program to Illustrate Use of getChar() and split() Method
1. public class Split_getChar
2. {
3. public static void main(String args[])
4. {
5. String[] a;
6. String b = "Sanfoundary 1000 Java Programs";
7. a = b.split(" ");
8. for (int i = 0; i < a.length; i++)
9. {
10. System.out.println(a[i]);
11. }
12. System.out.println("Using getChar() method:");
13. char c[]=new char[11];
14. b.getChars(0, 11, c, 0);
15. for(int i=0;i<11;i++)
16. {
17. System.out.print(c[i]);
18. }
19. }
20. }
Output:-
Sanfoundary
1000
Java
Programs
Usin getChar() method:
Sanfoundary
Split() String Method Program in Java
1. public class Split_Demo
2. {
3. public static void main(String... a)
4. {
5. String s1 = "HelloJava from JavaGuy";
6. String s2[] = s1.split(" ");
7. String part1 = s2[0];
8. String part2 = s2[1];
9. String part3 = s2[2];
10. System.out.println("The string after spliting is "+part1+ " and "+part2);
11. }
12. }
Output:-
The string after spliting is Hello and Java
String Class Methods Program in Java
1. /*
2. * String Class Methods Program in Java
3. */
4.
5. public class Important_Methods
6. {
7. public static void main(String... a)
8. {
9. String str1 = "Hello";
10. String str2 = "from";
11. String str3 = "JAVA";
12. int len = str1.length();
13. System.out.println("The length of the String str1 using length() is "+len);
14. String str4 = str1.concat(str2).concat(str3);
15. System.out.println("The string after concatenation using concat() is " +str4);
16. char c = str4.charAt(5);
17. System.out.println("The character atindex 5 using charAt() is " +c);
18. String str5 = "AbCdEfGhIjKlMnOpQrStUvWxYz";
19. String str6[]= str5.split("M");
20. String part1 = str6[0];
21. String part2 = str6[1];
22. System.out.println("The string after spliting using split() will be = "+part1+"
"+part2);
23. }
24. }
Output:-
The length of the String str1 using length() is 5
The string after concatenation using concat() is HellofromJAVA
The character atindex 5 using charAt() is f
The string after spliting using split() will be = AbCdEfGhIjKl and nOpQrStUvWxYz
Java Program to Close the Frame using WindowAdapter Class
1. /* Java Program to demonstrate the WindowAdapter Class */
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. class Window_Adapter extends WindowAdapter
6. {
7. static JFrame frame;
8. //Driver function
9. public static void main(String args[])
10. {
11. //Create a frame
12. frame=new JFrame("Window Adapter Class");
13. frame.setBackground(Color.white);
14. frame.setSize(500,500);
15. //Create an object of the class
16. Window_Adapter obj=new Window_Adapter();
17. //Associate WindowListener with frame
18. frame.addWindowListener(obj);
19. frame.setVisible(true);
20. }
21. //function to display status as closing when the frame is closed
22. @Override
23. public void windowClosing(WindowEvent e)
24. {
25. System.out.println("Status of frame : Closing");
26. windowClosed(e);
27. }
28. //function to close the frame
29. @Override
30. public void windowClosed(WindowEvent e)
31. {
32. frame.dispose();
33. }
34. //function to display status as iconified when the frame is minimized
35. @Override
36. public void windowIconified(WindowEvent e)
37. {
38. System.out.println("Status of frame : Iconified");
39. }
40. //function to display status as deiconified when the frame is maximized
41. @Override
42. public void windowDeiconified(WindowEvent e)
43. {
44. System.out.println("Status of frame : Deiconfied");
45. }
46. //function to display status as activated when the frame is active
47. @Override
48. public void windowActivated(WindowEvent e)
49. {
50. System.out.println("Status of frame : Activated");
51. }
52. //function to display status as deactivated when the frame is inactive
53. @Override
54. public void windowDeactivated(WindowEvent e)
55. {
56. System.out.println("Status of frame : Deactivated");
57. }
58. //function to display status as opened when the frame is created
59. @Override
60. public void windowOpened(WindowEvent e)
61. {
62. System.out.println("Status of frame : Opened");
63. }
64. }
Output:-
Here’s the run time test cases for WindowAdapter Class.
Test case 1 – Here’s the runtime output of the windowOpened function.
Test case 2 – Here’s the runtime output of the windowDeactivated function.

Test case 3 – Here’s the runtime output of the windowActivated function.

Test case 4 – Here’s the runtime output of the windowIconified function.


Test case 5 – Here’s the runtime output of the windowDeiconified function.

Test case 6 -Here’s the runtime output of the windowClosing function.


Java Program to Draw a Line using GUI
1. /* Java Program to Draw a Line using GUI */
2. import java.applet.*;
3. import java.awt.*;
4. import java.lang.Math;
5. public class Line extends Applet
6. {
7. //Function to initialize the applet
8. public void init()
9. {
10. setBackground(Color.white);
11. }
12. //Function to draw the line
13. public void paint(Graphics g)
14. {
15. int x1 = (int)(Math.random()*1000)%500;
16. int y1 = (int)(Math.random()*1000)%500;
17.
18. int x2 = (int)(Math.random()*1000)%500;
19. int y2 = (int)(Math.random()*1000)%500;
20.
21. g.drawLine(x1,y1,x2,y2);
22. }
23. }
24. /*
25. <applet code = Line.class width = 500 height = 500>
26. </applet>
27. */
Here’s the run time test cases to draw a line for different input cases.
Test case 1 – To View a Line.
Test case 2 – To View a Line.
Java Program to Implement ArrayBlockingQueue API
1. import java.util.Collection;
2. import java.util.Iterator;
3. import java.util.concurrent.ArrayBlockingQueue;
4. import java.util.concurrent.TimeUnit;
5.
6. public class ArrayBlockingQueueImpl<E>
7. {
8. private ArrayBlockingQueue<E> arrayBlockingQueue;
9.
10. /** Creates an ArrayBlockingQueue with the given (fixed) capacity and default
access policy. **/
11. public ArrayBlockingQueueImpl(int capacity)
12. {
13. arrayBlockingQueue = new ArrayBlockingQueue<E>(capacity);
14. }
15.
16. /** Creates an ArrayBlockingQueue with the given (fixed) capacity and the
specified access policy. **/
17. public ArrayBlockingQueueImpl(int capacity, boolean fair)
18. {
19. arrayBlockingQueue = new ArrayBlockingQueue<>(capacity, fair);
20. }
21.
22. /** Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified
access policy and
23. * initially containing the elements of the given collection, added in traversal
order of the
24. * collection's iterator.
25. **/
26. public ArrayBlockingQueueImpl(int capacity, boolean fair, Collection<? extends
E> c)
27. {
28. arrayBlockingQueue = new ArrayBlockingQueue<E>(capacity, fair, c);
29. }
30.
31. /**
32. * Inserts the specified element at the tail of this queue if it is possible
33. * to do so immediately without exceeding the queue's capacity, returning
34. * true upon success and throwing an IllegalStateException if this queue is full.
35. **/
36. boolean add(E e)
37. {
38. return arrayBlockingQueue.add(e);
39. }
40.
41. /** Atomically removes all of the elements from this queue. **/
42. void clear()
43. {
44. arrayBlockingQueue.clear();
45. }
46.
47. /** Returns true if this queue contains the specified element. **/
48. public boolean contains(Object o)
49. {
50. return arrayBlockingQueue.contains(o);
51. }
52.
53. /** Removes all available elements from this queue and adds them to the given
collection. **/
54. public int drainTo(Collection<? super E> c)
55. {
56. return arrayBlockingQueue.drainTo(c);
57. }
58.
59. /** Removes at most the given number of available elements from this queue
60. * and adds them to the given collection.
61. **/
62. public int drainTo(Collection<? super E> c, int maxElements)
63. {
64. return arrayBlockingQueue.drainTo(c, maxElements);
65. }
66.
67. /** Returns an iterator over the elements in this queue in proper sequence. **/
68. public Iterator<E> iterator()
69. {
70. return arrayBlockingQueue.iterator();
71. }
72.
73. /**
74. * Inserts the specified element at the tail of this queue if it is possible
75. * to do so immediately without exceeding the queue's capacity, returning
76. * true upon success and false if this queue is full.
77. **/
78. public boolean offer(E e)
79. {
80. return arrayBlockingQueue.offer(e);
81. }
82.
83. /**
84. * Inserts the specified element at the tail of this queue, waiting up to
85. * the specified wait time for space to become available if the queue is
86. * full.
87. **/
88. public boolean offer(E e, long timeout, TimeUnit unit) throws
InterruptedException
89. {
90. return arrayBlockingQueue.offer(e, timeout, unit);
91. }
92.
93. /**
94. * Retrieves, but does not remove, the head of this queue, or returns null
95. * if this queue is empty.
96. **/
97. public E peek()
98. {
99. return arrayBlockingQueue.peek();
100. }
101.
102. /**
103. * Retrieves and removes the head of this queue, or returns null if this
104. * queue is empty.
105. **/
106. public E poll()
107. {
108. return arrayBlockingQueue.poll();
109. }
110.
111. /**
112. * Retrieves and removes the head of this queue, waiting up to the
specified
113. * wait time if necessary for an element to become available.
114. **/
115. public E poll(long timeout, TimeUnit unit) throws InterruptedException
116. {
117. return arrayBlockingQueue.poll(timeout, unit);
118. }
119.
120. /**
121. * Inserts the specified element at the tail of this queue, waiting for
122. * space to become available if the queue is full.
123. **/
124. public void put(E e) throws InterruptedException
125. {
126. arrayBlockingQueue.put(e);
127. }
128.
129. /**
130. * Returns the number of additional elements that this queue can ideally
(in
131. * the absence of memory or resource constraints) accept without
blocking.
132. **/
133. public int remainingCapacity()
134. {
135. return arrayBlockingQueue.remainingCapacity();
136. }
137.
138. /**
139. * Removes a single instance of the specified element from this queue, if it
140. * is present.
141. **/
142. public boolean remove(Object o)
143. {
144. return arrayBlockingQueue.remove(o);
145. }
146.
147. /** Returns the number of elements in this queue. **/
148. public int size()
149. {
150. return arrayBlockingQueue.size();
151. }
152.
153. /**
154. * Retrieves and removes the head of this queue, waiting if necessary until
155. * an element becomes available
156. **/
157. public E take() throws InterruptedException
158. {
159. return arrayBlockingQueue.take();
160. }
161.
162. /**
163. * Returns an array containing all of the elements in this queue, in proper
164. * sequence.
165. **/
166. public Object[] toArray()
167. {
168. return arrayBlockingQueue.toArray();
169. }
170.
171. /**
172. * Returns an array containing all of the elements in this queue, in proper
173. * sequence; the runtime type of the returned array is that of the specified
174. * array.
175. **/
176. public <T> T[] toArray(T[] a)
177. {
178. return arrayBlockingQueue.toArray(a);
179. }
180.
181. /** Returns a string representation of this collection. **/
182. public String toString()
183. {
184. return arrayBlockingQueue.toString();
185. }
186.
187. public static void main(String... arg)
188. {
189. ArrayBlockingQueueImpl<Integer> arrayBlockingQueue = new
ArrayBlockingQueueImpl<Integer>(10);
190. try
191. {
192. arrayBlockingQueue.put(100);
193. arrayBlockingQueue.put(200);
194. arrayBlockingQueue.put(300);
195. } catch (InterruptedException e)
196. {
197. e.printStackTrace();
198. }
199. arrayBlockingQueue.add(400);
200. arrayBlockingQueue.add(500);
201.
202. System.out.println("the elements of the arrayblockingqueue is ");
203. Iterator<Integer> itr = arrayBlockingQueue.iterator();
204. while (itr.hasNext())
205. {
206. System.out.print(itr.next() + "\t");
207. }
208. System.out.println();
209. arrayBlockingQueue.offer(600);
210. arrayBlockingQueue.offer(700);
211. System.out.println("the peak element of the arrayblockingqueue is(by
peeking) "
212. + arrayBlockingQueue.peek());
213. System.out.println("the peak element of the arrayblockingqueue is(by
polling) "
214. + arrayBlockingQueue.poll());
215. System.out.println("the remaining capacity is " +
arrayBlockingQueue.remainingCapacity());
216. System.out.println("element 300 removed " +
arrayBlockingQueue.remove(300));
217. System.out.println("the arrayblockingqueue contains 400 :" +
arrayBlockingQueue.contains(400));
218. System.out.println("the hash arrayblockingqueue contains 100 :" +
arrayBlockingQueue.contains(100));
219. System.out.println("the size of the arrayblocingqueue is " +
arrayBlockingQueue.size());
220. System.out.println(arrayBlockingQueue);
221. }
222. }
Output:-
the elements of the arrayblockingqueue is
100 200 300 400 500
the peak element of the arrayblockingqueue is(by peeking) 100
the peak element of the arrayblockingqueue is(by polling) 100
the remaining capacity is 4
element 300 removed true
the arrayblockingqueue contains 400 :true
the hash arrayblockingqueue contains 100 :false
the size of the arrayblocingqueue is 5
[200, 400, 500, 600, 700]
Java Program to Implement Selection Sort
1. /*
2. * Java Program to Implement Selection Sort
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class SelectionSort */
8. public class SelectionSort
9. {
10. /* Selection Sort function */
11. public static void sort( int arr[] ){
12. int N = arr.length;
13. int i, j, pos, temp;
14. for (i = 0; i < N-1; i++)
15. {
16. pos = i;
17. for (j = i+1; j < N; j++)
18. {
19. if (arr[j] < arr[pos])
20. {
21. pos = j;
22. }
23. }
24. /* Swap arr[i] and arr[pos] */
25. temp = arr[i];
26. arr[i] = arr[pos];
27. arr[pos]= temp;
28. }
29. }
30. /* Main method */
31. public static void main(String[] args)
32. {
33. Scanner scan = new Scanner( System.in );
34.
35. System.out.println("Selection Sort Test\n");
36. int n, i;
37. /* Accept number of elements */
38. System.out.println("Enter number of integer elements");
39. n = scan.nextInt();
40. /* Create integer array on n elements */
41. int arr[] = new int[ n ];
42. /* Accept elements */
43. System.out.println("\nEnter "+ n +" integer elements");
44. for (i = 0; i < n; i++)
45. arr[i] = scan.nextInt();
46. /* Call method sort */
47. sort(arr);
48. /* Print sorted Array */
49. System.out.println("\nElements after sorting ");
50. for (i = 0; i < n; i++)
51. System.out.print(arr[i]+" ");
52. System.out.println();
53. }
54.
55. }
Output:-
Enter number of integer elements
20

Enter 20 integer elements


999 921 823 816 767 712 698 657 532 412 391 323 287 256 225 162 123 64 24 6

Elements after sorting


6 24 64 123 162 225 256 287 323 391 412 532 657 698 712 767 816 823 921 999
Java Program to Implement Bubble Sort
1. //This is a java program to sort numbers using bubble sort
2. import java.util.Random;
3.
4. public class Bubble_Sort
5. {
6. static int[] sort(int[] sequence)
7. {
8. // Bubble Sort
9. for (int i = 0; i < sequence.length; i++)
10. for (int j = 0; j < sequence.length - 1; j++)
11. if (sequence[j] > sequence[j + 1])
12. {
13. sequence[j] = sequence[j] + sequence[j + 1];
14. sequence[j + 1] = sequence[j] - sequence[j + 1];
15. sequence[j] = sequence[j] - sequence[j + 1];
16. }
17. return sequence;
18. }
19.
20. static void printSequence(int[] sorted_sequence)
21. {
22. for (int i = 0; i < sorted_sequence.length; i++)
23. System.out.print(sorted_sequence[i] + " ");
24. }
25.
26. public static void main(String args[])
27. {
28. System.out
29. .println("Sorting of randomly generated numbers using BUBBLE SORT");
30. Random random = new Random();
31. int N = 20;
32. int[] sequence = new int[N];
33.
34. for (int i = 0; i < N; i++)
35. sequence[i] = Math.abs(random.nextInt(1000));
36.
37. System.out.println("\nOriginal Sequence: ");
38. printSequence(sequence);
39.
40. System.out.println("\nSorted Sequence: ");
41. printSequence(sort(sequence));
42. }
43. }
Output:-
Sorting of randomly generated numbers using BUBBLE SORT

Original Sequence:
307 677 574 88 325 851 676 357 172 932 166 450 60 538 964 987 706 690 919 518
Sorted Sequence:
60 88 166 172 307 325 357 450 518 538 574 676 677 690 706 851 919 932 964 987
Java Program to Implement Stooge Sort Algorithm
1. //This is a java program to sort numbers using Stooge Sort
2. import java.util.Random;
3.
4. public class Stooge_Sort
5. {
6.
7. public static int N = 20;
8. public static int[] sequence = new int[N];
9.
10. public static int[] stoogeSort(int[] L, int i, int j)
11. {
12. if (L[j] < L[i])
13. {
14. int swap = L[i];
15. L[i] = L[j];
16. L[j] = swap;
17. }
18. if ((j - i + 1) >= 3)
19. {
20. int t = (j - i + 1) / 3;
21. stoogeSort(L, i, j - t);
22. stoogeSort(L, i + t, j);
23. stoogeSort(L, i, j - t);
24. }
25. return L;
26. }
27.
28. public static void printSequence(int[] sorted_sequence)
29. {
30. for (int i = 0; i < sorted_sequence.length; i++)
31. System.out.print(sorted_sequence[i] + " ");
32. }
33.
34. public static void main(String[] args)
35. {
36. Random random = new Random();
37. System.out
38. .println("Sorting of randomly generated numbers using STOOGE SORT");
39.
40. for (int i = 0; i < N; i++)
41. sequence[i] = Math.abs(random.nextInt(1000));
42.
43. System.out.println("\nOriginal Sequence: ");
44. printSequence(sequence);
45.
46. System.out.println("\nSorted Sequence: ");
47. printSequence(stoogeSort(sequence, 0, sequence.length - 1));
48. }
49. }
Output:-
Sorting of randomly generated numbers using STOOGE SORT

Original Sequence:
213 931 260 34 184 706 346 849 279 918 781 242 995 2 187 378 634 965 138 843
Sorted Sequence:
2 34 138 184 187 213 242 260 279 346 378 634 706 781 843 849 918 931 965 995

You might also like