0% found this document useful (0 votes)
1 views97 pages

100 Common Java Programs

java Programmes

Uploaded by

sk5881998
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
1 views97 pages

100 Common Java Programs

java Programmes

Uploaded by

sk5881998
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 97

Table Of Contents

1. Fahrenheit To Celsius Program


2. Largest Of Three Numbers Program
3. SWAP Two Numbers Program
4. Program To Pass Or Fail In Exam
5. Prime Number Program
6. Reverse A Number Program
7. Check Vowel Or Consonant Program
8. Leap Year Program
9. Factorial Program
10. Binary to Decimal
11. Get IP Address Program
12.Find Power of a Number
13. Area of a Triangle
14. Calculate Simple Interest
15. Product of 2 Numbers
16. Area of a circle
17. Fibonacci Series
18. Print Ascii Value
19. Find nth Prime Number
20. Convert string to float
21. Palindrome Program
22. Duplicate elements
23. Natural Number Program
24 Extract Digits from a Given Number
25 Convert Days into Years, Months and Days
26 Binary Equivalent of an Integer
27 Linear Search
28 Binary Search
29 Selection Sort
30 Greatest of two numbers
31. Sum of digits of a number
32. Reverse a number Using recursion
33. Armstrong number Program
34. ATM Transaction Program
35. Find GCD of Two Numbers
36. right rotate the elements of an array
37. frequency of each element
38. Find second smallest element in an array
39. Compute Quotient and Remainder
40. Check Alphabet or not
41. Display Alphabets (A to Z) using loop
42. Count Number of Digits
43. Display Prime Numbers Between Two Intervals
44. Display Armstrong Number Between Two Intervals
45. Print a Multi-dimensional Array
46. Concatenate Two Arrays
47. Print an Array using standard library
48. Convert String to Date
49. Round a Number to n Decimal Places
50. Program to Compare Strings Using ==
51. Program to Compare Strings Using equals()
52. Check if a string is numeric
53. Convert char to int using parseInt()
54. Simple Calculator Program
55. Calculate Average Program
56. Find Frequency of Character
57. Print a 2 D Array or Matrix
58. Ternary operator Example
59. Java Substring Example
60. Find Square root Program
61. Find Max and Min EXAMPLE
62. Random lowercase letters
63. Integer.bitCount() Example
64. Java charAt() Example
65. Java String.join() Method
66. Reverse a Sentence Using Recursion
67. Convert long type into int
68. convert int type to long
69. Remove All Whitespaces from a String
70. Convert Octal to Decimal
71. Add Two Binary Strings
72. Remove Leading Zeros
73. print Even length words
74. Find a Sublist in a List
75. Split a List into Two Halves
76. Remove a SubList from a List
77. Find Min and Max in a List
78. Traverse in a Directory.
79. Search for a File in a Directory
80. Find Current Working Directory
81. Delete a directory
82. Check if a Directory is Empty or Not
83. Find common elements in two ArrayLists
84. Add Element at First and Last Position
85. Array Copy in Java
86. Swapping Pairs of Characters
87. Make a File Read-Only
88. Left Triangle Star Pattern.
89. Right Triangle Star Pattern.
90. Left Down Triangle Star Pattern
91. Right Down Triangle Star Pattern
92. Square Hollow Pattern
93. Rhombus Pattern
94. Diamond Star Pattern
95. Triangle Star Pattern
96. Reverse Triangle Pattern
97. Mirror Image Triangle Pattern
98. Right Pascal’s Triangle
99. Zero-One Triangle Pattern
100. Butterfly Star Pattern
1. Fahrenheit To Celsius Program

import java.util.*;
class FahrenheitToCelsius
{
public static void main(String[] args)
{
float temperatue;
Scanner in = new Scanner(System.in);
System.out.println("Enter Fahrenheit: ");
temperatue = in.nextInt();
temperatue = ((temperatue - 32)*5)/9;
System.out.println("Temperatue in Celsius = "
+ temperatue);

}
}

Output:
Enter Fahrenheit:
98
Temperatue in Celsius = 36.666668
2. Largest Of Three Numbers Program

import java.util.Scanner;
class LargestOfThreeNumbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct.");
}
}

Output:
Enter three integers
100
400
200
Second number is the largest.
3. SWAP Two Numbers Program

import java.util.Scanner;
class SwapTwoNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}

Output:
Enter x and y
100
200
Before Swapping
x = 100
y = 200
After Swapping
x = 200
y = 100
4. Program To Pass Or Fail In Exam

import java.util.Scanner;
class PassOrFailInExam
{
public static void main(String[] args)
{
int marksObtained, passingMarks;
char grade;
passingMarks = 35;
Scanner input = new Scanner(System.in);
System.out.println("Input marks scored by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
if (marksObtained > 95)
grade = 'A';
else if (marksObtained > 80)
grade = 'B';
else if (marksObtained > 65)
grade = 'C';
else
grade = 'D';
System.out.println("You passed the exam with grade: " + grade);
}
else {
grade = 'F';
System.out.println("You failed with grade: " + grade);
}
}
}
Output:
Input marks scored by you
70
You passed the exam with grade: C
5. Prime Number Program

import java.util.Scanner;
class CheckPrime
{
public static void main(String args[])
{
int i, num, flag = 1;
System.out.print("Enter the number :");
Scanner s = new Scanner(System.in);
num = s.nextInt();
for(i = 2; i < num; i++)
{
if(num % i == 0)
{
flag = 0;
break;
}
}
if(flag == 1)
System.out.println(""+num+" is a prime number.");
else
System.out.println(""+num+" is not a prime number.");
}
}
OutPut:
Enter the number :29
29 is a prime number.

