Java Codes 1 Invert
Java Codes 1 Invert
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
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
import java.util.Scanner;
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
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;
1000
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 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):
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
//This is sample program to calculate the GCD and LCM of two given numbers
import java.util.Scanner;
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
257184 800128
Case 2 (Positive test case - local maxima is at the beginning of the array):
Case 3 (Positive test case - local maxima is at the end of the array):
package com.sanfoundry.numerical;
import java.util.Scanner;
1
0 1
0 0 0
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):
$ 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
Option:3
Result after bitwise AND:4
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):
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.
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