6. Reverse A Number Program

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

OutPut:
Enter Number: 674
Reverse of a Number is 476
7. Check Vowel Or Consonant Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

class Vowel_Consonant
{
public static void main(String[] args) throws Exception
{
char ch;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the character you want to check:");
ch = (char) bf.read();
switch(ch)
{
case 'a':
System.out.println("Character "+ch+" is vowel");
break;
case 'e':
System.out.println("Character "+ch+" is vowel");
break;
case 'i':
System.out.println("Character "+ch+" is vowel");
break;
case 'o':
System.out.println("Character "+ch+" is vowel");
break;
case 'u':
System.out.println("Character "+ch+" is vowel");
break;
default:
System.out.println("Character "+ch+" is consonant");
break;
}
}
}

Output:
Enter the character you want to check:y
Character y is consonant

8. Leap Year Program

import java.util.Scanner;

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:2000
Year 2000 is a Leap Year

9. Factorial Program

import java.util.Scanner;

class Factorial
{
public static void main(String[] args)
{
long n, fact = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter Any Number: ");
n = s.nextInt();
for(int i = 1; i <= n; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+n+" is "+fact);
}
}
Output:
Enter Any Number: 7
Factorial of 7 is 5040

10. Binary to Decimal Program

class BinaryToDecimal
{
public static int getDecimal(int binary){
int decimal = 0;
int n = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
n++;
}
}
return decimal;
}

public static void main(String args[]){


System.out.println("Binary :1010 | Decimal : "+getDecimal(1010) + "\n");
System.out.println("Binary :1010 | Decimal : "+getDecimal(11111));
}}

Output:
Binary :1010 | Decimal : 10
Binary :1010 | Decimal : 31
11. Get IP Address Program

import java.net.InetAddress;

public class IPAddress


{
public static void main(String args[]) throws Exception
{
InetAddress IP = InetAddress.getLocalHost();
System.out.println("IP Address := "
+IP.getHostAddress());
}
}

OutPut:
IP Address := 10.8.19.20

12.Find Power of a Number

import java.util.Scanner;
public class Power
{
public static void main(String args[])
{
int x;
double y;
System.out.print("Enter any number: ");
Scanner s = new Scanner(System.in);
x = s.nextInt();
y = Math.pow(x , 2);
System.out.println("Square of "+x+" is :"+y);
}
}
OutPut:
Enter any number: 16
Square of 16 is :256.0

13. Area of a Triangle

public class Program{


static void area(double a, double b, double c){
double s = (a+b+c)/2;
s = s*(s-a)*(s-b)*(s-c);
System.out.println("Area of triangle is\n "
+ Math.sqrt(s));
}
public static void main(String[] args) {
double a,b,c;
a = 4;
b = 5;
c = 6;
if(a<0 || b<0 || c<0){
System.out.println("Invalid Input");
return;
}
area(a,b,c);
}
}
Output:
Area of triangle is
9.921567416492215

14. Calculate Simple Interest

import java.util.Scanner;

class Simple_Interest
{
public static void main(String args[])
{
float p, r, t;
Scanner s = new Scanner(System.in);
System.out.print("Enter the Principal : ");
p = s.nextFloat();
System.out.print("Enter the Rate of interest : ");
r = s.nextFloat();
System.out.print("Enter the Time period : ");
t = s.nextFloat();
float si;
si = (r * t * p) / 100;
System.out.print("The Simple Interest is : " + si);
}
}
Output:
Enter the Principal : 100
Enter the Rate of interest : 5
Enter the Time period : 2
The Simple Interest is : 10.0
15. Product of 2 Numbers

import java.io.*;
import java.util.*;

class Program
{
static int product(int x, int y)
{
if (x < y)
return product(y, x);
else if (y != 0)
return (x + product(x, y - 1));
else
return 0;
}
// Driver Code
public static void main (String[] args)
{
int x = 25, y = 12;
System.out.println(product(x, y));
}
}

OutPut:
Product Of Two Number Is:
300
16. Area of a circle

//Area = pi * r2
//where r is radius of circle
class Program
{
static final double PI = Math.PI;
static double findArea(int r)
{
return PI * Math.pow(r, 2);
}
public static void main(String[] args)
{
System.out.println("Area is " + findArea(5));
}
}

OutPut:
Area is 78.53981633974483
17. Fibonacci Series

class Fibonacci{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);
//n-2 because 2 numbers are already printed
}
}
18. Print Ascii Value

public class Programs


{
public static void main(String[] args)
{
// character whose ASCII value to be found
char ch1 = 'a';
char ch2 = 'b';
// variable that stores the integer value of the character
int asciivalue1 = ch1;
int asciivalue2 = ch2;
System.out.println("The ASCII value of " + ch1 + " is: " + asciivalue1);
System.out.println("The ASCII value of " + ch2 + " is: " + asciivalue2);
}
}

19. Find nth Prime Number

import java.util.Scanner;
public class NthPrimeNum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n to compute the nth prime number: ");

int n = sc.nextInt();
int num=1, count=0, i;
while (count < n)
{
num=num+1;
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
break;
}
}
if (i == num)
{
count = count+1;
}
}
System.out.println("The " +n +"th prime number is:
" + num);
}
}

20. Convert string to float

public class Program


{
public static void main(String args[])
{
String s="23.6";
float f=Float.parseFloat("23.6");
System.out.println(f);
}
}
21. Palindrome Program

import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter your Input");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("palindrome.");
else
System.out.println("Not a palindrome.");
}
}

Output:
Enter your Input 4554
4554
palindrome
22. duplicate elements

public class Program


{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3,4,2};
System.out.println("Duplicate elements : ");
//Searches duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}
Output:
Duplicate elements :
2
2
3
4
2
8
23. Natural Number Program

import java.util.Scanner;

class HelloWorld {
public static void main(String[] args) {
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
HelloWorld obj = new HelloWorld();
System.out.print("Natural numbers till "+n+" :");
obj.natural(n,1);
}
int natural(int y, int i)
{
if(i <= y)
{
System.out.print(i+" ");
return(natural(y,++i));
}
return 1;
}
}
Output:
Enter any number:10
Natural numbers till 10 :1 2 3 4 5 6 7 8 9 10
24 Extract Digits from a Given Number

import java.util.Scanner;
public class Extract_Digits
{
public static void main(String args[])
{
int n, m, a, i = 1, counter = 0;
Scanner s=new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
m = n;
while(n > 0)
{
n = n / 10;
counter++;
}
while(m > 0)
{
a = m % 10;
System.out.println("Digit at position "
+counter+": "+a + " \n");
m = m / 10;
counter--;
}
}
}
Output:
Enter any number:4789
Digit at position 4: 9
Digit at position 3: 8
Digit at position 2: 7
Digit at position 1: 4

25 Convert Days into Years, Months and Days

import java.util.Scanner;
public class Year_Week_Day
{
public static void main(String args[])
{
int m, year, week, day;
Scanner s = new Scanner(System.in);
System.out.print("Enter days:");
m = s.nextInt();
year = m / 365;
m = m % 365;
System.out.println("No. of years: "+year + " \n");
week = m / 7;
m = m % 7;
System.out.println("No. of weeks :"+week + " \n");
day = m;
System.out.println("No. of days :"+day + " \n");
}
}
Output:
Enter days:789
No. of years: 2
No. of weeks :8
No. of days :3
26 Binary Equivalent of an Integer

import java.util.Scanner;
public class Binary_Rec
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
n = s.nextInt();
Binary_Rec obj = new Binary_Rec();
String m = obj.Binary(n);
System.out.println("Answer:"+m);
}
String Binary(int x)
{
if(x > 0)
{
int a = x % 2;
x = x / 2;
return a + "" + Binary(x);
}
return "";
}
}
Output:
Enter the number:45
Answer:101101
27 Linear Search

import java.util.Scanner;
public class LinearSearch {
public static void main(String args[]) {
int array[] = {1, 2, 3, 4, 5};
int search, i;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number to search:");
search = input.nextInt();
for (i = 0; i < array.length; i++) {
if (array[i] == search) {
System.out.println(search + " is present at location " + (i + 1) + ".");
break;
}
}
if (i == array.length) {
System.out.println(search + " is not present in the array.");
}
}
}
Output:
Enter the number to search:
4
4 is present at location 4.
28. Binary Search

class Programs
{
public static int binarySearch(int arr[], int first,
int last, int key)
{
if (last>=first){
int mid = first + (last - first)/2;
if (arr[mid] == key){
return mid;
}
if (arr[mid] > key){
return binarySearch(arr, first, mid-1, key);
}else{
return binarySearch(arr, mid+1, last, key);
}
}
return -1;
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
int result = binarySearch(arr,0,last,key);
if (result == -1)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: "+result);
}
}
Output:
Element is found at index: 2
29 Selection Sort

public class Program


{
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
30 Greatest of two numbers

class HelloWorld {
public static void main(String[] args)
{
int num1 = 100, num2 = 200, temp;

if (num1 == num2)
System.out.println ("Both numbers are Equal\n");
else
{
temp = num1 > num2 ? num1 : num2;
System.out.println (temp + " is the largest");
}
}
}

Output:
200 is the largest
31. Sum of digits of a number

class HelloWorld {
public static void main(String[] args)
{
int num = 132456;
System.out.println ("Sum of digits : "
+ getSumOfDigits(num));
}
static int getSumOfDigits(int num)
{
if (num == 0)
return 0;
return (num % 10) + getSumOfDigits(num / 10);
}
}

Output:
Sum of digits : 21

32. Reverse a number Using recursion

class HelloWorld {
public static void main(String[] args)
{
int num = 1234, reverse = 0;
System.out.println ("Reversed Number is : "
+ getReverse(num, reverse));
}

static int getReverse (int num, int reverse)


{
if (num == 0)
return reverse;
int rem = num % 10;
reverse = reverse * 10 + rem;

return getReverse (num / 10, reverse);


}
}
Output:
Reversed Number is : 4321

33. Armstrong number Program

class HelloWorld {
public static void main(String[] args)
{
int num = 153, reverse = 0; //1634
int len = order(num);

if (num == getArmstrongSum(num, len))


System.out.println(num + " is an Armstrong Number");
else
System.out.println(num + " is not an Armstrong Number");
}

private static int getArmstrongSum(int num, int order) {


if(num == 0)
return 0;
int digit = num % 10;

return (int) Math.pow(digit, order) +


getArmstrongSum(num/10, order);
}

private static int order(int num) {


int len = 0;
while (num!=0)
{
len++;
num = num/10;
}
return len;
}
}
Output:
153 is an Armstrong Number

34. ATM Transaction Program

import java.util.Scanner;
public class Program
{
public static void main(String args[] )
{
int balance = 10000, withdraw, deposit;
Scanner s = new Scanner(System.in);
while(true)
{
System.out.println("=======ATM=======");
System.out.println("Choose 1 for Withdraw");
System.out.println("Choose 2 for Deposit");
System.out.println("Choose 3 for Check Balance");
System.out.println("Choose 4 for EXIT");
System.out.print("Enter your Choice :");
int n = s.nextInt();
switch(n)
{
case 1:
System.out.print("Enter money to be withdrawn:");
withdraw = s.nextInt();
if(balance >= withdraw)
{
balance = balance - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
break;

case 2:
System.out.print("Enter money to be deposited:");
deposit = s.nextInt();
balance = balance + deposit;
System.out.println("Your Money has been successfully depsited");
System.out.println("");
break;

case 3:
System.out.println("Balance : "+balance);
System.out.println("");
break;
case 4:
System.exit(0);
}
}
}
}

Output:
=======ATM=======
Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for EXIT
Enter your Choice :1
Enter money to be withdrawn:5000
Please collect your money

=======ATM=======
Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for EXIT
Enter your Choice :2
Enter money to be deposited:20000
Your Money has been successfully deposited
35. Find GCD of Two Numbers

class HelloWorld {
public static void main(String[] args)
{
int Num1=24, Num2=8, Temp, GCD=0;
while(Num2 != 0)
{
Temp = Num2;
Num2 = Num1 % Num2;
Num1 = Temp;
}
GCD = Num1;
System.out.println("\n GCD = " + GCD);
}
}

Output:
GCD = 4

36. right rotate the elements of an array

class RotateRight
{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 3, 4, 5};
int n = 2; //No of Position to rotate
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for(int i = 0; i < n; i++){
int j, last;
last = arr[arr.length-1];
for(j = arr.length-1; j > 0; j--){
arr[j] = arr[j-1];
}
arr[0] = last;
}
System.out.println();
System.out.println("Array after right rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}
Output:
Original array:
12345
Array after right rotation:
45123

37. frequency of each element

public class Frequency


{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 8, 3, 2, 9, 2, 5, 1};
int [] freq = new int [arr.length];
int visited = -1;
for(int i = 0; i < arr.length; i++){
int count = 1;
for(int j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
count++;
freq[j] = visited;
}
}
if(freq[i] != visited)
freq[i] = count;
}
for(int i = 0; i < freq.length; i++){
if(freq[i] != visited)
System.out.println( arr[i] + " -- " + freq[i] + "\n");
}
}
}

Output:
1 -- 2
2 -- 3
8 -- 1
3 -- 1
9 -- 1
5 -- 1
38. Find second smallest element in an array

class HelloWorld
{
static int secondSmallest(int arr[], int n)
{
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;

for (int i=0; i < n; i++){


if(arr[i] < first){ second = first; first = arr[i]; }
else if(second>arr[i])
second = arr[i];
}
return second;
}
public static void main(String[] args) {
int arr[] = {12, 13, 1, 11, 34, 11};
int n = arr.length;
System.out.print("Second Smallest:" + secondSmallest(arr, n));

}
}

39. Compute Quotient and Remainder


class HelloWorld {

public static void main(String[] args)


{
int dividend = 33, divisor = 4;

int quotient = dividend / divisor;


int remainder = dividend % divisor;

System.out.println("Quotient = " + quotient);


System.out.println(" Remainder = " + remainder);
}
}

40. Check Alphabet or not

class HelloWorld {

public static void main(String[] args)


{
char c = 'a';

if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
}

41. Display Alphabets (A to Z) using loop


public static void main(String[] args)
{
char c;
// Upper case
for(c = 'A'; c <= 'Z'; ++c)
System.out.print(c + " ");

System.out.println(" ");
// Lower case
for(c = 'a'; c <= 'z'; ++c)
System.out.print(c + " ");

}
42. Count Number of Digits

public class Main {

public static void main(String[] args)


{

int count = 0, num = 107853;

while (num != 0) {
// num = num/10
num /= 10;
++count;
}

System.out.println("Number of digits: " + count);


}
}

Output:
Number of digits: 6

43. Display Prime Numbers Between Two Intervals

public class Prime


{
public static void main(String[] args)
{
int low = 10, high = 100;
while (low < high) {
boolean flag = false;

for(int i = 2; i <= low/2; ++i)


{
if(low % i == 0) {
flag = true;
break;
}
}
if (!flag && low != 0 && low != 1)
System.out.print(low + " ");
++low;
}
}
}

Output:
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89 97

44. Display Armstrong Number Between Two Intervals

class Main
{
public static void main(String[] args)
{
int low = 100, high = 500;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0)
{
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}

if (result == number) {
System.out.print(number + " ");
}
}
}
}
Output:
153 370 371 407

45. Print a Multi-dimensional Array

import java.util.Arrays;
public class Array
{
public static void main(String[] args)
{
int[][] array = {{10, 12}, {13, 14}, {15, 16, 17}};

System.out.println(Arrays.deepToString(array));
}
}

Output:
[[10, 12], [13, 14], [15, 16, 17]]

46. Concatenate Two Arrays

import java.util.Arrays;
public class Concat
{
public static void main(String[] args)
{
int[] array1 = {10, 11, 12};
int[] array2 = {14,15, 16};

int len1 = array1.length;


int len2 = array2.length;
int[] result = new int[len1 + len2];

System.arraycopy(array1, 0, result, 0, len1);


System.arraycopy(array2, 0, result, len1, len2);

System.out.println(Arrays.toString(result));
}
}

Output:
[10, 11, 12, 14, 15, 16]

47. Print an Array using standard library

import java.util.Arrays;
public class Array
{
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6};
System.out.println(Arrays.toString(array));
}
}
Output:
[1, 2, 3, 4, 5, 6]

48. Convert String to Date

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TimeString


{
public static void main(String[] args) {
// Format y-M-d or yyyy-MM-d
String string = "2023-03-25";
LocalDate date = LocalDate.parse(string,
DateTimeFormatter.ISO_DATE);

System.out.println(date);
}
}

Output:
2023-03-25

49. Round a Number to n Decimal Places

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Program


{
public static void main(String[] args)
{
double num = 1.45283;
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(num));
}
}

Output:
1.4529

50. Program to Compare Strings Using “==”

public class Program


{
public static void main(String[] args)
{
String style = "Bold";
String style2 = "Bold";

if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

51. Program to Compare Strings Using equals()

public class Programs


{
public static void main(String[] args)
{
String style = new String("Bold");
String style2 = new String("Bold");

if(style.equals(style2))
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

52. Check if a string is numeric.

public class Program


{
public static void main(String[] args)
{
String string = "125.15";
boolean numeric = true;
try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}

53. Convert char to int using parseInt()

class Program
{
public static void main(String[] args)
{
// create char variables
char a = '1';
char b = '8';
// convert char variables to int
// Use parseInt()
int num1 = Integer.parseInt(String.valueOf(a));
int num2 = Integer.parseInt(String.valueOf(b));
// print numeric value
System.out.println(num1); // 1
System.out.println(num2); //8
}
}
54. Simple Calculator Program

import java.util.Scanner;

class Program
{
public static void main(String[] args)
{
char operator;
Double number1, number2, result;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
System.out.println("Enter first number");
number1 = input.nextDouble();

System.out.println("Enter second number");


number2 = input.nextDouble();

switch (operator) {
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}

Output:
Choose an operator: +, -, *, or /
Enter first number
1200
Enter second number
400
1200.0 - 400.0 = 800.0

55. Calculate Average Program

public class Average


{
public static void main(String[] args)
{
double[] numArray = { 47.3, 67.5, -45.6, 28.34, 35.0};
double sum = 0.0;
for (double num: numArray) {
sum += num;
}
double average = sum / numArray.length;
System.out.format("The average is: %.2f", average);
}
}
Output:
The average is: 26.51
56. Find Frequency of Character

public class Frequency


{
public static void main(String[] args)
{
String str = "Follow coding.aryan";
char ch = 'o';
int frequency = 0;

for(int i = 0; i < str.length(); i++) {


if(ch == str.charAt(i)) {
++frequency;
}
}
System.out.println("Frequency of " + ch
+ " = " + frequency);
}
}
Output:
Frequency of o = 3

57. Print a 2 D Array or Matrix

import java.io.*;
import java.util.*;
class Matrix {
public static void printMatrix(int mat[][])
{
// Loop through all rows
for (int[] row : mat)
// converting each row as string
// and then printing in a separate line
System.out.println(Arrays.toString(row));
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
print2D(mat);
}
}

58. Ternary operator Example

public class Program


{
public static void main(String[] args)
{
int value1 = 100;
int value2 = value1 == 100 ? 50 : 10;
System.out.println("Value2: " + value2);

System.out.println("value3: ");
String value3 = value1 >= value2 ? "greater" : "lesser";
System.out.print(value3);
}
}

Output:
Value2: 50
value3: greater

59. Java Substring Example

public class Program


{
public static void main(String[] args)
{
String value = "Plz Follow coding.aryan";

String follow = value.substring(3, 10);


System.out.print(follow + ": ");

String aryan = value.substring(11,23);


System.out.println(aryan);
}
}

Output:
Follow: coding.aryan
60. Find Square root Program

public class Program


{
public static void main(String[] args)
{
// ... Test the sqrt method.
double value = java.lang.Math.sqrt(16);
double value2 = java.lang.Math.sqrt(49);

System.out.println(value);
System.out.println(value2);
}
}

Ouput:
4.0
7.0

61. Find Max and Min Example

public class Program


{
public static void main(String[] args)
{
int result = Math.min(100,200);
System.out.println("Min of two number is: " + result);

result = Math.max(100,200);
System.out.println("Max of two number is: " + result);
}
}

Output:
Min of two number is: 100
Max of two number is: 200

62. Random lowercase letters

import java.util.Random;
public class Program
{
public static void main(String[] args)
{
Random random = new Random();
// Generate 10 random lowercase letters.
for (int i = 0; i < 10; i++)
{
int n = random.nextInt(26);
char value = (char) (n + 97);
// Display our results.
System.out.println(value + "..." +
Integer.toString(n));
}
}
}

OutPut:
q...16
w...22
f...5
w...22
j...9
l...11
j...9
c...2
u...20
f...5

63. Integer.bitCount() Example

public class Program


{
public static void main(String[] args)
{
// Call bitCount on 0, 1 and MAX_VALUE.
int bits0 = Integer.bitCount(0);
int bits1 = Integer.bitCount(1);
int bitsAll = Integer.bitCount(Integer.MAX_VALUE);

System.out.println(bits0);
System.out.println(bits1);
System.out.println(bitsAll);
}
}

Output:
0
1
31

64. Java charAt() Example

import java.util.Random;
public class Program
{
public static void main(String[] args)
{
String value = "aryan";
// Loop through all characters in the string.
// ... Use charAt to get the values.
for (int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
System.out.println(c);
}
}
}

Output:
a
r
y
a
n
65. Java String.join() Method

public class Program


{
public static void main(String[] args)
{
// Create a String array of three elements.
String[] values = { "Follow" , "Coding", "Aryan" };

// Join the elements together.


String result = String.join("...", values);
System.out.println(result);
}
}

Output:
Follow...Coding...Aryan
66. Reverse a Sentence Using Recursion

public class Reverse {

public static void main(String[] args)


{
String sentence = "Coding Aryan";
String reversed = reverse(sentence);
System.out.println("The reversed sentence: " + reversed);
}

public static String reverse(String sentence) {


if (sentence.isEmpty())
return sentence;

return reverse(sentence.substring(1)) + sentence.charAt(0);


}
}

Output:
The reversed sentence: nayrA gnidoC

67. Convert long type into int

class Main
{
public static void main(String[] args)
{
// create an object of Long class
Long obj = 45462329L;

// convert object of Long into int


// using intValue()
int a = obj.intValue();

System.out.println(a);
}
}

Output:
45462329

68. convert int type to long

class Main {
public static void main(String[] args)
{
// create int variables
int a = 500;

// convert to an object of Long


// using valueOf()
Long obj = Long.valueOf(a);
System.out.println(obj); // 500
}
}

Output:
500

69. Remove All Whitespaces from a String

import java.util.Scanner;

class Main
{
public static void main(String[] args)
{
// create an object of Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Enter any string");

// take the input


String input = sc.nextLine();
System.out.println("Original Str: " + input);

// remove white spaces


input = input.replaceAll("\\s", "");
System.out.println("Final Str: " + input);
sc.close();
}
}

Output:
Enter any string
Coding. Aryan
Original Str: Coding. Aryan
Final Str: Coding.Aryan
70. Convert Octal to Decimal

import java.util.Scanner;
class Octal_Decimal
{
Scanner scan;
int num;
void getVal()
{
System.out.println("Octal to Decimal");
scan = new Scanner(System.in);
System.out.println("\nEnter the number :");
num = Integer.parseInt(scan.nextLine(), 8);
}
void convert()
{
String decimal = Integer.toString(num);
System.out.println("Decimal Value is : " + decimal);
}
}

class MainClass
{
public static void main(String args[])
{
Octal_Decimal obj = new Octal_Decimal();
obj.getVal();
obj.convert();
}
}

Output:
Octal to Decimal
Enter the number :
10
Decimal Value is : 8

71. Add Two Binary Strings

public class Program {

static String add_Binary(String x, String y)


{
int num1 = Integer.parseInt(x, 2);
int num2 = Integer.parseInt(y, 2);
int sum = num1 + num2;
String result = Integer.toBinaryString(sum);
return result;
}
// Main driver method
public static void main(String args[])
{
String x = "011011", y = "1010111";

System.out.print(add_Binary(x, y));
}
}
Output:
1110010

72. Remove Leading Zeros

import java.util.Arrays;
import java.util.List;

class Program {

public static String removeZero(String str)


{
int i = 0;
while (i < str.length() && str.charAt(i) == '0')
i++;
StringBuffer sb = new StringBuffer(str);
sb.replace(0, i, "");
return sb.toString();
}
public static void main(String[] args)
{
String str = "000001238439";
str = removeZero(str);
System.out.println(str);
}
}

Output:
1238439
73. print Even length words

class Program {
public static void printWords(String s)
{

for (String word : s.split(" "))


if (word.length() % 2 == 0)
System.out.println(word);
}

public static void main(String[] args)


{
String s = "Java Programs Simplified";
printWords(s);
}
}

Output:
JavaPrograms
Simplified
74. Find a Sublist in a List

import java.util.*;

public class Program {

public static void main(String[] argv) throws Exception


{
ArrayList<Integer>
arrlist = new ArrayList<Integer>();
arrlist.add(1);
arrlist.add(4);
arrlist.add(9);
arrlist.add(25);
arrlist.add(36);
System.out.println("Initial arrlist: "
+ arrlist);
List<Integer> arrlist2 = arrlist.subList(1, 4);
System.out.println("Sublist of arrlist: "
+ arrlist2);
}
}

Output:
Initial arrlist: [1, 4, 9, 25, 36]
Sublist of arrlist: [4, 9, 25]

75. Split a List into Two Halves

import java.util.ArrayList;
import java.util.List;

public class Program{

public static List[] split(List<String> list)


{
List<String> first = new ArrayList<String>();
List<String> second = new ArrayList<String>();
int size = list.size();
for (int i = 0; i < size / 2; i++)
first.add(list.get(i));
for (int i = size / 2; i < size; i++)
second.add(list.get(i));

return new List[] { first, second };


}

// Method 2
// Main driver method
public static void main(String[] args)
{

// Creating an ArrayList of string type


List<String> list = new ArrayList<String>();

// Adding elements to list object


// using add() method
list.add("Coding");
list.add("Is");
list.add("Fun");
list.add("For");
list.add("Me");

// Calling split method which return List of array


List[] lists = split(list);

// Printing specific elements of list by


// passing arguments with in
System.out.println(lists[0]);
System.out.println(lists[1]);
}
}

Output:
[Coding, Is]
[Fun, For, Me]

76. Remove a SubList from a List

import java.util.*;

public class Program


{
public static void main(String args[])
{
AbstractList<String>
list = new LinkedList<String>();
list.add("Coding");
list.add("Aryan");
list.add("Create");
list.add("Useful");
list.add("Content");
System.out.println("Original List: "
+ list);
list.subList(1, 4).clear();
System.out.println("Final List: "
+ list);
}
}

Output:
Original List: [Coding, Aryan, Create, Useful, Content]
Final List: [Coding, Content]

77. Find Min and Max in a List

import java.util.Collections;
import java.util.List;

public class Program


{
public static Integer findMin(List<Integer> list)
{
if (list == null || list.size() == 0) {
return Integer.MAX_VALUE;
}
return Collections.min(list);
}
public static Integer findMax(List<Integer> list)
{
if (list == null || list.size() == 0) {
return Integer.MIN_VALUE;
}
return Collections.max(list);
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
list.add(55);
list.add(23);
list.add(67);
list.add(99);
System.out.println("Min: " + findMin(list));
System.out.println("Max: " + findMax(list));
}
}
Output:
Min: 23
Max: 99
78. Traverse in a Directory.

import java.io.*;
import java.nio.file.*;
import java.util.stream.Stream;

class Program {
public static void main(String[] args)
throws IOException
{
try (Stream<Path> filepath
= Files.walk(Paths.get("c:\\Demo")))
{
filepath.forEach(System.out::println);
}
catch (IOException e) {
throw new IOException("Directory Not Found!");
}
}
}

Output:
c:\Demo
c:\Demo\article.docx
c:\Demo\test.txt
79. Search for a File in a Directory

// Java Program to Search for a File in a Directory


import java.io.*;
class MyFile implements FilenameFilter
{
String initials;
public MyFilenameFilter(String initials)
{
this.initials = initials;
}
public boolean accept(File dir, String name)

return name.startsWith(initials);
}
}

public class Main {

public static void main(String[] args)


{
File directory = new File("/home/user/");
MyFile filter = new MyFile("file.cpp");
String[] flist = directory.list(filter);
if (flist == null) {
System.out.println(
"Directory does not exists.");
}
else {
for (int i = 0; i < flist.length; i++) {
System.out.println(flist[i]+" found");
}
}
}
}

Output:
file.cpp found

80. Find Current Working Directory

import java.io.*;

public class Program {

public static void main(String[] args)


{
// Getting the path of system property
String path = System.getProperty("user.dir");

// Printing the path of the working Directory


System.out.println("Working Directory = " + path);
}
}

81. Delete a directory

import java.io.File;
class Program {
public static void main(String[] args)
{
File directory = new File("/home/Test");

if (directory.isDirectory()) {
String arr[] = directory.list();
if (arr.length > 0) {
System.out.println("The directory "
+ directory.getPath()
+ " is not Empty!");
}
else {
System.out.println("The directory "
+ directory.getPath()
+ " is Empty!");
}
}
}
}

82. Check if a Directory is Empty or Not

import java.io.File;
class Program {
public static void main(String[] args)
{
File directory = new File("/home/Demo");
if (directory.isDirectory()) {
String arr[] = directory.list();

if (arr.length > 0) {
System.out.println("The directory "
+ directory.getPath()
+ " is not Empty!");
}
else {
System.out.println("The directory "
+ directory.getPath()
+ " is Empty!");
}}}}
83. Find common elements in two ArrayLists

public static void main(String[] args)


{
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("Hello");
list1.add("Coding");
list1.add("Programming");
list1.add("Developers");
System.out.println("List1: "
+ list1);
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("Hello");
list2.add("Programming");
list2.add("Aryan");
System.out.println("List2: "
+ list2);
list1.retainAll(list2);
System.out.println("Common elements: "
+ list1);
}
}

Output:
List1: [Hello, Coding, Programming, Developers]
List2: [Hello, Programming, Aryan]
Common elements: [Hello, Programming]

84. Add Element at First and Last Position

import java.util.*;

public class Program{

public static void main(String args[])


{
LinkedList<String> linkedList
= new LinkedList<String>();
linkedList.add("I");
linkedList.add("R");
linkedList.add("S");
System.out.println("Linked list: " + linkedList);
linkedList.addFirst("F");
linkedList.addLast("T");
System.out.println("Updated Linked list: "
+ linkedList);
}
}

Output:
Linked list: [I,R,S]
Updated Linked list: [F,I,R,S,T]
85. Array Copy in Java

public class Test {


public static void main(String[] args)
{
int a[] = { 1, 8, 3 };
int b[] = new int[a.length];
b = a;
b[0]++;
System.out.println("Contents of a[] ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");

System.out.println("\n\nContents of b[] ");


for (int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
}
}

Output:
Contents of a[] 2 8 3
Contents of b[] 2 8 3

86. Swapping Pairs of Characters

class Program {

public static String swapPair(String str)


{
if (str == null || str.isEmpty())
return str;
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length - 1; i += 2) {
char temp = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = temp;
}
return new String(ch);
}
public static void main(String args[])
{
String str = "Coding.Aryan";
System.out.println(swapPair(str));
}
}

Output:
oCidgnA.yrna

87. Make a File Read-Only

import java.io.File;
public class ChangetoReadOnly {

public static void main(String[] args)


{
try {
File file = new File(
"C://Users//Desktop//test.txt");
file.setWritable(false);
if (!file.canWrite()) {
System.out.println(
"This File is read only.");
}
else {
System.out.println(
"This File is writable.");
}
}
catch (Exception e) {
System.out.println(
"unable to change to readonly mode.");
}
}
}

88. Right Triangle Star Pattern

public class RightTrianglePattern


{

public static void main(String args[])


{
int i, j, row=7;
for(i=0; i<row; i++)
{
//inner loop for columns
for(j=0; j<=i; j++)
{
//prints stars
System.out.print("* ");
}
//throws the cursor in a new line.
System.out.println();
}
}
}

89. Right Triangle Star Pattern.

public class Program


{
public static void main(String[] args)
{
int rows = 5; // Number of rows in the pattern
for (int i = 1; i <= rows; i++) {
// Iterate over each row
for (int j = 1; j <= rows - i; j++) {
// Print spaces before the stars
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
// Print stars for each column in the row
System.out.print("*");
}
System.out.println();
// Move to the next line
}
}
}
90. Left Down Triangle Star Pattern

public class LeftDownTriangleStarPattern


{
public static void main(String[] args)
{
int rows = 5;
// Number of rows in the pattern

for (int i = rows; i >= 1; i--) {


// Iterate over each row in reverse order
for (int j = 1; j <= i; j++) {
// Print stars for each column in the row
System.out.print("* ");
}
System.out.println();
// Move to the next line
}
}
}

91. Right Down Triangle Star Pattern

public class Program


{
public static void main(String[] args)
{
int rows = 5;
// Number of rows in the pattern

for (int i = rows; i >= 1; i--) {


// Iterate over each row in reverse order
for (int j = 1; j <= i; j++) {
// Print stars for each column in the row
System.out.print("* ");
}
System.out.println();
// Move to the next line
}
}
}

92. Square Hollow Pattern

import java.util.*;

public class Program


{
public static void printPattern(int n)
{
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1
|| j == n - 1) {
System.out.print("*");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}

93. Rhombus Pattern

import java.util.*;

public class Program {

public static void printPattern(int n)


{
int i, j;
int num = 1;
// outer loop to handle number of rows
for (i = 1; i <= n; i++) {
// inner loop to print spaces
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// inner loop to print stars
for (j = 1; j <= n; j++) {
System.out.print("*");
}
// printing new line for each row
System.out.println();
}
}

// Driver Function
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}

94. Diamond Star Pattern

import java.util.*;

public class Program {

// Function to demonstrate pattern


public static void printPattern(int n)
{
int i, j;
int num = 1;
// outer loop to handle upper part
for (i = 1; i <= n; i++) {
// inner loop to print spaces
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// inner loop to print stars
for (j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}

// outer loop to handle lower part


for (i = n-1; i >= 1; i--) {
// inner loop to print spaces
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// inner loop to print stars
for (j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}
95. Triangle Star Pattern

import java.util.*;

public class Program {

public static void printPattern(int n)


{
int i, j;
// outer loop to handle rows
for (i = 0; i < n; i++) {
// inner loop to print spaces.
for (j = n - i; j > 1; j--) {
System.out.print(" ");
}
// inner loop to print stars.
for (j = 0; j <= i; j++) {
System.out.print("* ");
}
// printing new line for each row
System.out.println();
}
}

public static void main(String args[])


{
int n = 6;
printPattern(n);
}
}
96. Reverse Triangle Pattern

import java.util.*;

public class Programs {

public static void main(String args[])


{
int n = 6;
int i, j;
// outer loop to handle rows
for (i = 1; i <= n; i++) {
// inner loop to print spaces.
for (j = 1; j < i; j++) {
System.out.print(" ");
}
// inner loop to print value of j.
for (j = i; j <= n; j++) {
System.out.print(j + " ");
}
// printing new line for each row
System.out.println();
}
}
}
97. Mirror Image Triangle Pattern

import java.util.*;

public class Programs {

public static void main(String args[])


{
int n = 6;
int i, j;
// Printing the upper part
for (i = 1; i <= n; i++) {
// inner loop to print spaces.
for (j = 1; j < i; j++) {
System.out.print(" ");
}
// inner loop to print value of j.
for (j = i; j <= n; j++) {
System.out.print(j + " ");
}
// printing new line for each row
System.out.println();
}

// Printing the lower part


for (i = n - 1; i >= 1; i--) {
// inner loop to print spaces.
for (j = 1; j < i; j++) {
System.out.print(" ");
}
// inner loop to print value of j.
for (j = i; j <= n; j++) {
System.out.print(j + " ");
}
// printing new line for each row
System.out.println();
}
}
}

98. Right Pascal’s Triangle

import java.util.*;

public class Program {

public static void main(String args[])


{
int n = 4;
int i, j;
int num = 1;
// outer loop to handle upper part
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// outer loop to handle lower part
for (i = n-1; i >= 1; i--) {
for (j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
99. Zero-One Triangle Pattern

import java.util.*;
public class Program
{
public static void main(String args[])
{
int i, j;
int n = 6;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++) {
// if the sum of (i+j) is even then print 1
if ((i + j) % 2 == 0) {
System.out.print(1 + " ");
}
// otherwise print 0
else {
System.out.print(0 + " ");
}
}
System.out.println();
}
}
}
100. Butterfly Star Pattern

import java.util.*;

public class Program


{
public static void main(String args[])
{
int n = 6;
int i, j;
int num = 1;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
int spaces = 2 * (n - i);
for (j = 1; j <= spaces; j++) {
System.out.print(" ");
}
for (j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
// outer loop to handle lower part
for (i = n; i >= 1; i--) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
int spaces = 2 * (n - i);
for (j = 1; j <= spaces; j++) {
System.out.print(" ");
}
for (j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

You might also like