You are on page 1of 422

CONTENTS

1. Java Program to Print an Integer (Entered by the User)


2. Java Program to Add Two Integers
3. Java Program to Multiply two Floating Point Numbers
4. Java Program to Find ASCII Value of a character
5. Java Program to Compute Quotient and Remainder
6. Java Program to Swap Two Numbers
7. Java Program to Check Whether a Number is Even or Odd
8. Java Program to Check Whether an Alphabet is Vowel or Consonant
9. Java Program to Find the Largest Among Three Numbers
10. Java Program to Find all Roots of a Quadratic Equation
11. Java Program to Check Leap Year
12. Java Program to Check Whether a Character is Alphabet or Not
13. Java Program to Calculate the Sum of Natural Numbers
14. Java Program to Find Factorial of a Number
15. Java Program to Generate Multiplication Table
16. Java Program to Display Fibonacci Series
17. Java Program to Find GCD of two Numbers
18. Java Program to Find LCM of two Numbers
19. Java Program to Display Characters from A to Z using loop
20. Java Program to Count Number of Digits in an Integer
21. Java Program to Reverse a Number
22. Java Program to Calculate the Power of a Number
23. Java Program to Check Whether a Number is Palindrome or Not
24. Java Program to Check Whether a Number is Prime or Not
25. Java Program to Display Prime Numbers Between Two Intervals
26. Java Program to Check Armstrong Number
27. Java Program to Display Armstrong Number Between Two Intervals
28. Java Program to Display Prime Numbers Between Intervals Using Function
29. Java Program to Display Armstrong Numbers Between Intervals Using Function
30. Java Program to Check Whether a Number can be Expressed as Sum of Two
Prime Numbers
31. Java Program to Find the Sum of Natural Numbers using Recursion
32. Java Program to Find Factorial of a Number Using Recursion
33. Java Program to Find G.C.D Using Recursion
34. Java Program to Convert Binary Number to Decimal and vice-versa
35. Java Program to Convert Octal Number to Decimal and vice-versa
36. Java Program to Convert Binary Number to Octal and vice-versa
37. Java Program to Reverse a Sentence Using Recursion
38. Java Program to calculate the power using recursion
39. Java Program to Calculate Average Using Arrays
40. Java Program to Find Largest Element of an Array
41. Java Program to Calculate Standard Deviation
42. Java Program to Add Two Matrix Using Multi-dimensional Arrays
43. Java Program to Multiply to Matrix Using Multi-dimensional Arrays
44. Java Program to Multiply two Matrices by Passing Matrix to a Function
45. Java Program to Find Transpose of a Matrix
46. Java Program to Print an Array
47. Java Program to Concatenate Two Arrays
48. Java Program to Check if An Array Contains a Given Value
49. Java Program to Find the Frequency of Character in a String
50. Java Program to Count the Number of Vowels and Consonants in a Sentence
51. Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
52. Java Program to Add Two Complex Numbers by Passing Class to a Function
53. Java Program to Calculate Difference Between Two Time Periods
54. Java Program to Remove All Whitespaces from a String
55. Java Program to Determine the class of an object
56. Java Program to Create an enum class
57. Java Program to Print object of a class
58. Java Program to Create custom exception
59. Java Program to Create a immutable class
60. Java Program to Convert String to Date
61. Java Program to Convert a Stack Trace to a String
62. Java Program to Compare Strings
63. Java Program to Check if a String is Numeric
64. Java Program to Check if two strings are anagram
65. Java Program to Compute all the permutations of the string
66. Java Program to Create random strings
67. Java Program to Clear the StringBuffer
68. Java Program to Capitalize the first character of each word in a String
69. Java Program to Iterate through each characters of the string.
70. Java Program to Display Factors of a Number
71. Java Program to Make a Simple Calculator Using switch...case
72. Java Code To Create Pyramid and Pattern
73. Java Program to Round a Number to n Decimal Places
74. Java Program to Convert Character to String and Vice-Versa
75. Java Program to Check if a String is Empty or Null
76. Java Program to Get Current Date/TIme
77. Java Program to Convert Milliseconds to Minutes and Seconds
78. Java Program to Add Two Dates
79. Java Program to Join Two Lists
80. Java Program to Convert the ArrayList to an array and vice versa
81. Java Program to Get Current Working Directory
82. Java Program to Convert Map (HashMap) to List
83. Java Program to Convert Array to Set (HashSet) and Vice-Versa
84. Java Program to Convert Byte Array to Hexadecimal
85. Java Program to Create String from Contents of a File
86. Java Program to Append Text to an Existing File
87. Java Program to Convert File to byte array and Vice-Versa
88. Java Program to Convert InputStream to String
89. Java Program to Convert OutputStream to String
90. Java Program to Lookup enum by String value
91. Java Program to Sort a Map By Values
92. Java Program to Sort ArrayList of Custom Objects By Property
93. Java Program to Create Directories
94. Java Program to Rename File
95. Java Program to Get all Files Present in a Directory
96. Java Program to Copy File
97. Java Program to convert char type variables to int
98. Java Program to convert int type variables to char
99. Java Program to convert long type variables into int
100. Java Program to convert int type variables to long
101. Java Program to convert boolean variables into string
102. Java Program to convert string type variables into boolean
103. Java Program to convert string type variables into int
104. Java Program to convert int type variables to String
105. Java Program to convert int type variables to double
106. Java Program to convert double type variables to int
107. Java Program to convert string variables to double
108. Java Program to convert double type variables to string
109. Java Program to convert primitive types to objects and vice versa
110. Java Program to Implement Bubble Sort algorithm
111. Java Program to Implement Quick Sort Algorithm
112. Java Program to Implement Merge Sort Algorithm
113. Java Program to Implement Binary Search Algorithm
114. Java Program to Call One Constructor from another
115. Java Program to implement private constructors
116. Java Program to pass lambda expression as a method argument
117. Java Program to pass methods as arguments to other methods
118. Java Program to Calculate the Execution Time of Methods
119. Java Program to Convert a String into the InputStream
120. Java Program to Convert the InputStream into Byte Array
121. Java Program to Load File as InputStream
122. Java Program to Create File and Write to the File
123. Java Program to Read the Content of a File Line by Line
124. Java Program to Delete File in Java
125. Java Program to Delete Empty and Non-empty Directory
126. Java Program to Get the File Extension
127. Java Program to Get the name of the file from the absolute path
128. Java Program to Get the relative path from two absolute paths
129. Java Program to Count number of lines present in the file
130. Java Program to Check if a string is a valid shuffle of two strings
131. Java Program to Implement the graph data structure
132. Java Program to Check Whether a Number is Positive or Negative
133. Java Program to Differentiate String == operator and equals() method
134. Java Program to Implement switch statement on strings
135. Java Program to Calculate simple interest and compound interest
136. Java Program to Implement multiple inheritance
137. Java Program to Determine the name and version of the operating system
138. Java Program to Check if two of three boolean variables are true
139. Java Program to Iterate over enum
140. Java Program to Check the birthday and print Happy Birthday message
141. Java Program to Implement LinkedList
142. Java Program to Implement stack data structure
143. Java Program to Implement the queue data structure
144. Java Program to Get the middle element of LinkedList in a single iteration
145. Java Program to Convert the LinkedList into an Array and vice versa
146. Java Program to Convert the ArrayList into a string and vice versa
147. Java Program to Iterate over an ArrayList
148. Java Program to Iterate over a HashMap
149. Java Program to Iterate over a Set
150. Java Program to Merge two lists
151. Java Program to Update value of HashMap using key
152. Java Program to Remove duplicate elements from ArrayList
153. Java Program to Get key from HashMap using the value
154. Java Program to Detect loop in a LinkedList
155. Java Program to Calculate union of two sets
156. Java Program to Calculate the intersection of two sets
157. Java Program to Calculate the difference between two sets
158. Java Program to Check if a set is the subset of another set
159. Java Program to Sort map by keys
160. Java Program to Pass ArrayList as the function argument
161. Java Program to Iterate over ArrayList using Lambda Expression
162. Java Program to Implement Binary Tree Data Structure
163. Java Program to Perform the preorder tree traversal
164. Java Program to Perform the postorder tree traversal
165. Java Program to Perform the inorder tree traversal
166. Java Program to Count number of leaf nodes in a tree
167. Java Program to Check if a string contains a substring
168. Java Program to Access private members of a class
1. Java Program to Print an Integer (Entered by the User)
In this program, you'll learn to print a number entered by the user in Java. The integer is stored in a variable
using System.in, and is displayed on the screen using System.out.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Hello World Program

Java Basic Input and Output

Example: How to Print an Integer entered by an user

import java.util.Scanner;

public class HelloWorld {

public static void main(String[] args) {

// Creates a reader instance which takes

// input from standard input - keyboard

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

// nextInt() reads the next integer from the keyboard

int number = reader.nextInt();

// println() prints the following line to the output screen

System.out.println("You entered: " + number);

Output

Enter a number: 10

You entered: 10

In this program, an object of Scanner class, reader is created to take inputs from standard input, which is
keyboard.
Then, Enter a number prompt is printed to give the user a visual cue as to what they should do next.

reader.nextInt()then reads all entered integers from the keyboard unless it encounters a new line character \n
(Enter). The entered integers are then saved to the integer variable number.

If you enter any character which is not an integer, the compiler will throw an InputMismatchException.

Finally, number is printed onto the standard output (System.out) - computer screen using the function println().

2. Java Program to Add Two Integers


In this program, you'll learn to store and add two integer numbers in Java. After addition, the final sum is
displayed on the screen.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Operators

Java Basic Input and Output

Example: Program to Add Two Integers

public class AddTwoIntegers {

public static void main(String[] args) {

int first = 10;

int second = 20;

System.out.println("Enter two numbers: " + first + " " + second);

int sum = first + second;

System.out.println("The sum is: " + sum);

}
}

Output:

Enter two numbers: 10 20

The sum is: 30

In this program, two integers 10 and 20 are stored in integer variables first and second respectively.

Then, first and second are added using the + operator, and its result is stored in another variable sum.

Finally, sum is printed on the screen using println() function.

3. Java Program to Multiply two Floating Point Numbers


In this program, you'll learn to multiply two floating point numbers in Java, store the result and display it on the
screen.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Hello World Program

Example: Multiply Two Floating-Point Numbers

public class MultiplyTwoNumbers {

public static void main(String[] args) {

float first = 1.5f;

float second = 2.0f;

float product = first * second;

System.out.println("The product is: " + product);


}

Output

The product is: 3.0

In the above program, we have two floating-point numbers 1.5f and 2.0f stored in variables first and second
respectively.

Notice, we have used f after the numbers. This ensures the numbers are float, otherwise they will be assigned -
type double.

first and second are then multiplied using the * operator and the result is stored in a new float variable product.

Finally, the result product is printed on the screen using println() function.

4. Java Program to Find ASCII Value of a character


In this program, you'll learn to find and display the ASCII value of a character in Java. This is done using type-
casting and normal variable assignment operations.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Hello World Program

Example: Find ASCII value of a character

public class AsciiValue {

public static void main(String[] args) {

char ch = 'a';

int ascii = ch;

// You can also cast char to int


int castAscii = (int) ch;

System.out.println("The ASCII value of " + ch + " is: " + ascii);

System.out.println("The ASCII value of " + ch + " is: " + castAscii);

Output

The ASCII value of a is: 97

The ASCII value of a is: 97

In the above program, character a is stored in a char variable, ch. Like, double quotes (" ") are used to declare
strings, we use single quotes (' ') to declare characters.

Now, to find the ASCII value of ch, we just assign ch to an int variable ascii. Internally, Java converts the
character value to an ASCII value.

We can also cast the character ch to an integer using (int). In simple terms, casting is converting variable from
one type to another, here char variable ch is converted to an int variable castAscii.

Finally, we print the ascii value using the println() function.

5. Java Program to Compute Quotient and Remainder


In this program, you'll learn to compute quotient and remainder from the given dividend and divisor in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Hello World Program

Java Operators

Example: Compute Quotient and Remainder

public class QuotientRemainder {


public static void main(String[] args) {

int dividend = 25, divisor = 4;

int quotient = dividend / divisor;

int remainder = dividend % divisor;

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

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

Output:

Quotient = 6

Remainder = 1

In the above program, two numbers 25 (dividend) and 4 (divisor) are stored in two variables dividend and divisor
respectively.

Now, to find the quotient we divide dividend by divisor using / operator. Since, both dividend and divisor are
integers, the result will also be computed as an integer.

So, mathematically 25/4 results 6.25, but since both operands are int, quotient variable only stores 6 (integer
part).

Likewise, to find the remainder we use the % operator. So, the remainder of 25/4, i.e. 1 is stored in an integer
variable remainder.

Finally, quotient and remainder are printed on the screen using println() function.

6. Java Program to Swap Two Numbers


In this program, you'll learn two techniques to swap two numbers in Java. The first one uses a temporary
variable for swapping, while the second one doesn't use any temporary variables.
To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Operators

Example 1: Swap two numbers using temporary variable

public class SwapNumbers {

public static void main(String[] args) {

float first = 1.20f, second = 2.45f;

System.out.println("--Before swap--");

System.out.println("First number = " + first);

System.out.println("Second number = " + second);

// Value of first is assigned to temporary

float temporary = first;

// Value of second is assigned to first

first = second;

// Value of temporary (which contains the initial value of first) is assigned to second

second = temporary;

System.out.println("--After swap--");

System.out.println("First number = " + first);

System.out.println("Second number = " + second);

}
Output:

--Before swap--

First number = 1.2

Second number = 2.45

--After swap--

First number = 2.45

Second number = 1.2

In the above program, two numbers 1.20f and 2.45f which are to be swapped are stored in variables: first and
second respectively.

The variables are printed before swapping using println() to see the results clearly after swapping is done.

First, the value of first is stored in variable temporary (temporary = 1.20f).

Then, value of second is stored in first (first = 2.45f).

And, finally value of temporary is stored in second (second = 1.20f).

This completes the swapping process and the variables are printed on the screen.

Remember, the only use of temporary is to hold the value of first before swapping. You can also swap the
numbers without using temporary.

Example 2: Swap two numbers without using temporary variable

public class SwapNumbers {

public static void main(String[] args) {

float first = 12.0f, second = 24.5f;

System.out.println("--Before swap--");

System.out.println("First number = " + first);


System.out.println("Second number = " + second);

first = first - second;

second = first + second;

first = second - first;

System.out.println("--After swap--");

System.out.println("First number = " + first);

System.out.println("Second number = " + second);

Output:

--Before swap--

First number = 12.0

Second number = 24.5

--After swap--

First number = 24.5

Second number = 12.0

In the above program, instead of using temporary variable, we use simple mathematics to swap the numbers.

For the operation, storing (first - second) is important. This is stored in variable first.

first = first - second;

first = 12.0f - 24.5f

Then, we just add second (24.5f) to this number - calculated first (12.0f - 24.5f) to swap the number.

second = first + second;

second = (12.0f - 24.5f) + 24.5f = 12.0f

Now, second holds 12.0f (which was initially value of first). So, we subtract calculated first (12.0f - 24.5f) from
swapped second (12.0f) to get the other swapped number.
first = second - first;

first = 12.0f - (12.0f - 24.5f) = 24.5f

The swapped numbers are printed on the screen using println().

7. Java Program to Check Whether a Number is Even or Odd


In this program, you'll learn to check if a number entered by an user is even or odd. This will be done using
if...else statement and ternary operator in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Scanner Class

Example 1: Check whether a number is even or odd using if...else statement

import java.util.Scanner;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = reader.nextInt();

if(num % 2 == 0)

System.out.println(num + " is even");

else

System.out.println(num + " is odd");

}
}

Output

Enter a number: 12

12 is even

In the above program, a Scanner object, reader is created to read a number from the user's keyboard. The
entered number is then stored in a variable num.

Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is
divisible by 2 or not.

For this, we use if...else statement in Java. If num is divisible by 2, we print num is even. Else, we print num is
odd.

We can also check if num is even or odd by using ternary operator in Java.

Example 2: Check whether a number is even or odd using ternary operator

import java.util.Scanner;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = reader.nextInt();

String evenOdd = (num % 2 == 0) ? "even" : "odd";


System.out.println(num + " is " + evenOdd);

Output

Enter a number: 13

13 is odd

In the above program, we've replaced if...else statement with ternary operator (? :).

Here, if num is divisible by 2,"even" is returned. Else, "odd" is returned. The returned value is saved in a string
variable evenOdd.

Then, the result is printed on the screen using string concatenation.

8. Java Program to Check Whether an Alphabet is Vowel or Consonant


In this program, you'll learn to check whether an alphabet is a vowel or a consotant using if..else and switch
statement in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java switch Statement

Example 1: Check whether an alphabet is vowel or consonant using if..else statement

public class VowelConsonant {

public static void main(String[] args) {

char ch = 'i';

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )


System.out.println(ch + " is vowel");

else

System.out.println(ch + " is consonant");

Output

i is vowel

In the above program, 'i' is stored in a char variable ch. In Java, you use double quotes (" ") for strings and single
quotes (' ') for characters.

Now, to check whether ch is vowel or not, we check if ch is any of: ('a', 'e', 'i', 'o', 'u'). This is done using a simple
if..else statement.

We can also check for vowel or consonant using a switch statement in Java.

Example 2: Check whether an alphabet is vowel or consonant using switch statement

public class VowelConsonant {

public static void main(String[] args) {

char ch = 'z';

switch (ch) {

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':
System.out.println(ch + " is vowel");

break;

default:

System.out.println(ch + " is consonant");

Output

z is consonant

In the above program, instead of using a long if condition, we replace it with a switch case statement.

If ch is either of cases: ('a', 'e', 'i', 'o', 'u'), vowel is printed. Else, default case is executed and consonant is printed
on the screen.

9. Java Program to Find the Largest Among Three Numbers


In this program, you'll learn to find the largest among three numbers using if else and nested if..else statement
in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Operators

Java if, if...else Statement

Example 1: Find Largest Among three numbers using if..else statement

public class Largest {

public static void main(String[] args) {

double n1 = -4.5, n2 = 3.9, n3 = 2.5;

if( n1 >= n2 && n1 >= n3)


System.out.println(n1 + " is the largest number.");

else if (n2 >= n1 && n2 >= n3)

System.out.println(n2 + " is the largest number.");

else

System.out.println(n3 + " is the largest number.");

Output

3.9 is the largest number.

In the above program, three numbers -4.5, 3.9 and 2.5 are stored in variables n1, n2 and n3 respectively.

Then, to find the largest, the following conditions are checked using if else statements

If n1 is greater or equals to both n2 and n3, n1 is the greatest.

If n2 is greater or equals to both n1 and n3, n2 is the greatest.

Else, n3 is the greatest.

The greatest number can also be found using a nested if..else statement.

Example 2: Find the largest number among three using nested if..else statement

public class Largest {

public static void main(String[] args) {

double n1 = -4.5, n2 = 3.9, n3 = 5.5;

if(n1 >= n2) {


if(n1 >= n3)

System.out.println(n1 + " is the largest number.");

else

System.out.println(n3 + " is the largest number.");

} else {

if(n2 >= n3)

System.out.println(n2 + " is the largest number.");

else

System.out.println(n3 + " is the largest number.");

Output

5.5 is the largest number.

In the above program, instead of checking for two conditions in a single if statement, we use nested if to find the
greatest.

Then, to find the largest, the following conditions are checked using if else statements

If n1 is greater or equals to n2,

and if n1 is greater or equals to n3, n1 is the greatest.

else, n3 is the greatest.

Else,

if n2 is greater or equals to both n3, n2 is the greatest.

else, n3 is the greatest.

10. Java Program to Find all Roots of a Quadratic Equation


In this program, you'll learn to find all roots of a quadratic equation and print them using format() in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Math sqrt()

The standard form of a quadratic equation is:

ax2 + bx + c = 0, where

a, b and c are real numbers and

a≠0

The term b2-4ac is known as the determinant of a quadratic equation. The determinant tells the nature of the
roots.

If determinant is greater than 0, the roots are real and different.

If determinant is equal to 0, the roots are real and equal.

If determinant is less than 0, the roots are complex and different.

Example: Java Program to Find Roots of a Quadratic Equation

public class Quadratic {

public static void main(String[] args) {

double a = 2.3, b = 4, c = 5.6;

double root1, root2;

double determinant = b * b - 4 * a * c;

// condition for real and different roots

if(determinant > 0) {

root1 = (-b + Math.sqrt(determinant)) / (2 * a);

root2 = (-b - Math.sqrt(determinant)) / (2 * a);

System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);


}

// Condition for real and equal roots

else if(determinant == 0) {

root1 = root2 = -b / (2 * a);

System.out.format("root1 = root2 = %.2f;", root1);

// If roots are not real

else {

double realPart = -b / (2 *a);

double imaginaryPart = Math.sqrt(-determinant) / (2 * a);

System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart,


imaginaryPart);

Output

root1 = -0.87+1.30i and root2 = -0.87-1.30i

In the above program, the coefficients a, b, and c are set to 2.3, 4, and 5.6 respectively. Then, the determinant is
calculated as b2 - 4ac.

Based on the value of the determinant, the roots are calculated as given in the formula above. Notice we've
used library function Math.sqrt() to calculate the square root of a number.

The calculated roots (either real or complex) are printed on the screen using format() function in Java. The
format() function can also be replaced by printf() as:

System.out.printf("root1 = root2 = %.2f;", root1);


11. Java Program to Check Leap Year
In this program, you'll learn to check if the given year is a leap year or not. This is checked using a if else
statement.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Operators

Java if, if...else Statement

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap
year only if it is perfectly divisible by 400.

Example: Java Program to Check a Leap Year

public class LeapYear {

public static void main(String[] args) {

int year = 1900;

boolean leap = false;

if(year % 4 == 0)

if( year % 100 == 0)

// year is divisible by 400, hence the year is a leap year

if ( year % 400 == 0)

leap = true;

else

leap = false;

else

leap = true;
}

else

leap = false;

if(leap)

System.out.println(year + " is a leap year.");

else

System.out.println(year + " is not a leap year.");

Output

1900 is not a leap year.

When you change the value of year to 2012, the output will be:

2012 is a leap year.

In the above program, the given year 1900 is stored in the variable year.

Since 1900 is divisible by 4 and is also a century year (ending with 00), it has been divisible by 400 for a leap
year. Since it's not divisible by 400, 1900 is not a leap year.

But, if we change year to 2000, it is divisible by 4, is a century year, and is also divisible by 400. So, 2000 is a leap
year.

Likewise, If we change year to 2012, it is divisible by 4 and is not a century year, so 2012 a leap year. We don't
need to check if 2012 is divisible by 400 or not.

12. Java Program to Check Whether a Character is Alphabet or Not


In this program, you'll learn to check whether a given character is an alphabet or not. This is done using an if else
statement or a ternary operator in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Operators

Example 1: Java Program to Check Alphabet using if else

public class Alphabet {

public static void main(String[] args) {

char c = '*';

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.");

Output

* is not an alphabet.

In Java, the char variable stores the ASCII value of a character (number between 0 and 127) rather than the
character itself.

The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from
65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122. Similarly, alphabet A is stored as 65
and alphabet Z is stored as 90.

Now, when we compare variable c between 'a' to 'z' and 'A' to 'Z', the variable is compared with the ASCII value
of the alphabets 97 to 122 and 65 to 90 respectively.

Since the ASCII value of * does not fall in between the ASCII value of alphabets. Hence, the program outputs * is
not an alphabet.
You can also solve the problem using ternary operator in Java.

Example 2: Java Program to Check Alphabet using ternary operator

public class Alphabet {

public static void main(String[] args) {

char c = 'A';

String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')

? c + " is an alphabet."

: c + " is not an alphabet.";

System.out.println(output);

Output

A is an alphabet.

In the above program, the if else statement is replaced with ternary operator (? :).

Example 3: Java Program to Check Alphabet using isAlphabetic() Method

class Main {

public static void main(String[] args) {

// declare a variable

char c = 'a';

// checks if c is an alphabet
if (Character.isAlphabetic(c)) {

System.out.println(c + " is an alphabet.");

else {

System.out.println(c + " is not an alphabet.");

Output

a is an alphabet.

In the above example, notice the expression,

Character.isAlphabetic(c)

Here, we have used the isAlphabetic() method of the Character class. It returns true if the specified variable is an
alphabet. Hence, the code inside if block is executed.

13. Java Program to Calculate the Sum of Natural Numbers


In this program, you'll learn to calculate the sum of natural numbers using for loop and while loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java while and do...while Loop

The positive numbers 1, 2, 3... are known as natural numbers and its sum is the result of all numbers starting
from 1 to the given number.

For n, the sum of natural numbers is:

1 + 2 + 3 + ... + n

Example 1: Sum of Natural Numbers using for loop


public class SumNatural {

public static void main(String[] args) {

int num = 100, sum = 0;

for(int i = 1; i <= num; ++i)

// sum = sum + i;

sum += i;

System.out.println("Sum = " + sum);

Output

Sum = 5050

The above program loops from 1 to the given num(100) and adds all numbers to the variable sum.

You can solve this problem using a while loop as follows:

Example 2: Sum of Natural Numbers using while loop

public class SumNatural {

public static void main(String[] args) {

int num = 50, i = 1, sum = 0;


while(i <= num)

sum += i;

i++;

System.out.println("Sum = " + sum);

Output

Sum = 1275

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's because the number of
iteration (up to num) is known.

Visit this page to learn how to find the sum of natural numbers using recursion.

14. Java Program to Find Factorial of a Number


In this program, you'll learn to find the factorial of a number using for and while loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java while and do...while Loop

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

Example 1: Find Factorial of a number using for loop


public class Factorial {

public static void main(String[] args) {

int num = 10;

long factorial = 1;

for(int i = 1; i <= num; ++i)

// factorial = factorial * i;

factorial *= i;

System.out.printf("Factorial of %d = %d", num, factorial);

Output

Factorial of 10 = 3628800

In this program, we've used for loop to loop through all numbers between 1 and the given number num (10),
and the product of each number till num is stored in a variable factorial.

We've used long instead of int to store large results of factorial. However, it's still not big enough to store the
value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable declared in java.math library.

Example 2: Find Factorial of a number using BigInteger

import java.math.BigInteger;

public class Factorial {

public static void main(String[] args) {


int num = 30;

BigInteger factorial = BigInteger.ONE;

for(int i = 1; i <= num; ++i)

// factorial = factorial * i;

factorial = factorial.multiply(BigInteger.valueOf(i));

System.out.printf("Factorial of %d = %d", num, factorial);

Output

Factorial of 30 = 265252859812191058636308480000000

Here, instead of long, we use BigInteger variable factorial.

Since, * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be casted to
BigInteger for multiplication.

Likewise, we can also use a while loop to solve this problem.

Example 3: Find Factorial of a number using while loop

public class Factorial {

public static void main(String[] args) {

int num = 5, i = 1;

long factorial = 1;

while(i <= num)

{
factorial *= i;

i++;

System.out.printf("Factorial of %d = %d", num, factorial);

Output

Factorial of 5 = 120

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's because the number of
iteration (upto num) is known.

Visit this page to learn to find factorial of a number using recursion.

15. Java Program to Generate Multiplication Table


In this program, you'll learn to generate multiplication table of a given number. This is done by using a for and a
while loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java while and do...while Loop

Example 1: Generate Multiplication Table using for loop

public class MultiplicationTable {

public static void main(String[] args) {

int num = 5;

for(int i = 1; i <= 10; ++i)


{

System.out.printf("%d * %d = %d \n", num, i, num * i);

Output

5*1=5

5 * 2 = 10

5 * 3 = 15

5 * 4 = 20

5 * 5 = 25

5 * 6 = 30

5 * 7 = 35

5 * 8 = 40

5 * 9 = 45

5 * 10 = 50

The same multiplication table can also be generated using a while loop in Java.

Example 2: Generate Multiplication Table using while loop

public class MultiplicationTable {

public static void main(String[] args) {

int num = 9, i = 1;

while(i <= 10)

System.out.printf("%d * %d = %d \n", num, i, num * i);

i++;
}

Output

9*1=9

9 * 2 = 18

9 * 3 = 27

9 * 4 = 36

9 * 5 = 45

9 * 6 = 54

9 * 7 = 63

9 * 8 = 72

9 * 9 = 81

9 * 10 = 90

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's because the number of
iteration (from 1 to 10) is known.

16. Java Program to Display Fibonacci Series


In this program, you'll learn to display fibonacci series in Java using for and while loops. You'll learn to display
the series upto a specific term or a number.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java while and do...while Loop

The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of
the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Example 1: Display Fibonacci series using for loop

public class Fibonacci {

public static void main(String[] args) {

int n = 10, t1 = 0, t2 = 1;

System.out.print("First " + n + " terms: ");

for (int i = 1; i <= n; ++i)

System.out.print(t1 + " + ");

int sum = t1 + t2;

t1 = t2;

t2 = sum;

Output

0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

In the above program, first (t1) and second (t2) terms are initialized to the first two terms of the Fibonacci series
0 and 1 respectively.

Then, for loop iterates to n (number of terms) displaying the sum of the previous two terms stored in variable t1.

You can also generate Fibonacci series using a while loop in Java.

Example 2: Display Fibonacci series using while loop

public class Fibonacci {


public static void main(String[] args) {

int i = 1, n = 10, t1 = 0, t2 = 1;

System.out.print("First " + n + " terms: ");

while (i <= n)

System.out.print(t1 + " + ");

int sum = t1 + t2;

t1 = t2;

t2 = sum;

i++;

The output is the same as the above program.

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's because the number of
iteration (from 1 to n) is known.

Example 3: Display Fibonacci series up to a given number (instead of terms)

public class Fibonacci {

public static void main(String[] args) {


int n = 100, t1 = 0, t2 = 1;

System.out.print("Upto " + n + ": ");

while (t1 <= n)

System.out.print(t1 + " + ");

int sum = t1 + t2;

t1 = t2;

t2 = sum;

Output

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

Instead of displaying the series up to a specific number, this program displays it until a given number (100).

For this, we just need to compare the sum of the last two numbers (t1) with n.

If t1 is less than or equals to n, print t1. Else, we're finished displaying all terms.

17. Java Program to Find GCD of two Numbers


In this program, you'll learn to find GCD of two numbers in Kotlin. This is done by using for and while loops with
the help of if else statements.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java for Loop


Java while and do...while Loop

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a
remainder).

Example 1: Find GCD of two numbers using for loop and if statement

public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = 153, gcd = 1;

for(int i = 1; i <= n1 && i <= n2; ++i)

// Checks if i is factor of both integers

if(n1 % i==0 && n2 % i==0)

gcd = i;

System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);

Output

G.C.D of 81 and 153 is 9

Here, two numbers whose GCD are to be found are stored in n1 and n2 respectively.

Then, a for loop is executed until i is less than both n1 and n2. This way, all numbers between 1 and smallest of
the two numbers are iterated to find the GCD.

If both n1 and n2 are divisble by i, gcd is set to the number. This goes on until it finds the largest number (GCD)
which divides both n1 and n2 without remainder.
We can also solve this problem using a while loop as follows:

Example 2: Find GCD of two numbers using while loop and if else statement

public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = 153;

while(n1 != n2)

if(n1 > n2)

n1 -= n2;

else

n2 -= n1;

System.out.println("G.C.D = " + n1);

Output

G.C.D = 9

This is a better way to find the GCD. In this method, smaller integer is subtracted from the larger integer, and
the result is assigned to the variable holding larger integer. This process is continued until n1 and n2 are equal.

The above two programs works as intended only if the user enters positive integers. Here's a little modification
of the second example to find the GCD for both positive and negative integers.
Example 3: GCD for both positive and negative numbers

public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = -153;

// Always set to positive

n1 = ( n1 > 0) ? n1 : -n1;

n2 = ( n2 > 0) ? n2 : -n2;

while(n1 != n2)

if(n1 > n2)

n1 -= n2;

else

n2 -= n1;

System.out.println("G.C.D = " + n1);

Output

G.C.D = 9

18. Java Program to Find LCM of two Numbers


In this program, you'll learn to find the lcm of two number by using GCD, and by not using GCD. This is done
using for and while loops in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java while and do...while Loop

The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a
remainder).

Example 1: LCM using while Loop and if Statement

public class Main {

public static void main(String[] args) {

int n1 = 72, n2 = 120, lcm;

// maximum number between n1 and n2 is stored in lcm

lcm = (n1 > n2) ? n1 : n2;

// Always true

while(true) {

if( lcm % n1 == 0 && lcm % n2 == 0 ) {

System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);

break;

++lcm;

Output

The LCM of 72 and 120 is 360.

In this program, the two numbers whose LCM is to be found are stored in variables n1 and n2 respectively.
Then, we initially set lcm to the largest of the two numbers. This is because, LCM cannot be less than the largest
number.

Inside the infinite while loop (while(true)), we check if lcm perfectly divides both n1 and n2 or not.

If it does, we've found the LCM. We print the LCM and break out from the while loop using break statement.

Else, we increment lcm by 1 and re-test the divisibility condition.

We can also use GCD to find the LCM of two numbers using the following formula:

LCM = (n1 * n2) / GCD

If you don't know how to calculate GCD in Java, check Java Program to find GCD of two numbers.

Example 2: Calculate LCM using GCD

public class Main {

public static void main(String[] args) {

int n1 = 72, n2 = 120, gcd = 1;

for(int i = 1; i <= n1 && i <= n2; ++i) {

// Checks if i is factor of both integers

if(n1 % i == 0 && n2 % i == 0)

gcd = i;

int lcm = (n1 * n2) / gcd;

System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);

}
The output of this program is the same as Example 1.

Here, inside the for loop, we calculate the GCD of the two numbers - n1 and n2. After the calculation, we use the
above formula to calculate the LCM.

19. Java Program to Display Characters from A to Z using loop


In this program, you'll learn to print English alphabets using for loop in Java. You'll also learn learn to print only
uppercased and lowercased alphabets.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java for Loop

Example 1: Display Uppercased A to Z using for loop

public class Characters {

public static void main(String[] args) {

char c;

for(c = 'A'; c <= 'Z'; ++c)

System.out.print(c + " ");

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

You can loop through A to Z using for loop because they are stored as ASCII characters in Java.

So, internally, you loop through 65 to 90 to print the English alphabets.


With a little modification, you can display lowercased alphabets as shown in the example below.

Example 2: Display Lowercased a to z using for loop

public class Characters {

public static void main(String[] args) {

char c;

for(c = 'a'; c <= 'z'; ++c)

System.out.print(c + " ");

Output

abcdefghijklmnopqrstuvwxyz

You simply replace 'A' with 'a' and 'Z' with 'z' to display the lowercased alphabets. In this case, internally you
loop through 97 to 122.

20. Java Program to Count Number of Digits in an Integer


In this program, you'll learn to count the number of digits using a while loop and for loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java while and do...while Loop

Java for Loop

Example 1: Count Number of Digits in an Integer using while loop

public class NumberDigits {


public static void main(String[] args) {

int count = 0, num = 3452;

while(num != 0)

// num = num/10

num /= 10;

++count;

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

Output

Number of digits: 4

In this program, while the loop is iterated until the test expression num != 0 is evaluated to 0 (false).

After the first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.

After the second iteration, the value of num will be 34 and the count is incremented to 2.

After the third iteration, the value of num will be 3 and the count is incremented to 3.

After the fourth iteration, the value of num will be 0 and the count is incremented to 4.

Then the test expression is evaluated to false and the loop terminates.

Example 2: Count Number of Digits in an Integer using for loop

public class NumberDigits {

public static void main(String[] args) {


int count = 0, num = 123456;

for(; num != 0; num/=10, ++count) {

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

Output

Number of digits: 6

In this program, instead of using a while loop, we use a for loop without any body.

On each iteration, the value of num is divided by 10 and count is incremented by 1.

The for loop exits when num != 0 is false, i.e. num = 0.

Since, for loop doesn't have a body, you can change it to a single statement in Java as such:

for(; num != 0; num/=10, ++count);

21. Java Program to Reverse a Number


In this program, you'll learn to reverse a number using a while loop and a for loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java for Loop

Example 1: Reverse a Number using a while loop in Java


public class ReverseNumber {

public static void main(String[] args) {

int num = 1234, reversed = 0;

while(num != 0) {

int digit = num % 10;

reversed = reversed * 10 + digit;

num /= 10;

System.out.println("Reversed Number: " + reversed);

Output

Reversed Number: 4321

In this program, while loop is used to reverse a number as given in the following steps:

First, the remainder of the num divided by 10 is stored in the variable digit. Now, the digit contains the last digit
of num, i.e. 4.

digit is then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in
the reversed number. One-th place multiplied by 10 gives you tenth place, tenth gives you hundredth, and so
on. In this case, reversed contains 0 * 10 + 4 = 4.

num is then divided by 10 so that now it only contains the first three digits: 123.

After second iteration, digit equals 3, reversed equals 4 * 10 + 3 = 43 and num = 12

After third iteration, digit equals 2, reversed equals 43 * 10 + 2 = 432 and num = 1

After fourth iteration, digit equals 1, reversed equals 432 * 10 + 1 = 4321 and num = 0

Now num = 0, so the test expression num != 0 fails and while loop exits. reversed already contains the reversed
number 4321.
Example 2: Reverse a number using a for loop in Java

public class ReverseNumber {

public static void main(String[] args) {

int num = 1234567, reversed = 0;

for(;num != 0; num /= 10) {

int digit = num % 10;

reversed = reversed * 10 + digit;

System.out.println("Reversed Number: " + reversed);

Output

Reversed Number: 7654321

In the above program, the while loop is replaced by a for loop where:

no initialization expression is used

test expression remains the same (num != 0)

update/increment expression contains num /= 10.

So, after each iteration, the update expression runs which removes the last digit of num.

When the for loop exits, reversed will contain the reversed number.

22. Java Program to Calculate the Power of a Number


In this program, you'll learn to calculate the power of a number with and without using pow() function.
To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java for Loop

Java Math pow()

Example 1: Calculate power of a number using a while loop

public class Power {

public static void main(String[] args) {

int base = 3, exponent = 4;

long result = 1;

while (exponent != 0)

result *= base;

--exponent;

System.out.println("Answer = " + result);

Output

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying the result by base until the exponent becomes zero.
In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.

Example 2: Calculate the power of a number using a for loop

public class Power {

public static void main(String[] args) {

int base = 3, exponent = 4;

long result = 1;

for (;exponent != 0; --exponent)

result *= base;

System.out.println("Answer = " + result);

Output

Answer = 81

Here, instead of using a while loop, we've used a for loop.

After each iteration, the exponent is decremented by 1, and the result is multiplied by the base exponent
number of times.

Both programs above do not work if you have a negative exponent. For that, you need to use the pow() function
in Java standard library.
Example 3: Calculate the power of a number using pow() function

public class Power {

public static void main(String[] args) {

int base = 3, exponent = -4;

double result = Math.pow(base, exponent);

System.out.println("Answer = " + result);

Output

Answer = 0.012345679012345678

In this program, we use Java's Math.pow() function to calculate the power of the given base.

23. Java Program to Check Whether a Number is Palindrome or Not


In this program, you'll learn to check whether a number is palindrome or not in Java. This is done by using for
and while loop.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java while and do...while Loop

Java for Loop

Example 1: Program to Check Palindrome using while loop

public class Palindrome {

public static void main(String[] args) {


int num = 121, reversedInteger = 0, remainder, originalInteger;

originalInteger = num;

// reversed integer is stored in variable

while( num != 0 )

remainder = num % 10;

reversedInteger = reversedInteger * 10 + remainder;

num /= 10;

// palindrome if orignalInteger and reversedInteger are equal

if (originalInteger == reversedInteger)

System.out.println(originalInteger + " is a palindrome.");

else

System.out.println(originalInteger + " is not a palindrome.");

Output

121 is a palindrome number.

In this program,

First, given number (num)'s value is stored in another integer variable, originalInteger. This is because, we need
to compare the values of reversed number and original number at the end.

Then, a while loop is used to loop through num until it is equal to 0.

On each iteration, the last digit of num is stored in the remainder.

Then, the remainder is added to reversedInteger such that it is added to the next place value (multiplication by
10).
Then, the last digit is removed from num after division by 10.

Finally, reversedInteger and originalInteger are compared. If equal, it is a palindrome number. If not, it isn't.

Here are the execution steps that take place:

Palindrome execution steps

num num != 0 remainder reversedInteger

121 true 1 0 * 10 + 1 = 1

12 true 2 1 * 10 + 2 = 12

1 true 1 12 * 10 + 1 = 121

0 false - 121

Example 2: Program to Check Palindrome using for loop

public class Palindrome {

public static void main(String[] args) {

int num = 11221, reversedInteger = 0, remainder, originalInteger;

originalInteger = num;

// reversed integer is stored in variable

for( ;num != 0; num /= 10 )

remainder = num % 10;

reversedInteger = reversedInteger * 10 + remainder;

// palindrome if orignalInteger and reversedInteger are equal

if (originalInteger == reversedInteger)

System.out.println(originalInteger + " is a palindrome.");

else
System.out.println(originalInteger + " is not a palindrome.");

Output

11221 is not a palindrome.

In the above program, for loop is used instead of a while loop.

On each iteration, num /= 10 is executed and condition num !=0 is checked.

24. Java Program to Check Whether a Number is Prime or Not


In this article, you'll learn to check whether a number is prime or not. This is done using a for loop and while
loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java for Loop

A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by
any other number, it is not a prime number.

Example 1: Program to Check Prime Number using a for loop

public class Main {

public static void main(String[] args) {

int num = 29;

boolean flag = false;

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

// condition for nonprime number


if(num % i == 0)

flag = true;

break;

if (!flag)

System.out.println(num + " is a prime number.");

else

System.out.println(num + " is not a prime number.");

Output

29 is a prime number.

In the above program, for loop is used to determine if the given number num is prime or not.

Here, note that we are looping from 2 to num/2. It is because a number is not divisible by more than its half.

Inside the for loop, we check if the number is divisible by any number in the given range (2...num/2).

If num is divisible, flag is set to true and we break out of the loop. This determines num is not a prime number.

If num isn't divisible by any number, flag is false and num is a prime number.

Example 2: Program to Check Prime Number using a while loop

public class Main {

public static void main(String[] args) {


int num = 33, i = 2;

boolean flag = false;

while(i <= num/2)

// condition for nonprime number

if(num % i == 0)

flag = true;

break;

++i;

if (!flag)

System.out.println(num + " is a prime number.");

else

System.out.println(num + " is not a prime number.");

Output

33 is not a prime number.

In the above program, while loop is used instead of a for loop. The loop runs until i <= num/2. On each iteration,
whether num is divisble by i is checked and the value of i is incremented by 1.

Visit this page to learn, how you can display all prime numbers between two intervals.

25. Java Program to Display Prime Numbers Between Two Intervals


In this program, you'll learn to display prime numbers between two given intervals, low and high. You'll learn to
do this using a while and a for loop in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java if, if...else Statement

Java for Loop

Example: Display Prime Numbers Between two Intervals

public class Prime {

public static void main(String[] args) {

int low = 20, high = 50;

while (low < high) {

boolean flag = false;

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

// condition for nonprime number

if(low % i == 0) {

flag = true;

break;

if (!flag && low != 0 && low != 1)

System.out.print(low + " ");

++low;

}
}

Output

23 29 31 37 41 43 47

In this program, each number between low and high are tested for prime. The inner for loop checks whether the
number is prime or not.

You can check: Java Program to Check Prime Number for more explanation.

The difference between checking a single prime number compared to an interval is, you need to reset the value
of flag = false on each iteration of while loop.

Note: If you check the interval from 0 to 10. Then, you need to exclude 0 and 1. As 0 and 1 are not prime
numbers. The condition will be:

if (!flag && low != 0 && low != 1)

26. Java Program to Check Armstrong Number


In this program, you'll learn to check whether a given number is armstrong number or not. You'll learn to do this
by using a for loop and a while loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java if, if...else Statement

Java for Loop

A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For
example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.

Example 1: Check Armstrong Number for 3 digit number

public class Armstrong {

public static void main(String[] args) {

int number = 371, originalNumber, remainder, result = 0;

originalNumber = number;

while (originalNumber != 0)

remainder = originalNumber % 10;

result += Math.pow(remainder, 3);

originalNumber /= 10;

if(result == number)

System.out.println(number + " is an Armstrong number.");

else

System.out.println(number + " is not an Armstrong number.");

Output

371 is an Armstrong number.

First, given number (number)'s value is stored in another integer variable, originalNumber. This is because, we
need to compare the values of final number and original number at the end.

Then, a while loop is used to loop through originalNumber until it is equal to 0.

On each iteration, the last digit of num is stored in remainder.


Then, remainder is powered by 3 (number of digits) using Math.pow() function and added to result.

Then, the last digit is removed from originalNumber after division by 10.

Finally, result and number are compared. If equal, it is an Armstrong number. If not, it isn't.

Example 2: Check Armstrong number for n digits

public class Armstrong {

public static void main(String[] args) {

int number = 1634, originalNumber, remainder, result = 0, n = 0;

originalNumber = number;

for (;originalNumber != 0; originalNumber /= 10, ++n);

originalNumber = number;

for (;originalNumber != 0; originalNumber /= 10)

remainder = originalNumber % 10;

result += Math.pow(remainder, n);

if(result == number)

System.out.println(number + " is an Armstrong number.");

else

System.out.println(number + " is not an Armstrong number.");

Output
1634 is an Armstrong number.

In this program, instead of using while loop, we've used two for loops.

The first for loop is used to count the number of digits in the number. It is the condensed form of:

for (;originalNumber != 0; originalNumber /= 10) {

n++;

The second for loop then calculates the result where on each iteration, the remainder is powered by the number
of digits n.

Visit this page to learn, how you can display all armstrong numbers between two intervals.

27. Java Program to Display Armstrong Number Between Two Intervals


In this program, you'll learn to display all armstrong numbers between two given intervals, low and high, in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java if, if...else Statement

Java for Loop

A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For
example:

153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.

This program is built on the concept of how to check whether an integer is an Armstrong number or not.

Example: Armstrong Numbers Between Two Integers


public class Armstrong {

public static void main(String[] args) {

int low = 999, high = 99999;

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

1634 8208 9474 54748 92727 93084

In the above program, each number between the given interval high and low are checked.

After each check, the number of digits and the sum result is restored to 0.

28. Java Program to Display Prime Numbers Between Intervals Using


Function
In this program, you'll learn to display all prime numbers between the given intervals using a function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java while and do...while Loop

To find all prime numbers between two integers, checkPrimeNumber() function is created. This function checks
whether a number is prime or not.

Example: Prime Numbers Between Two Integers

public class Prime {

public static void main(String[] args) {

int low = 20, high = 50;

while (low < high) {

if(checkPrimeNumber(low))

System.out.print(low + " ");


++low;

public static boolean checkPrimeNumber(int num) {

boolean flag = true;

for(int i = 2; i <= num/2; ++i) {

if(num % i == 0) {

flag = false;

break;

return flag;

Output

23 29 31 37 41 43 47

In the above program, we've created a function named checkPrimeNumber() which takes a parameter num and
returns a boolean value.

If the number is prime, it returns true. If not, it returns false.

Based on the return value, the number is printed on the screen inside the main() method.

Note that inside the checkPrimeNumber() method, we are looping from 2 to num/2. This is because a number
cannot be divided by more than it's half.
Recommended Readings

Java Program to Check if a number is prime

29. Java Program to Display Armstrong Numbers Between Intervals Using


Function
In this program, you'll learn to display all armstrong numbers between two given intervals, low and high, using a
function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java for Loop

To find all Armstrong numbers between two integers, checkArmstrong() function is created. This function checks
whether a number is Armstrong or not.

Example: Armstrong Numbers Between Two Integers

public class Armstrong {

public static void main(String[] args) {

int low = 999, high = 99999;

for(int number = low + 1; number < high; ++number) {

if (checkArmstrong(number))

System.out.print(number + " ");

public static boolean checkArmstrong(int num) {

int digits = 0;
int result = 0;

int originalNumber = num;

// number of digits calculation

while (originalNumber != 0) {

originalNumber /= 10;

++digits;

originalNumber = num;

// 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 == num)

return true;

return false;

Output

1634 8208 9474 54748 92727 93084

In the above program, we've created a function named checkArmstrong() which takes a parameter num and
returns a boolean value.

If the number is Armstrong, it returns true. If not, it returns false.


Based on the return value, the number is printed on the screen inside main() function.

30. Java Program to Check Whether a Number can be Expressed as Sum of


Two Prime Numbers
In this program, you'll learn to check whether a given number can be expressed as a sum of two prime numbers
or not. This is done with the help of loops and break statements in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java for Loop

Java if, if...else Statement

To accomplish this task, checkPrime() function is created.

The checkPrime() returns 1 if the number passed to the function is a prime number.

Example: Integer as a Sum of Two Prime Numbers

public class CheckPrime {

public static void main(String[] args) {

int number = 34;

boolean flag = false;

for (int i = 2; i <= number / 2; ++i) {

// condition for i to be a prime number

if (checkPrime(i)) {

// condition for n-i to be a prime number

if (checkPrime(number - i)) {
// n = primeNumber1 + primeNumber2

System.out.printf("%d = %d + %d\n", number, i, number - i);

flag = true;

if (!flag)

System.out.println(number + " cannot be expressed as the sum of two prime numbers.");

// Function to check prime number

static boolean checkPrime(int num) {

boolean isPrime = true;

for (int i = 2; i <= num / 2; ++i) {

if (num % i == 0) {

isPrime = false;

break;

return isPrime;

Output

34 = 3 + 31
34 = 5 + 29

34 = 11 + 23

34 = 17 + 17

31. Java Program to Find the Sum of Natural Numbers using Recursion
In this program, you'll learn to find the sum of natural number using recursion in Java. This is done with the help
of a recursive function.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Recursion

The positive numbers 1, 2, 3... are known as natural numbers. The program below takes a positive integer from
the user and calculates the sum up to the given number.

You can find the sum of natural numbers using loop as well. However, you will learn to solve this problem using
recursion here.

Example: Sum of Natural Numbers Using Recursion

public class AddNumbers {

public static void main(String[] args) {

int number = 20;

int sum = addNumbers(number);

System.out.println("Sum = " + sum);

public static int addNumbers(int num) {

if (num != 0)

return num + addNumbers(num - 1);

else
return num;

Output

Sum = 210

The number whose sum is to be found is stored in a variable number.

Initially, the addNumbers() is called from the main() function with 20 passed as an argument.

The number (20) is added to the result of addNumbers(19).

In the next function call from addNumbers() to addNumbers(), 19 is passed which is added to the result of
addNumbers(18). This process continues until num is equal to 0.

When num is equal to 0, there is no recursive call and this returns the sum of integers to the main() function.

32. Java Program to Find Factorial of a Number Using Recursion


In this program, you'll learn to find and display the factorial of a number using a recursive function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Recursion

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

The factorial of a negative number doesn't exist. And the factorial of 0 is 1.

You will learn to find the factorial of a number using recursion in this example. Visit this page to learn, how you
can find the factorial of a number using loop.
Example: Factorial of a Number Using Recursion

public class Factorial {

public static void main(String[] args) {

int num = 6;

long factorial = multiplyNumbers(num);

System.out.println("Factorial of " + num + " = " + factorial);

public static long multiplyNumbers(int num)

if (num >= 1)

return num * multiplyNumbers(num - 1);

else

return 1;

Output

Factorial of 6 = 720

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is
passed. Since, it is called from the same function, it is a recursive call.

In each recursive call, the value of argument num is decreased by 1 until num reaches less than 1.

When the value of num is less than 1, there is no recursive call.

And each recursive calls returns giving us:


6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720

33. Java Program to Find G.C.D Using Recursion


In this program, you'll learn to find the GCD (Greatest Common Divisor) or HCF using a recursive function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Recursion

This program takes two positive integers and calculates GCD using recursion.

Visit this page to learn how you can calculate the GCD using loops.

Example: GCD of Two Numbers using Recursion

public class GCD {

public static void main(String[] args) {

int n1 = 366, n2 = 60;

int hcf = hcf(n1, n2);

System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf);

public static int hcf(int n1, int n2)

if (n2 != 0)

return hcf(n2, n1 % n2);

else

return n1;

}
}

Output

G.C.D of 366 and 60 is 6.

In the above program, the recursive function is called until n2 is 0. In the end, the value of n1 is the GCD or HCF
of the given two numbers.

Execution Steps

No. Recursive call n1 n2 n1 % n2

1 hcf(366, 60) 366 60 6

2 hcf(60, 6) 60 6 0

Final hcf(6, 0) 6 0 -

34. Java Program to Convert Binary Number to Decimal and vice-versa


In this program, you'll learn to convert binary number to a decimal number and vice-versa using functions in
Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Operators

Java while and do...while Loop

Visit this page to learn how to convert binary number to decimal.

Example 1: Program to convert binary number to decimal

public class BinaryDecimal {

public static void main(String[] args) {

long num = 110110111;

int decimal = convertBinaryToDecimal(num);

System.out.printf("%d in binary = %d in decimal", num, decimal);


}

public static int convertBinaryToDecimal(long num)

int decimalNumber = 0, i = 0;

long remainder;

while (num != 0)

remainder = num % 10;

num /= 10;

decimalNumber += remainder * Math.pow(2, i);

++i;

return decimalNumber;

Output

110110111 in binary = 439 in decimal

Visit this page to learn, how to convert decimal number to binary.

Example 2: Program to convert decimal number to binary

public class DecimalBinary {

public static void main(String[] args) {

int num = 19;

long binary = convertDecimalToBinary(num);

System.out.printf("%d in decimal = %d in binary", num, binary);

}
public static long convertDecimalToBinary(int n)

long binaryNumber = 0;

int remainder, i = 1, step = 1;

while (n!=0)

remainder = n % 2;

System.out.printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);

n /= 2;

binaryNumber += remainder * i;

i *= 10;

return binaryNumber;

Output

Step 1: 19/2, Remainder = 1, Quotient = 9

Step 2: 9/2, Remainder = 1, Quotient = 4

Step 3: 4/2, Remainder = 0, Quotient = 2

Step 4: 2/2, Remainder = 0, Quotient = 1

Step 5: 1/2, Remainder = 1, Quotient = 0

19 in decimal = 10011 in binary

35. Java Program to Convert Octal Number to Decimal and vice-versa


In this program, you'll learn to convert octal number to a decimal number and vice-versa using functions in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods

Java Operators

Java while and do...while Loop

Example 1: Program to Convert Decimal to Octal

public class DecimalOctal {

public static void main(String[] args) {

int decimal = 78;

int octal = convertDecimalToOctal(decimal);

System.out.printf("%d in decimal = %d in octal", decimal, octal);

public static int convertDecimalToOctal(int decimal)

int octalNumber = 0, i = 1;

while (decimal != 0)

octalNumber += (decimal % 8) * i;

decimal /= 8;

i *= 10;

return octalNumber;

Output

78 in decimal = 116 in octal


This conversion takes place as:

8 | 78

8 | 9 -- 6

8 | 1 -- 1

8 | 0 -- 1

(116)

Example 2: Program to Convert Octal to Decimal

public class OctalDecimal {

public static void main(String[] args) {

int octal = 116;

int decimal = convertOctalToDecimal(octal);

System.out.printf("%d in octal = %d in decimal", octal, decimal);

public static int convertOctalToDecimal(int octal)

int decimalNumber = 0, i = 0;

while(octal != 0)

decimalNumber += (octal % 10) * Math.pow(8, i);

++i;

octal/=10;

return decimalNumber;

}
}

Output

116 in octal = 78 in decimal

This conversion takes place as:

1 * 82 + 1 * 81 + 6 * 80 = 78

36. Java Program to Convert Binary Number to Octal and vice-versa


In this program, you'll learn to convert binary number to a octal number and vice-versa using functions in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Operators

Java while and do...while Loop

Example 1: Program to Convert Binary to Octal

In this program, we will first convert binary number to decimal. Then, the decimal number is converted to octal.

public class BinaryOctal {

public static void main(String[] args) {

long binary = 101001;

int octal = convertBinarytoOctal(binary);

System.out.printf("%d in binary = %d in octal", binary, octal);

public static int convertBinarytoOctal(long binaryNumber)

int octalNumber = 0, decimalNumber = 0, i = 0;


while(binaryNumber != 0)

decimalNumber += (binaryNumber % 10) * Math.pow(2, i);

++i;

binaryNumber /= 10;

i = 1;

while (decimalNumber != 0)

octalNumber += (decimalNumber % 8) * i;

decimalNumber /= 8;

i *= 10;

return octalNumber;

Output

101001 in binary = 51 in octal

This conversion takes place as:

Binary To Decimal

1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 41

Decimal to Octal

8 | 41

8 | 5 -- 1
8 | 0 -- 5

(51)

Example 2: Program to Convert Octal to Binary

In this program, the octal number to decimal to decimal at first. Then, the decimal number is converted to
binary number.

public class OctalBinary {

public static void main(String[] args) {

int octal = 67;

long binary = convertOctalToBinary(octal);

System.out.printf("%d in octal = %d in binary", octal, binary);

public static long convertOctalToBinary(int octalNumber)

int decimalNumber = 0, i = 0;

long binaryNumber = 0;

while(octalNumber != 0)

decimalNumber += (octalNumber % 10) * Math.pow(8, i);

++i;

octalNumber/=10;

i = 1;

while (decimalNumber != 0)

binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;

i *= 10;

return binaryNumber;

Output

67 in octal = 110111 in binary

This conversion takes place as:

Octal To Decimal

6 * 81 + 7 * 80 = 55

Decimal to Binary

2 | 55

2 | 27 -- 1

2 | 13 -- 1

2 | 6 -- 1

2 | 3 -- 0

2 | 1 -- 1

2 | 0 -- 1

(110111)

37. Java Program to Reverse a Sentence Using Recursion


In this program, you'll learn to reverse a given sentence using a recursive loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods

Java Recursion

Java String

Example: Reverse a Sentence Using Recursion

public class Reverse {

public static void main(String[] args) {

String sentence = "Go work";

String reversed = reverse(sentence);

System.out.println("The reversed sentence is: " + reversed);

public static String reverse(String sentence) {

if (sentence.isEmpty())

return sentence;

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

Output:

The reversed sentence is: krow oG

In the above program, we've a recursive function reverse().

On each iteration, we add (concatenate) the result of next reverse() function to the first character of sentence
using charAt(0).

The recursive call must be before the charAt(), because that way the last characters will start adding to the left-
hand side. If you reverse the order, you'll end up with the original sentence.

In the end, we end up with an empty sentence and reverse() returns the reversed sentence.
Note: The sentence.substring(1) method returns the portion of the string sentence starting from index 1 to end
of the string. To learn more, visit Java String substring().

Execution steps

Iteration reverse() substring() reversedString

1 reverse("Go work") "o Work" result + "G"

2 reverse("o Work") " Work"result + "o" + "G"

3 reverse(" Work") "Work" result + " " + "o" + "G"

4 reverse("Work") "ork" result + "W" + " " + "o" + "G"

5 reverse("ork") "rk" result + "o" + "W" + " " + "o" + "G"

6 reverse("rk") "k" result + "r" + "o" + "W" + " " + "o" + "G"

7 reverse("k") "" result + "k" + "r" + "o" + "W" + " " + "o" + "G"

Final reverse("") - "" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG"

38. Java Program to calculate the power using recursion


In this program, you'll learn to calculate the power of a number using a recursive function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Recursion

Example: Program to calculate power using recursion

public class Power {

public static void main(String[] args) {

int base = 3, powerRaised = 4;

int result = power(base, powerRaised);

System.out.printf("%d^%d = %d", base, powerRaised, result);


}

public static int power(int base, int powerRaised) {

if (powerRaised != 0)

return (base * power(base, powerRaised - 1));

else

return 1;

Output

3^4 = 81

In the above program, you calculate the power using a recursive function power().

In simple terms, the recursive function multiplies the base with itself for powerRaised times, which is:

3 * 3 * 3 * 3 = 81

Execution steps

Iteration power() powerRaised result

1 power(3, 4) 4 3 * result2

2 power(3, 3) 3 3 * 3 * result3

3 power(3, 2) 2 3 * 3 * 3 * result4

4 power(3, 1) 1 3 * 3 * 3 * 3 * resultfinal

Final power(3, 0) 0 3 * 3 * 3 * 3 * 1 = 81

39. Java Program to Calculate Average Using Arrays


In this program, you'll learn to calculate the average of the given arrays in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays

Java for-each Loop

Example: Program to Calculate Average Using Arrays

public class Average {

public static void main(String[] args) {

double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };

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: 27.69

In the above program, the numArray stores the floating-point values whose average is to be found.

Then, to calculate the average, we need to first calculate the sum of all elements in the array. This is done using
a for-each loop in Java.

Finally, we calculate the average by the formula:

average = sum of numbers / total count

In this case, the total count is given by numArray.length.

Finally, we print the average using format() function so that we limit the decimal points to only 2 using "%.2f"
40. Java Program to Find Largest Element of an Array
In this program, you'll learn to find the largest element in an array using a for loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java for-each Loop

Example: Find the largest element in an array

public class Largest {

public static void main(String[] args) {

double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };

double largest = numArray[0];

for (double num: numArray) {

if(largest < num)

largest = num;

System.out.format("Largest element = %.2f", largest);

Output

Largest element = 55.50

In the above program, we store the first element of the array in the variable largest.

Then, largest is used to compare other elements in the array. If any number is greater than largest, largest is
assigned the number.
In this way, the largest number is stored in largest when it is printed.

41. Java Program to Calculate Standard Deviation


In this program, you'll learn to calculate the standard deviation using a function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Methods

This program calculates the standard deviation of a individual series using arrays. Visit this page to learn about
Standard Deviation.

To calculate the standard deviation, calculateSD() function is created. The array containing 10 elements is
passed to the function and this function calculates the standard deviation and returns it to the main() function.

Example: Program to Calculate Standard Deviation

public class StandardDeviation {

public static void main(String[] args) {

double[] numArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

double SD = calculateSD(numArray);

System.out.format("Standard Deviation = %.6f", SD);

public static double calculateSD(double numArray[])

double sum = 0.0, standardDeviation = 0.0;

int length = numArray.length;


for(double num : numArray) {

sum += num;

double mean = sum/length;

for(double num: numArray) {

standardDeviation += Math.pow(num - mean, 2);

return Math.sqrt(standardDeviation/length);

Output

Standard Deviation = 2.872281

In the above program, we've used the help of Java Math.pow() and Java Math.sqrt() to calculate the power and
square root respectively.

Note: This program calculates the standard deviation of a sample. If you need to compute S.D. of a population,
return Math.sqrt(standardDeviation/(length-1)) instead of Math.sqrt(standardDeviation/length) from the
calculateSD() method.

42. Java Program to Add Two Matrix Using Multi-dimensional Arrays


In this program, you'll learn to add two matrices using multi-dimensional arrays in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java for Loop

Example: Program to Add Two Matrices


public class AddMatrices {

public static void main(String[] args) {

int rows = 2, columns = 3;

int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };

int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };

// Adding Two matrices

int[][] sum = new int[rows][columns];

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

for (int j = 0; j < columns; j++) {

sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];

// Displaying the result

System.out.println("Sum of two matrices is: ");

for(int[] row : sum) {

for (int column : row) {

System.out.print(column + " ");

System.out.println();

Output

Sum of two matrices is:

-2 8 7

10 8 6
In the above program, the two matrices are stored in 2d array, namely firstMatrix and secondMatrix. We've also
defined the number of rows and columns and stored them in variables rows and columns respectively.

Then, we initialize a new array of the given rows and columns called sum. This matrix array stores the addition of
the given matrices.

We loop through each index of both arrays to add and store the result.

Finally, we loop through each element in the sum array using the for-each loop to print the elements.

43. Java Program to Multiply to Matrix Using Multi-dimensional Arrays


In this program, you'll learn to multiply two matrices using multi-dimensional arrays in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Multidimensional Arrays

For matrix multiplication to take place, the number of columns of first matrix must be equal to the number of
rows of second matrix. In our example, i.e.

c1 = r2

Also, the final product matrix is of size r1 x c2, i.e.

product[r1][c2]

You can also multiply two matrices using functions.

Example: Program to Multiply Two Matrices

public class MultiplyMatrices {

public static void main(String[] args) {

int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;

int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };

int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices

int[][] product = new int[r1][c2];

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

for (int j = 0; j < c2; j++) {

for (int k = 0; k < c1; k++) {

product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];

// Displaying the result

System.out.println("Sum of two matrices is: ");

for(int[] row : product) {

for (int column : row) {

System.out.print(column + " ");

System.out.println();

Output

Sum of two matrices is:

24 29

6 25

In the above program, the multiplication takes place as:


|- (a11 x b11) + (a12 x b21) + (a13 x b31) (a11 x b12) + (a12 x b22) + (a13 x b32) -|

|_ (a21 x b11) + (a22 x b21) + (a23 x b31) (a21 x b12) + (a22 x b22) + (a23 x b32) _|

In our example, it takes place as:

|- (3 x 2) + (-2 x -9) + (5 x 0) = 24 (3 x 3) + (-2 x 0) + (5 x 4) = 29 -|

|_ (3 x 2) + ( 0 x -9) + (4 x 0) = 6 (3 x 3) + ( 0 x 0) + (4 x 4) = 25 _|

44. Java Program to Multiply two Matrices by Passing Matrix to a Function


In this program, you'll learn to multiply two matrices using a function in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Multidimensional Arrays

For matrix multiplication to take place, the number of columns of the first matrix must be equal to the number
of rows of the second matrix. In our example, i.e.

c1 = r2

Also, the final product matrix is of size r1 x c2, i.e.

product[r1][c2]

You can also multiply two matrices without functions.

Example: Program to Multiply Two Matrices using a Function

public class MultiplyMatrices {

public static void main(String[] args) {

int r1 = 2, c1 = 3;

int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };

int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices

int[][] product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2);

// Displaying the result

displayProduct(product);

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) {

int[][] product = new int[r1][c2];

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

for (int j = 0; j < c2; j++) {

for (int k = 0; k < c1; k++) {

product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];

return product;

public static void displayProduct(int[][] product) {

System.out.println("Product of two matrices is: ");

for(int[] row : product) {

for (int column : row) {

System.out.print(column + " ");

System.out.println();
}

Output

Product of two matrices is:

24 29

6 25

In the above program, there are two functions:

multiplyMatrices() which multiplies the two given matrices and returns the product matrix

displayProduct() which displays the output of the product matrix on the screen.

The multiplication takes place as:

|- (a11 x b11) + (a12 x b21) + (a13 x b31) (a11 x b12) + (a12 x b22) + (a13 x b32) -|

|_ (a21 x b11) + (a22 x b21) + (a23 x b31) (a21 x b12) + (a22 x b22) + (a23 x b32) _|

In our example, it takes place as:

|- (3 x 2) + (-2 x -9) + (5 x 0) = 24 (3 x 3) + (-2 x 0) + (5 x 4) = 29 -|

|_ (3 x 2) + ( 0 x -9) + (4 x 0) = 6 (3 x 3) + ( 0 x 0) + (4 x 4) = 25 _|

45. Java Program to Find Transpose of a Matrix


In this program, you'll learn to find and print the transpose of a given matrix in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Multidimensional Arrays

Java Methods

Transpose of a matrix is the process of swapping the rows to columns. For 2x3 matrix,
Matrix

a11 a12 a13

a21 a22 a23

Transposed Matrix

a11 a21

a12 a22

a13 a23

Example: Program to Find Transpose of a Matrix

public class Transpose {

public static void main(String[] args) {

int row = 2, column = 3;

int[][] matrix = { {2, 3, 4}, {5, 6, 4} };

// Display current matrix

display(matrix);

// Transpose the matrix

int[][] transpose = new int[column][row];

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

for (int j = 0; j < column; j++) {

transpose[j][i] = matrix[i][j];

// Display transposed matrix

display(transpose);

}
public static void display(int[][] matrix) {

System.out.println("The matrix is: ");

for(int[] row : matrix) {

for (int column : row) {

System.out.print(column + " ");

System.out.println();

Output

The matrix is:

2 3 4

5 6 4

The matrix is:

2 5

3 6

4 4

In the above program, display() function is only used to print the contents of a matrix to the screen.

Here, the given matrix is of form 2x3, i.e. row = 2 and column = 3.

For the transposed matrix, we change the order of transposed to 3x2, i.e. row = 3 and column = 2. So, we have
transpose = int[column][row]

The transpose of the matrix is calculated by simply swapping columns to rows:

transpose[j][i] = matrix[i][j];
46. Java Program to Print an Array
In this program, you'll learn different techniques to print the elements of a given array in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Multidimensional Arrays

Java for Loop

Example 1: Print an Array using For loop

public class Array {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

for (int element: array) {

System.out.println(element);

Output

In the above program, the for-each loop is used to iterate over the given array, array.

It accesses each element in the array and prints using println().


Example 2: Print an Array using standard library Arrays

import java.util.Arrays;

public class Array {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(array));

Output

[1, 2, 3, 4, 5]

In the above program, the for loop has been replaced by a single line of code using Arrays.toString() function.

As you can see, this gives a clean output without any extra lines of code.

Example 3: Print a Multi-dimensional Array

import java.util.Arrays;

public class Array {

public static void main(String[] args) {

int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};

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

}
Output

[[1, 2], [3, 4], [5, 6, 7]]

In the above program, since each element in array contains another array, just using Arrays.toString() prints the
address of the elements (nested array).

To get the numbers from the inner array, we just another function Arrays.deepToString(). This gets us the
numbers 1, 2 and so on, we are looking for.

This function works for 3-dimensional arrays as well.

47. Java Program to Concatenate Two Arrays


In this program, you'll learn to concatenate two arrays in Java using arraycopy and without it.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java for-each Loop

Example 1: Concatenate Two Arrays using arraycopy

import java.util.Arrays;

public class Concat {

public static void main(String[] args) {

int[] array1 = {1, 2, 3};

int[] array2 = {4, 5, 6};

int aLen = array1.length;

int bLen = array2.length;

int[] result = new int[aLen + bLen];


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

System.arraycopy(array2, 0, result, aLen, bLen);

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

Output

[1, 2, 3, 4, 5, 6]

In the above program, we've two integer arrays array1 and array2.

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we
create a new integer array result with length aLen + bLen.

Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

The arraycopy(array1, 0, result, 0, aLen) function, in simple terms, tells the program to copy array1 starting from
index 0 to result from index 0 to aLen.

Likewise, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2 starting from index 0 to
result from index aLen to bLen.

Example 2: Concatenate Two Arrays without using arraycopy

import java.util.Arrays;

public class Concat {

public static void main(String[] args) {

int[] array1 = {1, 2, 3};

int[] array2 = {4, 5, 6};


int length = array1.length + array2.length;

int[] result = new int[length];

int pos = 0;

for (int element : array1) {

result[pos] = element;

pos++;

for (int element : array2) {

result[pos] = element;

pos++;

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

Output

[1, 2, 3, 4, 5, 6]

In the above program, instead of using arraycopy, we manually copy each element of both arrays array1 and
array2 to result.

We store the total length required for result, i.e. array1.length + array2. length. Then, we create a new array
result of the length.

Now, we use the for-each loop to iterate through each element of array1 and store it in the result. After
assigning it, we increase the position pos by 1, pos++.

Likewise, we do the same for array2 and store each element in result starting from the position after array1.
48. Java Program to Check if An Array Contains a Given Value
In this program, you'll learn to check if an array contains a given value in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Variables and (Primitive) Data Types

Example 1: Check if Int Array contains a given value

public class Contains {

public static void main(String[] args) {

int[] num = {1, 2, 3, 4, 5};

int toFind = 3;

boolean found = false;

for (int n : num) {

if (n == toFind) {

found = true;

break;

if(found)

System.out.println(toFind + " is found.");

else

System.out.println(toFind + " is not found.");

Output
3 is found.

In the above program, we have an array of integers stored in variable num. Likewise, the number to be found is
stored in toFind.

Now, we use a for-each loop to iterate through all elements of num and check individually if toFind is equal to n
or not.

If yes, we set found to true and break from the loop. If not, we move to the next iteration.

Example 2: Check if an array contains given value using Stream

import java.util.stream.IntStream;

public class Contains {

public static void main(String[] args) {

int[] num = {1, 2, 3, 4, 5};

int toFind = 7;

boolean found = IntStream.of(num).anyMatch(n -> n == toFind);

if(found)

System.out.println(toFind + " is found.");

else

System.out.println(toFind + " is not found.");

Output

7 is not found.
In the above program, instead of using a for-each loop, we convert the array to an IntStream and use its
anyMatch() method.

anyMatch() method takes a predicate, an expression, or a function that returns a boolean value. In our case, the
predicate compares each element n in the stream to toFind and returns true or false.

If any of the element n returns true, found is set to true as well.

Example 3: Check if an array contains a given value for non-primitive types

import java.util.Arrays;

public class Contains {

public static void main(String[] args) {

String[] strings = {"One", "Two", "Three", "Four", "Five"};

String toFind = "Four";

boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind));

if(found)

System.out.println(toFind + " is found.");

else

System.out.println(toFind + " is not found.");

Output

Four is found.

In the above program, we've used a non-primitive data type String and used Arrays's stream() method to first
convert it to a stream and anyMatch() to check if the array contains the given value toFind.
49. Java Program to Find the Frequency of Character in a String
In this program, you'll learn to find the occurence (frequency) of a character in a given string.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java for Loop

Java String charAt()

Example: Find Frequency of Character

public class Frequency {

public static void main(String[] args) {

String str = "This website is awesome.";

char ch = 'e';

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 e = 4

In the above program, the length of the given string, str, is found using the string method length().
We loop through each character in the string using charAt() function which takes the index (i) and returns the
character in the given index.

We compare each character to the given character ch. If it's a match, we increase the value of frequency by 1.

In the end, we get the total occurrence of a character stored in frequency and print it.

50. Java Program to Count the Number of Vowels and Consonants in a


Sentence
In this program, you'll learn to count the number of vowels, consonants, digits and spaces in a given sentence
using if else in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java if, if...else Statement

Example: Program to count vowels, consonants, digits, and spaces

public class Count {

public static void main(String[] args) {

String line = "This website is aw3som3.";

int vowels = 0, consonants = 0, digits = 0, spaces = 0;

line = line.toLowerCase();

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

char ch = line.charAt(i);

if(ch == 'a' || ch == 'e' || ch == 'i'

|| ch == 'o' || ch == 'u') {

++vowels;

}
else if((ch >= 'a'&& ch <= 'z')) {

++consonants;

else if( ch >= '0' && ch <= '9')

++digits;

else if (ch ==' ')

++spaces;

System.out.println("Vowels: " + vowels);

System.out.println("Consonants: " + consonants);

System.out.println("Digits: " + digits);

System.out.println("White spaces: " + spaces);

Output

Vowels: 6

Consonants: 11

Digits: 3

White spaces: 3

In the above example, we've 4 conditions for each of the checks.

The first if condition is to check whether the character is a vowel or not.

The else if condition following if is to check whether the character is a consonant or not. The order should be the
same otherwise, all vowels are treated as consonants as well.

The 3rd condition (else-if) is to check whether the character is between 0 to 9 or not.
Finally, the last condition is to check whether the character is a space character or not.

For this, we've lowercased the line using toLowerCase(). This is an optimization done not to check for capitalized
A to Z and vowels.

We've used length() function to know the length of the string and charAt() to get the character at the given
index (position).

51. Java Program to Sort Elements in Lexicographical Order (Dictionary


Order)
In this program, you'll learn to sort the element words in lexicographical order using a for loop and if else in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java if, if...else Statement

Java String

Example: Program to Sort Strings in Dictionary Order

public class Sort {

public static void main(String[] args) {

String[] words = { "Ruby", "C", "Python", "Java" };

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

for (int j = i + 1; j < 4; ++j) {

if (words[i].compareTo(words[j]) > 0) {

// swap words[i] with words[j[

String temp = words[i];

words[i] = words[j];

words[j] = temp;

}
}

System.out.println("In lexicographical order:");

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

System.out.println(words[i]);

Output

In lexicographical order:

Java

Python

Ruby

In the above program, the list of 5 words to sorted is stored in a variable, words.

Then, we loop through each word (words[i]) and compare it with all words (words[j]) after it in the array. This is
done by using the string's compareTo() method.

If the return value of compareTo() is greater than 0, it has to be swapped in position, i.e. words[i] comes after
words[j]. So, in each iteration, words[i] contains the earliest word.

Execution Steps

Iteration Initial words i j words[]

1 { "Ruby", "C", "Python", "Java" } 0 1 { "C", "Ruby", "Python", "Java" }

2 { "C", "Ruby", "Python", "Java" } 0 2 { "C", "Ruby", "Python", "Java" }

3 { "C", "Ruby", "Python", "Java" } 0 3 { "C", "Ruby", "Python", "Java" }

4 { "C", "Ruby", "Python", "Java" } 1 2 { "C", "Python", "Ruby", "Java" }

5 { "C", "Python", "Ruby", "Java" } 1 3 { "C", "Java", "Ruby", "Python" }


Final { "C", "Java", "Ruby", "Python" } 2 3 { "C", "Java", "Python", "Ruby" }

52. Java Program to Add Two Complex Numbers by Passing Class to a


Function
In this program, you'll learn to add two complex numbers in Java by creating a class named Complex and passing
it into a function add().

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Add Two Complex Numbers

public class Complex {

double real;

double imag;

public Complex(double real, double imag) {

this.real = real;

this.imag = imag;

public static void main(String[] args) {

Complex n1 = new Complex(2.3, 4.5),

n2 = new Complex(3.4, 5.0),

temp;

temp = add(n1, n2);

System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag);


}

public static Complex add(Complex n1, Complex n2)

Complex temp = new Complex(0.0, 0.0);

temp.real = n1.real + n2.real;

temp.imag = n1.imag + n2.imag;

return(temp);

Output

Sum = 5.7 + 9.5i

In the above program, we created a class Complex with two member variables: real and imag. As name suggests,
real stores real part of a complex number and imag stores the imaginary part.

The Complex class has a constructor with initializes the value of real and imag.

We also created a new static function add() that takes two complex numbers as parameters and returns the
result as a complex number.

Inside the add() method, we just add the real and imaginary parts of complex numbers n1 and n2, store it in a
new variable temp and return temp.

Then, in the calling function main(), we print it using printf() function.

53. Java Program to Calculate Difference Between Two Time Periods


In this program, you'll learn to calculate the difference between two time periods in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Class and Objects

Example: Calculate Difference Between Two Time Periods

public class Time {

int seconds;

int minutes;

int hours;

public Time(int hours, int minutes, int seconds) {

this.hours = hours;

this.minutes = minutes;

this.seconds = seconds;

public static void main(String[] args) {

// create objects of Time class

Time start = new Time(8, 12, 15);

Time stop = new Time(12, 34, 55);

Time diff;

// call difference method

diff = difference(start, stop);

System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds);

System.out.printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds);

System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);


}

public static Time difference(Time start, Time stop)

Time diff = new Time(0, 0, 0);

// if start second is greater

// convert minute of stop into seconds

// and add seconds to stop second

if(start.seconds > stop.seconds){

--stop.minutes;

stop.seconds += 60;

diff.seconds = stop.seconds - start.seconds;

// if start minute is greater

// convert stop hour into minutes

// and add minutes to stop minutes

if(start.minutes > stop.minutes){

--stop.hours;

stop.minutes += 60;

diff.minutes = stop.minutes - start.minutes;

diff.hours = stop.hours - start.hours;

// return the difference time

return(diff);

}
}

Output

TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40

In the above program, we've created a class named Time with three member variables: hours, minutes, and
seconds. As the name suggests, they store hours, minutes and seconds of a given time respectively.

The Time class has a constructor that initializes the value of hours, minutes, and seconds.

We've also created a static function difference that takes two Time variables as parameters, find the difference
and returns it as Time class.

54. Java Program to Remove All Whitespaces from a String


In this program, you'll learn to remove all whitespaces in a given string using regular expressions in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Basic Input and Output

Example 1: Program to Remove All Whitespaces

public class Whitespaces {

public static void main(String[] args) {

String sentence = "T his is b ett er.";

System.out.println("Original sentence: " + sentence);

sentence = sentence.replaceAll("\\s", "");

System.out.println("After replacement: " + sentence);

}
Output

Original sentence: T his is b ett er.

After replacement: Thisisbetter.

In the aboe program, we use String's replaceAll() method to remove and replace all whitespaces in the string
sentence.

To learn more, visit Java String replaceAll().

We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in
the string. Then, we replace it with "" (empty string literal).

Example 2: Take string from users and remove the white space

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 the string");

// take the input

String input = sc.nextLine();

System.out.println("Original String: " + input);

// remove white spaces

input = input.replaceAll("\\s", "");

System.out.println("Final String: " + input);

sc.close();
}

Output

Enter the string

J av a- P rog ram m ing

Original String: J av a- P rog ram m ing

Final String: Java-Programming

In the above example, we have used the Java Scanner to take input from the user.

Here, the replaceAll() method replaces all the white spaces from the string.

55. Java Program to Determine the class of an object


In this example, we will learn to determine the class of an object in Java using the getClass() method, instanceof
operator, and the isInstance() method.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java instanceof

Example 1: Check the class of an object using getClass()

class Test1 {

// first class

class Test2 {

// second class

}
class Main {

public static void main(String[] args) {

// create objects

Test1 obj1 = new Test1();

Test2 obj2 = new Test2();

// get the class of the object obj1

System.out.print("The class of obj1 is: ");

System.out.println(obj1.getClass());

// get the class of the object obj2

System.out.print("The class of obj2 is: ");

System.out.println(obj2.getClass());

Output

The class of obj1 is: class Test1

The class of obj2 is: class Test2

In the above example, we have used the getClass() method of the Object class to get the class name of the
objects obj1 and obj2.

To learn more, visit Java Object getClass().

Example 2: Check the class of an object using instanceOf operator

class Test {

// class

class Main {

public static void main(String[] args) {


// create an object

Test obj = new Test();

// check if obj is an object of Test

if(obj instanceof Test) {

System.out.println("obj is an object of the Test class");

else {

System.out.println("obj is not an object of the Test class");

Output

obj is an object of the Test class

In the above example, we have used the instanceof operator to check if the object obj is an instance of the class
Test.

Example 3: Check the class of an object using isInstance()

class Test {

// first class

class Main {

public static void main(String[] args) {

// create an object

Test obj = new Test();


// check if obj is an object of Test1

if(Test.class.isInstance(obj)){

System.out.println("obj is an object of the Test class");

else {

System.out.println("obj is not an object of the Test class");

Output

obj is an object of the Test class

Here, we have used the isInstance() method of the class Class to check if the object obj is an object of the class
Test.

The isInstance() method works similarly to the instanceof operator. However, it is preferred during the run time.

56. Java Program to Create an enum class


In this example, we will learn to create an enum class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java enums

Java Class and Objects

Example 1: Java program to create an enum class

enum Size{

// enum constants

SMALL, MEDIUM, LARGE, EXTRALARGE;


public String getSize() {

// this will refer to the object SMALL

switch(this) {

case SMALL:

return "small";

case MEDIUM:

return "medium";

case LARGE:

return "large";

case EXTRALARGE:

return "extra large";

default:

return null;

public static void main(String[] args) {

// call the method getSize()

// using the object SMALL

System.out.println("The size of Pizza I get is " + Size.SMALL.getSize());

// call the method getSize()

// using the object LARGE

System.out.println("The size of Pizza I want is " + Size.LARGE.getSize());


}

Output

The size of Pizza I get is small

The size of Pizza I want is large

In the above example, we have created an enum class named Size. The class contains four constants SMALL,
MEDIUM, LARGE, and EXTRALARGE.

Here, the compiler automatically converts all the constants of the enum into its instances. Hence, we can call the
method using the constant as objects.

Size.SMALL.getSize()

In this call, the this keyword is now associated with the SMALL object. Hence, the value small is returned.

57. Java Program to Print object of a class


In this tutorial, we will learn to print the object of a class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Example 1: Java program to print the object

class Test {

class Main {

public static void main(String[] args) {

// create an object of the Test class

Test obj = new Test();


// print the object

System.out.println(obj);

Output

Test@512ddf17

In the above example, we have created an object of the class Test. When we print the object, we can see that
the output looks different.

This is because while printing the object, the toString() method of the object class is called. It formats the object
in the default format. That is,

Test - name of the class

@ - joins the string

512ddf17 - hashcode value of the object

If we want to format the output in our own way, we need to override the toString() method inside the class. For
example,

class Test {

@Override

public String toString() {

return "object";

class Main {

public static void main(String[] args) {


// create an object of the Test class

Test obj = new Test();

// print the object

System.out.println(obj);

Output

object

In the above example, the output has changed. It is because here we override the toString() method to return
the string object.

To learn about toString() method of the object class, visit Java Object toString().

First Line

Second Line

Third Line

So, we will get output

Total Number of Lines: 3

Example 2: Java program to count the number of lines in a file using java.nio.file package

import java.nio.file.*;

class Main {

public static void main(String[] args) {

try {

// make a connection to the file

Path file = Paths.get("input.txt");


// read all lines of the file

long count = Files.lines(file).count();

System.out.println("Total Lines: " + count);

} catch (Exception e) {

e.getStackTrace();

In the above example,

lines() - read all lines of the file as a stream

count() - returns the number of elements in the stream

Here, if the file input.txt contains the following content:

This is the article on Java Examples.

The examples count number of lines in a file.

Here, we have used the java.nio.file package.

The program will print Total Lines: 3.

58. Java Program to Create custom exception


In this example, we will learn to create custom checked and unchecked exception in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Exceptions

Java Exception Handling

Java Class and Objects

Example 1: Java program to create custom checked exception

import java.util.ArrayList;
import java.util.Arrays;

// create a checked exception class

class CustomException extends Exception {

public CustomException(String message) {

// call the constructor of Exception class

super(message);

class Main {

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

// check the exception condition

public void checkLanguage(String language) throws CustomException {

// throw exception if language already present in ArrayList

if(languages.contains(language)) {

throw new CustomException(language + " already exists");

else {

// insert language to ArrayList

languages.add(language);

System.out.println(language + " is added to the ArrayList");

public static void main(String[] args) {


// create object of Main class

Main obj = new Main();

// exception is handled using try...catch

try {

obj.checkLanguage("Swift");

obj.checkLanguage("Java");

catch(CustomException e) {

System.out.println("[" + e + "] Exception Occured");

Output

Swift is added to the ArrayList

[CustomException: Java already exists] Exception Occured

In the above example, we have extended the Exception class to create a custom exception named
CustomException. Here, we call the constructor of Exception class from the CustomException class using super()
keyword.

Inside the method checkLanguage(), we have checked the exception condition, and if the exception occurs, the
try..catch block handles the exception.

Here, this is the checked exception. We can also create unchecked exception class in Java. To learn more on
checked and unchecked exception, visit Java Exception.

Example 2: Create custom unchecked exception class

import java.util.ArrayList;

import java.util.Arrays;
// create a unchecked exception class

class CustomException extends RuntimeException {

public CustomException(String message) {

// call the constructor of RuntimeException

super(message);

class Main {

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

// check the exception condition

public void checkLanguage(String language) {

// throw exception if language already present in ArrayList

if(languages.contains(language)) {

throw new CustomException(language + " already exists");

else {

// insert language to ArrayList

languages.add(language);

System.out.println(language + " is added to the ArrayList");

public static void main(String[] args) {

// create object of Main class


Main obj = new Main();

// check if language already present

obj.checkLanguage("Swift");

obj.checkLanguage("Java");

Output

Swift is added to the ArrayList

Exception in thread "main" CustomException: Java already exists

at Main.checkLanguage(Main.java:21)

at Main.main(Main.java:37)

In the above example, we have extended the RuntimeException class to create an unchecked custom exception
class.

Here, you can notice that, we haven't declared any try...catch block. It is because the unchecked exception is
checked at runtime.

Besides that, other functionality of unchecked exception is similar to the above mentioned program.

59. Java Program to Create a immutable class


In this example, we will learn to create an immutable class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java program to create immutable class

final class Immutable {


private String name;

private int date;

Immutable(String name, int date) {

// initialize the immutable variables

this.name = name;

this.date = date;

// private getter methods

public String getName() {

return name;

public int getDate() {

return date;

class Main {

public static void main(String[] args) {

// create object of Immutable

Immutable obj = new Immutable("Programiz", 2011);

System.out.println("Name: " + obj.getName());

System.out.println("Date: " + obj.getDate());

}
Output

Name: Programiz

Date: 2011

In Java, immutable classes are those classes whose values are not changed. To create an immutable class, here

class is declared final so it cannot be extended

class members name and date are private so cannot be accessed outside of class

does not contain any setter methods so outer class cannot change the class members

getter method returns the copy of class members

class members are initialized using the constructor

60. Java Program to Convert String to Date


In this program, you'll learn to convert string to date in Java using formatter.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Basic Input and Output

Example 1: Convert String to Date using predefined formatters

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 = "2017-07-25";

LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);


System.out.println(date);

Output

2017-07-25

In the above program, we've used the predefined formatter ISO_DATE that takes date string in the format 2017-
07-25 or 2017-07-25+05:45'.

The LocalDate's parse() function parses the given string using the given formatter. You can also remove the
ISO_DATE formatter in the above example and replace the parse() method with:

LocalDate date = LocalDate.parse(string, DateTimeFormatter);

Example 2: Convert String to Date using pattern formatters

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

import java.util.Locale;

public class TimeString {

public static void main(String[] args) {

String string = "July 25, 2017";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);

LocalDate date = LocalDate.parse(string, formatter);

System.out.println(date);

Output
2017-07-25

In the above program, our date is in the format MMMM d, yyyy. So, we create a formatter of the given pattern.
Check all DateTimeFormatter patterns, if you're interested.

Now, we can parse the date using LocalDate.parse() function and get the LocalDate object.

61. Java Program to Convert a Stack Trace to a String


In this program, you'll learn to convert a stack trace to a string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Exception Handling

Example: Convert stack trace to a string

import java.io.PrintWriter;

import java.io.StringWriter;

public class PrintStackTrace {

public static void main(String[] args) {

try {

int division = 0 / 0;

} catch (ArithmeticException e) {

StringWriter sw = new StringWriter();

e.printStackTrace(new PrintWriter(sw));

String exceptionAsString = sw.toString();

System.out.println(exceptionAsString);

}
}

Output

java.lang.ArithmeticException: / by zero

at PrintStackTrace.main(PrintStackTrace.java:9)

In the above program, we've forced our program to throw ArithmeticException by dividing 0 by 0.

In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the
stack trace using printStackTrace() method of the exception and write it in the writer.

Then, we simply convert it to string using toString() method.

62. Java Program to Compare Strings


In this program, you'll learn to compare two strings in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Operators

Example 1: Compare two strings

public class CompareStrings {

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");

Output

Equal

In the above program, we've two strings style and style2. We simply use the equal to operator (==) to compare
the two strings, which compares the value Bold to Bold and prints Equal.

Example 2: Compare two strings using equals()

public class CompareStrings {

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");

Output

Equal

In the above program, we have two strings named style and style2 both containing the same world Bold.

However, we've used String constructor to create the strings. To compare these strings in Java, we need to use
the equals() method of the string.
You should not use == (equality operator) to compare these strings because they compare the reference of the
string, i.e. whether they are the same object or not.

On the other hand, equals() method compares whether the value of the strings is equal, and not the object
itself.

If you instead change the program to use equality operator, you'll get Not Equal as shown in the program below.

Example 3: Compare two string objects using == (Doesn't work)

public class CompareStrings {

public static void main(String[] args) {

String style = new String("Bold");

String style2 = new String("Bold");

if(style == style2)

System.out.println("Equal");

else

System.out.println("Not Equal");

Output

Not Equal

Example 4: Different ways to compare two strings

Here is the string comparison which is possible in Java.

public class CompareStrings {


public static void main(String[] args) {

String style = new String("Bold");

String style2 = new String("Bold");

boolean result = style.equals("Bold"); // true

System.out.println(result);

result = style2 == "Bold"; // false

System.out.println(result);

result = style == style2; // false

System.out.println(result);

result = "Bold" == "Bold"; // true

System.out.println(result);

Output

true

false

false

true

63. Java Program to Check if a String is Numeric


In this program, you'll learn different techniques to check if a string is numeric or not in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java String

Java Exception Handling

Example 1: Check if a string is numeric

public class Numeric {

public static void main(String[] args) {

String string = "12345.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");

Output

12345.15 is a number

In the above program, we have a String named string that contains the string to be checked. We also have a
boolean value numeric which stores if the final result is numeric or not.

To check if the string contains numbers only, in the try block, we use Double's parseDouble() method to convert
the string to a Double.
If it throws an error (i.e. NumberFormatException error), it means the string isn't a number and numeric is set to
false. Else, it's a number.

However, if you want to check if for a number of strings, you would need to change it to a function. And, the
logic is based on throwing exceptions, this can be pretty expensive.

Instead, we can use the power of regular expressions to check if the string is numeric or not as shown below.

Example 2: Check if a string is numeric or not using regular expressions (regex)

public class Numeric {

public static void main(String[] args) {

String string = "-1234.15";

boolean numeric = true;

numeric = string.matches("-?\\d+(\\.\\d+)?");

if(numeric)

System.out.println(string + " is a number");

else

System.out.println(string + " is not a number");

Output

-1234.15 is a number

In the above program, instead of using a try-catch block, we use regex to check if string is numeric or not. This is
done using String's matches() method.
In the matches() method,

-? allows zero or more - for negative numbers in the string.

\\d+ checks the string must have at least 1 or more numbers (\\d).

(\\.\\d+)? allows zero or more of the given pattern (\\.\\d+) in which

\\. checks if the string contains . (decimal points) or not

If yes, it should be followed by at least one or more number \\d+.

64. Java Program to Check if two strings are anagram


In this example, we will check if two strings are anagram or not in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Arrays

Two strings are said to be anagram, if we can form one string by arranging the characters of another string. For
example, Race and Care. Here, we can form Race by arranging the characters of Care.

Example 1: Java program to check if two strings are anagram

import java.util.Arrays;

class Main {

public static void main(String[] args) {

String str1 = "Java";

String str2 = "Vaaj";

// check if length is same

if(str1.length() == str2.length()) {
// convert strings to char array

char[] charArray1 = str1.toCharArray();

char[] charArray2 = str2.toCharArray();

// sort the char array

Arrays.sort(charArray1);

Arrays.sort(charArray2);

// if sorted char arrays are same

// then the string is anagram

boolean result = Arrays.equals(charArray1, charArray2);

if(result) {

System.out.println(str1 + " and " + str2 + " are anagram.");

else {

System.out.println(str1 + " and " + str2 + " are anagram.");

Output

Java and Vaaj are anagram.

In Java, we have two strings named str1 and str2. Here, we are checking if str1 and str2 are anagram.

Here,

str1.toCharArray() - converts the string into a char array


Arrays.sort() - sorts both the char arrays

Arrays.equal() - checks if the sorted char array are equal

If sorted arrays are equal, then the strings are anagram.

Example 2: Take string inputs from users and check if the strings are anagram

import java.util.Arrays;

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// create an object of Scanner class

Scanner input = new Scanner(System.in);

// take input from users

System.out.print("Enter first String: ");

String str1 = input.nextLine();

System.out.print("Enter second String: ");

String str2 = input.nextLine();

// check if length is same

if(str1.length() == str2.length()) {

// convert strings to char array

char[] charArray1 = str1.toCharArray();

char[] charArray2 = str2.toCharArray();

// sort the char array

Arrays.sort(charArray1);

Arrays.sort(charArray2);
// if sorted char arrays are same

// then the string is anagram

boolean result = Arrays.equals(charArray1, charArray2);

if(result) {

System.out.println(str1 + " and " + str2 + " are anagram.");

else {

System.out.println(str1 + " and " + str2 + " are anagram.");

input.close();

Output

Enter first String: Race

Enter second String: Care

Race and Care are anagram.

In the above example, we have used the Scanner class to take input from the user. Here, we checked if the
strings provided by users are anagram.

65. Java Program to Compute all the permutations of the string


In this example, we will learn to compute all the permutations of the string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Recursion
Java Scanner Class

Permutation of the string means all the possible new strings that can be formed by interchanging the position of
the characters of the string. For example, string ABC has permutations [ABC, ACB, BAC, BCA, CAB, CBA].

Example: Java program to get all the permutation of a string

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

class Main {

public static Set<String> getPermutation(String str) {

// create a set to avoid duplicate permutation

Set<String> permutations = new HashSet<String>();

// check if string is null

if (str == null) {

return null;

} else if (str.length() == 0) {

// terminating condition for recursion

permutations.add("");

return permutations;

// get the first character

char first = str.charAt(0);

// get the remaining substring

String sub = str.substring(1);

// make recursive call to getPermutation()


Set<String> words = getPermutation(sub);

// access each element from words

for (String strNew : words) {

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

// insert the permutation to the set

permutations.add(strNew.substring(0, i) + first + strNew.substring(i));

return permutations;

public static void main(String[] args) {

// create an object of scanner class

Scanner input = new Scanner(System.in);

// take input from users

System.out.print("Enter the string: ");

String data = input.nextLine();

System.out.println("Permutations of " + data + ": \n" + getPermutation(data));

Output

Enter the string: ABC

Permutations of ABC:

[ACB, BCA, ABC, CBA, BAC, CAB]

In Java, we have used the recursion to compute all the permutations of a string. Here, we store the permutation
in a set. So, there will be no duplicate permutation.
66. Java Program to Create random strings
In this example, we will learn to generate a random string and an alphanumeric random string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java for Loop

Java String charAt()

Example 1: Java program to generate a random string

import java.util.Random;

class Main {

public static void main(String[] args) {

// create a string of all characters

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// create random string builder

StringBuilder sb = new StringBuilder();

// create an object of Random class

Random random = new Random();

// specify length of random string

int length = 7;

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

// generate random index number


int index = random.nextInt(alphabet.length());

// get character specified by index

// from the string

char randomChar = alphabet.charAt(index);

// append the character to string builder

sb.append(randomChar);

String randomString = sb.toString();

System.out.println("Random String is: " + randomString);

Output

Random String is: IIYOBRK

In the above example, we have first created a string containing all the alphabets. Next, we have generated a
random index number using the nextInt() method of the Random class.

Using the random index number, we have generated the random character from the string alphabet. We then
used the StringBuilder class to append all the characters together.

If we want to change the random string into lower case, we can use the toLowerCase() method of the String.

randomString.toLowerCase()

Note: The output will be different every time you run the program.

Example 2: Java Program to generate a random alphanumeric string


import java.util.Random;

class Main {

public static void main(String[] args) {

// create a string of uppercase and lowercase characters and numbers

String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";

String numbers = "0123456789";

// combine all strings

String alphaNumeric = upperAlphabet + lowerAlphabet + numbers;

// create random string builder

StringBuilder sb = new StringBuilder();

// create an object of Random class

Random random = new Random();

// specify length of random string

int length = 10;

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

// generate random index number

int index = random.nextInt(alphaNumeric.length());

// get character specified by index

// from the string

char randomChar = alphaNumeric.charAt(index);


// append the character to string builder

sb.append(randomChar);

String randomString = sb.toString();

System.out.println("Random String is: " + randomString);

Output

Random Alphanumeric String is: pxg1Uzz9Ju

Here, we have created a string that contains numbers from 0 to 9 and the alphabets in uppercase and
lowercase.

From the string, we have randomly generated an alphanumeric string of length 10.

67. Java Program to Clear the StringBuffer


In this example, we will learn to clear the string buffer using the delete() and setLength() method and creating a
new StringBuffer object in Java.

Example 1: Java program to clear using StringBuffer using delete()

class Main {

public static void main(String[] args) {

// create a string buffer

StringBuffer str = new StringBuffer();

// add string to string buffer

str.append("Java");

str.append(" is");
str.append(" popular.");

System.out.println("StringBuffer: " + str);

// clear the string

// using delete()

str.delete(0, str.length());

System.out.println("Updated StringBuffer: " + str);

Output

StringBuffer: Java is popular.

Updated StringBuffer:

In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer.

Here, the delete() method removes all the characters within the specified index numbers.

Example 2: Clear the StringBuffer using setLength()

class Main {

public static void main(String[] args) {

// create a string buffer

StringBuffer str = new StringBuffer();

// add string to string buffer

str.append("Java");

str.append(" is");

str.append(" awesome.");

System.out.println("StringBuffer: " + str);


// clear the string

// using setLength()

str.setLength(0);

System.out.println("Updated StringBuffer: " + str);

Output

StringBuffer: Java is awesome.

Updated StringBuffer

Here, the setLength() method changes the character sequences present in StringBuffer to a new character
sequence. And, set the length of the new character sequence to 0.

Hence, the older character sequence is garbage collected.

Note: The setLength() method completely ignores the character sequence present in the string buffer. However,
the delete() method accesses the character sequence and deletes it. Hence, setLength() is more faster than
delete().

Example 3: Clear the StringBuffer by creating a new object

class Main {

public static void main(String[] args) {

// create a string buffer

StringBuffer str = new StringBuffer();

// add string to string buffer

str.append("Java");

str.append(" is");

str.append(" awesome.");
System.out.println("StringBuffer: " + str);

// clear the string

// using new

// here new object is created and assigned to str

str = new StringBuffer();

System.out.println("Updated StringBuffer: " + str);

Output

StringBuffer: Java is awesome.

Updated StringBuffer:

Here, new StringBuffer() creates a new string buffer object and assigns the previous variable to the new objects.
In this case, the previous object will be there. But it won't be accessible so it will be garbage collected.

Since, every time instead of clearing the previous string buffer, a new string buffer is created. So it is less
efficient in terms of performance.

68. Java Program to Capitalize the first character of each word in a String
In this example, we will learn to convert the first letter of a string into the uppercase in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java String toUpperCase()

Example 1: Java program to make the first letter of a String capital

class Main {

public static void main(String[] args) {

// create a string
String name = "programiz";

// create two substrings from name

// first substring contains first letter of name

// second substring contains remaining letters

String firstLetter = name.substring(0, 1);

String remainingLetters = name.substring(1, name.length());

// change the first letter to uppercase

firstLetter = firstLetter.toUpperCase();

// join the two substrings

name = firstLetter + remainingLetters;

System.out.println("Name: " + name);

Output

Name: Programiz

In the example, we have converted the first letter of the string name to upper case.

Example 2: Convert every word of a String to uppercase

class Main {

public static void main(String[] args) {

// create a string

String message = "everyone loves java";


// stores each characters to a char array

char[] charArray = message.toCharArray();

boolean foundSpace = true;

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

// if the array element is a letter

if(Character.isLetter(charArray[i])) {

// check space is present before the letter

if(foundSpace) {

// change the letter into uppercase

charArray[i] = Character.toUpperCase(charArray[i]);

foundSpace = false;

else {

// if the new character is not character

foundSpace = true;

// convert the char array to the string

message = String.valueOf(charArray);

System.out.println("Message: " + message);

Output
Message: Everyone Loves Java

Here,

we have created a string named message

we converted the string into a char array

we access every element of the char array

if the element is a white space, we convert the next element into uppercase

69. Java Program to Iterate through each characters of the string.


In this tutorial, we will learn to iterate through each characters of the string.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java for Loop

Java for-each Loop

Example 1: Loop through each character of a string using for loop

class Main {

public static void main(String[] args) {

// create a string

String name = "Programiz";

System.out.println("Characters in " + name + " are:");

// loop through each element

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

// access each character


char a = name.charAt(i);

System.out.print(a + ", ");

Output

Characters in Programiz are:

P, r, o, g, r, a, m, i, z,

In the above example, we have used the for-loop to access each element of the string. Here, we have used the
charAt() method to access each character of the string.

Example 2: Loop through each character of a string using for-each loop

class Main {

public static void main(String[] args) {

// create a string

String name = "Programiz";

System.out.println("Characters in string \"" + name + "\":");

// loop through each element using for-each loop

for(char c : name.toCharArray()) {

// access each character

System.out.print(c + ", ");

}
}

Output

Characters in string "Programiz":

P, r, o, g, r, a, m, i, z,

In the above example, we have converted the string into a char array using the toCharArray(). We then access
each element of the char array using the for-each loop.

70. Java Program to Display Factors of a Number


In this program, you'll learn to display all factors of a given number using for loop in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java if, if...else Statement

Example: Factors of a Positive Integer

public class Factors {

public static void main(String[] args) {

int number = 60;

System.out.print("Factors of " + number + " are: ");

for(int i = 1; i <= number; ++i) {

if (number % i == 0) {

System.out.print(i + " ");

Output
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

In the above program, number whose factors are to be found is stored in the variable number (60).

The for loop is iterated until i <= number is false. In each iteration, whether number is exactly divisible by i is
checked (condition for i to be the factor of number) and the value of i is

incremented by 1.

71. Java Program to Make a Simple Calculator Using switch...case


In this program, you'll learn to make a simple calculator using switch..case in Java. This calculator would be able
to add, subtract, multiply and divide two numbers.

To understand this example, you should have the knowledge of the following Java programming topics:

Java switch Statement

Java Scanner Class

Example: Simple Calculator using switch Statement

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter two numbers: ");

// nextDouble() reads the next double from the keyboard

double first = reader.nextDouble();

double second = reader.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");

char operator = reader.next().charAt(0);


double result;

switch(operator)

case '+':

result = first + second;

break;

case '-':

result = first - second;

break;

case '*':

result = first * second;

break;

case '/':

result = first / second;

break;

// operator doesn't match any case constant (+, -, *, /)

default:

System.out.printf("Error! operator is not correct");

return;

System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);

Output
Enter two numbers: 1.5

4.5

Enter an operator (+, -, *, /): *

1.5 * 4.5 = 6.8

The * operator entered by the user is stored in the operator variable using the next() method of Scanner object.

Likewise, the two operands, 1.5 and 4.5 are stored in variables first and second respectively using the
nextDouble() method of Scanner object.

Since the operator * matches the when condition '*':, the control of the program jumps to

result = first * second;

This statement calculates the product and stores in the variable result and the break; the statement ends the
switch statement.

Finally, the printf statement is executed.

Note: We have used the printf() method instead of println. This is because here we are printing the formatted
string. To learn more, visit the Java printf() method.

72. Java Code To Create Pyramid and Pattern


In this program, you'll learn to create pyramid, half pyramid, inverted pyramid, Pascal's triangle and Floyd's
triangle sing control statements in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java for Loop

Java if, if...else Statement

Java while and do...while Loop

List of Source Code

Code to print triangles using *, digits and characters


Code to print inverted triangles using * and digits

Code to print full pyramids

Code to print Pascal's triangle

Code to print Floyd's triangle

Programs to print triangles using *, numbers and characters

Example 1: Program to print half pyramid using *

**

***

****

*****

Source code

public class Pattern {

public static void main(String[] args) {

int rows = 5;

for(int i = 1; i <= rows; ++i) {

for(int j = 1; j <= i; ++j) {

System.out.print("* ");

System.out.println();

Example 2: Program to print half pyramid a using numbers

12

123
1234

12345

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 5;

for(int i = 1; i <= rows; ++i) {

for(int j = 1; j <= i; ++j) {

System.out.print(j + " ");

System.out.println();

Example 3: Program to print half pyramid using alphabets

BB

CCC

DDDD

EEEEE

Source Code

public class Pattern {

public static void main(String[] args) {

char last = 'E', alphabet = 'A';


for(int i = 1; i <= (last-'A'+1); ++i) {

for(int j = 1; j <= i; ++j) {

System.out.print(alphabet + " ");

++alphabet;

System.out.println();

Programs to print inverted half pyramid using * and numbers

Example 4: Inverted half pyramid using *

*****

****

***

**

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 5;

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

for(int j = 1; j <= i; ++j) {

System.out.print("* ");

System.out.println();

}
}

Example 5: Inverted half pyramid using numbers

12345

1234

123

12

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 5;

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

for(int j = 1; j <= i; ++j) {

System.out.print(j + " ");

System.out.println();

Programs to display pyramid and inverted pyramid using * and digits

Example 6: Program to print full pyramid using *

***

*****

*******

*********
Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 5, k = 0;

for(int i = 1; i <= rows; ++i, k = 0) {

for(int space = 1; space <= rows - i; ++space) {

System.out.print(" ");

while(k != 2 * i - 1) {

System.out.print("* ");

++k;

System.out.println();

Example 7: Program to print pyramid using numbers

232

34543

4567654

567898765

Source Code
public class Pattern {

public static void main(String[] args) {

int rows = 5, k = 0, count = 0, count1 = 0;

for(int i = 1; i <= rows; ++i) {

for(int space = 1; space <= rows - i; ++space) {

System.out.print(" ");

++count;

while(k != 2 * i - 1) {

if (count <= rows - 1) {

System.out.print((i + k) + " ");

++count;

else {

++count1;

System.out.print((i + k - 2 * count1) + " ");

++k;

count1 = count = k = 0;

System.out.println();

}
Example 8: Inverted full pyramid using *

*********

*******

*****

***

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 5;

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

for(int space = 1; space <= rows - i; ++space) {

System.out.print(" ");

for(int j=i; j <= 2 * i - 1; ++j) {

System.out.print("* ");

for(int j = 0; j < i - 1; ++j) {

System.out.print("* ");

System.out.println();

}
}

Example 9: Print Pascal's triangle

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 6, coef = 1;

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

for(int space = 1; space < rows - i; ++space) {

System.out.print(" ");

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

if (j == 0 || i == 0)

coef = 1;

else

coef = coef * (i - j + 1) / j;

System.out.printf("%4d", coef);

System.out.println();
}

Example 10: Print Floyd's Triangle.

23

456

7 8 9 10

Source Code

public class Pattern {

public static void main(String[] args) {

int rows = 4, number = 1;

for(int i = 1; i <= rows; i++) {

for(int j = 1; j <= i; j++) {

System.out.print(number + " ");

++number;

System.out.println();

73. Java Program to Round a Number to n Decimal Places


In this program, you'll learn to round a given number to n decimal places in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types

Java Basic Input and Output

Example 1: Round a Number using format

public class Decimal {

public static void main(String[] args) {

double num = 1.34567;

System.out.format("%.4f", num);

Output

1.3457

In the above program, we've used the format() method to print the given floating-point number num to 4
decimal places. The 4 decimal places are given by the format .4f.

This means, print only up to 4 places after the dot (decimal places), and f means to print the floating-point
number.

Example 2: Round a Number using DecimalFormat

import java.math.RoundingMode;

import java.text.DecimalFormat;

public class Decimal {

public static void main(String[] args) {

double num = 1.34567;

DecimalFormat df = new DecimalFormat("#.###");


df.setRoundingMode(RoundingMode.CEILING);

System.out.println(df.format(num));

Output

1.346

In the above program, we've used DecimalFormat class to round a given number num.

We declare the format using the # patterns #.###. This means we want num up to 3 decimal places. We also set
the rounding mode to Ceiling, this causes the last given place to be rounded to its

next number.

So, 1.34567 rounded to 3 decimal places prints 1.346, 6 is the next number for 3rd place decimal 5.

74. Java Program to Convert Character to String and Vice-Versa


In this program, you'll learn to convert a character (char) to a string and vice-versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Variables and (Primitive) Data Types

Java Arrays

Example 1: Convert char to String

public class CharString {

public static void main(String[] args) {

char ch = 'c';

String st = Character.toString(ch);

// Alternatively
// st = String.valueOf(ch);

System.out.println("The string is: " + st);

Output

The string is: c

In the above program, we have a character stored in the variable ch. We use the Character class's toString()
method to convert character to the string st.

Alternatively, we can also use String's valueOf() method for conversion. However, both internally are the same.

Example 2: Convert char array to String

If you have a char array instead of just a char, we can easily convert it to String using String methods as follows:

public class CharString {

public static void main(String[] args) {

char[] ch = {'a', 'e', 'i', 'o', 'u'};

String st = String.valueOf(ch);

String st2 = new String(ch);

System.out.println(st);

System.out.println(st2);

Output

aeiou
aeiou

In the above program, we have a char array ch containing vowels. We use String's valueOf() method again to
convert the character array to String.

We can also use the String constructor which takes character array ch as the parameter for conversion.

Example 3: Convert String to char array

We can also convert a string to char array (but not char) using String's method toCharArray().

import java.util.Arrays;

public class StringChar {

public static void main(String[] args) {

String st = "This is great";

char[] chars = st.toCharArray();

System.out.println(Arrays.toString(chars));

Output

[T, h, i, s, , i, s, , g, r, e, a, t]

In the above program, we have a string stored in the variable st. We use String's toCharArray() method to
convert the string to an array of characters stored in chars.

We then, use Arrays's toString() method to print the elements of chars in an array-like form.

75. Java Program to Check if a String is Empty or Null


In this program, you'll learn to check if a string is empty or null using if-else statement and functions in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Methods

Example 1: Check if String is Empty or Null

public class Null {

public static void main(String[] args) {

String str1 = null;

String str2 = "";

if(isNullOrEmpty(str1))

System.out.println("First string is null or empty.");

else

System.out.println("First string is not null or empty.");

if(isNullOrEmpty(str2))

System.out.println("Second string is null or empty.");

else

System.out.println("Second string is not null or empty.");

public static boolean isNullOrEmpty(String str) {

if(str != null && !str.isEmpty())

return false;

return true;

Output
str1 is null or empty.

str2 is null or empty.

In the above program, we've two strings str1 and str2. str1 contains null value and str2 is an empty string.

We've also created a function isNullOrEmpty() which checks, as the name suggests, whether the string is null or
empty. It checks it using a null check using != null and isEmpty() method of string.

In plain terms, if a string isn't a null and isEmpty() returns false, it's not either null or empty. Else, it is.

However, the above program doesn't return empty if a string contains only whitespace characters (spaces).
Technically, isEmpty() sees it contains spaces and returns false. For string with spaces,

we use the string method trim() to trim out all the leading and trailing whitespace characters.

Example 2: Check if String with spaces is Empty or Null

public class Null {

public static void main(String[] args) {

String str1 = null;

String str2 = " ";

if(isNullOrEmpty(str1))

System.out.println("str1 is null or empty.");

else

System.out.println("str1 is not null or empty.");

if(isNullOrEmpty(str2))

System.out.println("str2 is null or empty.");

else

System.out.println("str2 is not null or empty.");


}

public static boolean isNullOrEmpty(String str) {

if(str != null && !str.trim().isEmpty())

return false;

return true;

Output

str1 is null or empty.

str2 is null or empty.

Here in the isNullorEmpty(), we've added an extra method trim() which removes all leading and trailing
whitespace characters in the given string.

So, now if a string contains spaces only, the function returns true.

76. Java Program to Get Current Date/Time


In this program, you'll learn to get the current date and time in different formats in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Basic Input and Output

Example 1: Get Current date and time in default format

import java.time.LocalDateTime;

public class CurrentDateTime {

public static void main(String[] args) {

LocalDateTime current = LocalDateTime.now();


System.out.println("Current Date and Time is: " + current);

Output

Current Date and Time is: 2017-08-02T11:25:44.973

In the above program, the current date and time is stored in variable current using LocalDateTime.now()
method.

For default format, it is simply converted from a LocalDateTime object to a string internally using a toString()
method.

Example 2: Get Current date and time with pattern

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class CurrentDateTime {

public static void main(String[] args) {

LocalDateTime current = LocalDateTime.now();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

String formatted = current.format(formatter);

System.out.println("Current Date and Time is: " + formatted);

Output

Current Date and Time is: 2017-08-02 11:29:57.401


In the above program, we've defined a pattern of format Year-Month-Day Hours:Minutes:Seconds.Milliseconds
using a DateTimeFormatter object.

Then, we've used LocalDateTime's format() method to use the given formatter. This gets us the formatted string
output.

Example 3: Get Current Date time using predefined constants

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class CurrentDateTime {

public static void main(String[] args) {

LocalDateTime current = LocalDateTime.now();

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;

String formatted = current.format(formatter);

System.out.println("Current Date is: " + formatted);

Output

Current Date is: 20170802

In the above program, we've used a predefined format constant BASIC_ISO_DATE to get the current ISO date as
the output.

Example 4: Get Current Date time in localized style

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class CurrentDateTime {

public static void main(String[] args) {

LocalDateTime current = LocalDateTime.now();

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);

String formatted = current.format(formatter);

System.out.println("Current Date is: " + formatted);

Output

Current Date is: Aug 2, 2017 11:44:19 AM

In the above program, we've used a Localized style Medium to get the current date-time in the given format.
There are other styles as well: Full, Long and Short.

If you're interested, here's a list of all DateTimeFormatter patterns.

77. Java Program to Convert Milliseconds to Minutes and Seconds


In the above program, you'll learn to convert milliseconds to minutes and seconds individually, and together in
Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Basic Input and Output

Example 1: Convert milliseconds to minutes and seconds individually

import java.util.concurrent.TimeUnit;
public class Milliseconds {

public static void main(String[] args) {

long milliseconds = 1000000;

// long minutes = (milliseconds / 1000) / 60;

long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);

// long seconds = (milliseconds / 1000);

long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);

System.out.format("%d Milliseconds = %d minutes\n", milliseconds, minutes );

System.out.println("Or");

System.out.format("%d Milliseconds = %d seconds", milliseconds, seconds );

Output

1000000 Milliseconds = 16 minutes

Or

1000000 Milliseconds = 1000 seconds

In the above program, we've converted given milliseconds to minutes using toMinutes() method. Likewise, we
used toSeconds() method to convert it to seconds.

We can also use basic math to convert it to minutes and seconds.

Seconds = Milliseconds / 1000

while minutes is
Minutes = Seconds / 60

or

Minutes = (Milliseconds / 1000) / 60

Example 2: Convert Milliseconds to Minutes and Seconds

public class Milliseconds {

public static void main(String[] args) {

long milliseconds = 1000000;

long minutes = (milliseconds / 1000) / 60;

long seconds = (milliseconds / 1000) % 60;

System.out.format("%d Milliseconds = %d minutes and %d seconds.", milliseconds, minutes, seconds);

Output

1000000 Milliseconds = 16 minutes and 40 seconds.

In the above program, we've used formula:

Minutes = (Milliseconds / 1000) / 60

And

Remaining Seconds = (Milliseconds / 1000) % 60

First, we calculate the minutes by simply dividing it to seconds and then to minutes by dividing it with 60.

Then, we calculate the remaining seconds by dividing it to seconds and getting the remainder when divided by
60.

78. Java Program to Add Two Dates


In this program, you'll learn to add two dates in Java using Calendar.
To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Basic Input and Output

Since, Java epoch is 1970, any time represented in a Date object will not work. This means, your Dates will start
from 1970 and when two Date objects are added, the sum misses by about 1970 years.

So, we use Calendar instead.

Example: Java program to add two dates

import java.util.Calendar;

public class AddDates {

public static void main(String[] args) {

Calendar c1 = Calendar.getInstance();

Calendar c2 = Calendar.getInstance();

Calendar cTotal = (Calendar) c1.clone();

cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR));

cTotal.add(Calendar.MONTH, c2.get(Calendar.MONTH) + 1); // Zero-based months

cTotal.add(Calendar.DATE, c2.get(Calendar.DATE));

cTotal.add(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY));

cTotal.add(Calendar.MINUTE, c2.get(Calendar.MINUTE));

cTotal.add(Calendar.SECOND, c2.get(Calendar.SECOND));

cTotal.add(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND));

System.out.format("%s + %s = %s", c1.getTime(), c2.getTime(), cTotal.getTime());


}

Output

Tue Aug 08 10:20:56 NPT 2017 + Tue Aug 08 10:20:56 NPT 2017 = Mon Apr 16 20:41:53 NPT 4035

In the above program, c1 and c2 stores the current date. Then, we simply clone c1 and add c2's each DateTime
properties one after the other.

As you can see, we've added 1 to the months. This is because months start with 0 in Java.

Alternatively, you can also use Joda for time/date operations in Java.

79. Java Program to Join Two Lists


In this program, you'll learn different techniques to join two lists in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java List

Java ArrayList Class

Java ArrayList addAll()

Example 1: Join Two Lists using addAll()

import java.util.ArrayList;

import java.util.List;

public class JoinLists {

public static void main(String[] args) {

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

list1.add("a");
List<String> list2 = new ArrayList<String>();

list2.add("b");

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

joined.addAll(list1);

joined.addAll(list2);

System.out.println("list1: " + list1);

System.out.println("list2: " + list2);

System.out.println("joined: " + joined);

Output

list1: [a]

list2: [b]

joined: [a, b]

In the above program, we used List's addAll() method to join lists list1 and list2 to the joined list.

Example 2: Join Two Lists using union()

import java.util.ArrayList;

import java.util.List;

import org.apache.commons.collections.ListUtils;

public class JoinLists {

public static void main(String[] args) {


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

list1.add("a");

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

list2.add("b");

List<String> joined = ListUtils.union(list1, list2);

System.out.println("list1: " + list1);

System.out.println("list2: " + list2);

System.out.println("joined: " + joined);

The output of this program is the same as Example 1.

In the above program, we used union() method to join the given lists to joined.

Example 3: Join Two Lists using stream

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.Stream;

public class JoinLists {

public static void main(String[] args) {

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


list1.add("a");

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

list2.add("b");

List<String> joined = Stream.concat(list1.stream(), list2.stream())

.collect(Collectors.toList());

System.out.println("list1: " + list1);

System.out.println("list2: " + list2);

System.out.println("joined: " + joined);

The output of this program is the same as Example 1.

In the above program, we used Stream's concat() method to join two lists converted to streams. Then, we
convert them back to List using toList().

80. Java Program to Convert the ArrayList to an array and vice versa
In this example, we will learn to convert the arraylist into an array and vice versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java Arrays

Example 1: Convert the Arraylist into Array

import java.util.ArrayList;

class Main {

public static void main(String[] args) {


ArrayList<String> languages= new ArrayList<>();

// Add elements in the arraylist

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

System.out.println("ArrayList: " + languages);

// Create a new array of String type

String[] arr = new String[languages.size()];

// Convert ArrayList into the string array

languages.toArray(arr);

System.out.print("Array: ");

for(String item:arr) {

System.out.print(item+", ");

Output

ArrayList: [Java, Python, JavaScript]

Array: Java, Python, JavaScript,

In the above example, we have created an arraylist named languages. Notice the line,

languages.toArray(arr);

Here, the toArray() method converts the arraylist languages into an array. And stores it in the string array arr.

Note: If we don't pass any argument to the toArray() method, the method returns an array of the Object type.
Example 2: Convert Array to ArrayList

import java.util.Arrays;

import java.util.ArrayList;

class Main {

public static void main(String[] args) {

// create an array

String[] array = {"Java", "Python", "C"};

System.out.println("Array: " + Arrays.toString(array));

// convert array to arraylist

ArrayList<String> languages= new ArrayList<>(Arrays.asList(array));

System.out.println("ArrayList: " + languages);

Output

Array: [Java, Python, C]

ArrayList: [Java, Python, C]

In the above example, we have created an array of String type. Notice the expression,

Arrays.asList(array)

Here, the asList() method of the Arrays class converts the specified array into the arraylist.

81. Java Program to Get Current Working Directory


In this program, you'll learn to get the current working directory in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java String

Example 1: Get current working directory

public class CurrDirectory {

public static void main(String[] args) {

String path = System.getProperty("user.dir");

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

Output

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we used System's getProperty() method to get the user.dir property of the program. This
returns the directory which contains our Java project.

Example 2: Get the current working directory using Path

import java.nio.file.Paths;

public class CurrDirectory {

public static void main(String[] args) {

String path = Paths.get("").toAbsolutePath().toString();

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


}

Output

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we used Path's get() method to get the current path of our program. This returns a
relative path to the working directory.

We then change the relative path to an absolute path using toAbsolutePath(). Since it returns a Path object, we
need to change it to a string using toString() method.

82. Java Program to Convert Map (HashMap) to List


In this program, you'll learn different techniques to convert a map to a list in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Map Interface

Java HashMap

Java List

Java ArrayList Class

Example 1: Convert Map to List

import java.util.*;

public class MapList {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "a");

map.put(2, "b");

map.put(3, "c");

map.put(4, "d");
map.put(5, "e");

List<Integer> keyList = new ArrayList(map.keySet());

List<String> valueList = new ArrayList(map.values());

System.out.println("Key List: " + keyList);

System.out.println("Value List: " + valueList);

Output

Key List: [1, 2, 3, 4, 5]

Value List: [a, b, c, d, e]

In the above program, we have a map of Integer and String named map. Since the map contains a key, value
pair, we need two lists to store each of them, namely keyList for keys and valueList for

values.

We used map's keySet() method to get all the keys and created an ArrayList keyList from them. Likewise, we
used the map's values() method to get all the values and created an ArrayList valueList

from them.

Example 2: Convert Map to List using stream

import java.util.*;

import java.util.stream.Collectors;

public class MapList {

public static void main(String[] args) {


Map<Integer, String> map = new HashMap<>();

map.put(1, "a");

map.put(2, "b");

map.put(3, "c");

map.put(4, "d");

map.put(5, "e");

List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());

List<String> valueList = map.values().stream().collect(Collectors.toList());

System.out.println("Key List: " + keyList);

System.out.println("Value List: " + valueList);

The output of the program is the same as Example 1.

In the above program, instead of using ArrayList constructor, we've used stream() to convert the map to a list.

We've converted the keys and values to stream and convert it to a list using collect() method passing Collectors'
toList() as a parameter.

83. Java Program to Convert Array to Set (HashSet) and Vice-Versa


In this program, you'll learn to convert an array to a set and vice versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Set Interface

Java HashSet Class

Java Arrays
Example 1: Convert Array to Set

import java.util.*;

public class ArraySet {

public static void main(String[] args) {

String[] array = {"a", "b", "c"};

Set<String> set = new HashSet<>(Arrays.asList(array));

System.out.println("Set: " + set);

Output

Set: [a, b, c]

In the above program, we have an array named array. To convert array to set, we first convert it to a list using
asList() as HashSet accepts a list as a constructor.

Then, we initialize the set with the elements of the converted list.

Example 2: Convert Array to Set using stream

import java.util.*;

public class ArraySet {

public static void main(String[] args) {

String[] array = {"a", "b", "c"};

Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet()));


System.out.println("Set: " + set);

The output of the program is the same as Example 1.

In the above program, instead of converting an array to list and then to a set, we use a stream to convert to set.

We first convert the array to stream using stream() method and use collect() method with toSet() as a parameter
to convert the stream to a set.

Example 3: Convert Set to Array

import java.util.*;

public class SetArray {

public static void main(String[] args) {

Set<String> set = new HashSet<>();

set.add("a");

set.add("b");

set.add("c");

String[] array = new String[set.size()];

set.toArray(array);

System.out.println("Array: " + Arrays.toString(array));

}
Output

Array: [a, b, c]

In the above program, we have a HashSet named set. To convert set into an array, we first create an array of
length equal to the size of the set and use toArray() method.

84. Java Program to Convert Byte Array to Hexadecimal


In this program, you'll learn different techniques to convert byte array to hexadecimal in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Arrays

Java Class and Objects

Example 1: Convert Byte Array to Hex value

public class ByteHex {

public static void main(String[] args) {

byte[] bytes = {10, 2, 15, 11};

for (byte b : bytes) {

String st = String.format("%02X", b);

System.out.print(st);

Output

0A020F0B

In the above program, we have a byte array named bytes. To convert byte array to a hex value, we loop through
each byte in the array and use String's format().
We use %02X to print two places (02) of Hexadecimal (X) value and store it in the string st.

This is a relatively slower process for large byte array conversion. We can dramatically increase the speed of
execution using byte operations shown below.

Example 2: Convert Byte Array to Hex value using byte operations

public class ByteHex {

private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

public static String bytesToHex(byte[] bytes) {

char[] hexChars = new char[bytes.length * 2];

for ( int j = 0; j < bytes.length; j++ ) {

int v = bytes[j] & 0xFF;

hexChars[j * 2] = hexArray[v >>> 4];

hexChars[j * 2 + 1] = hexArray[v & 0x0F];

return new String(hexChars);

public static void main(String[] args) {

byte[] bytes = {10, 2, 15, 11};

String s = bytesToHex(bytes);

System.out.println(s);

The output of the program is the same as Example 1.


85. Java Program to Create String from Contents of a File
In this program, you'll learn different techniques to create a string from concents of a given file in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java File Class

Before we create a string from a file, we assume we have a file named test.txt in our src folder.

Here's the content of test.txt

This is a

Test file.

Example 1: Create String from file

import java.io.IOException;

import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.List;

public class FileString {

public static void main(String[] args) throws IOException {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

Charset encoding = Charset.defaultCharset();

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

System.out.println(lines);
}

Output

[This is a, Test file.]

In the above program, we use System's user.dir property to get the current directory stored in the variable path.
Check Java Program to get the current directory for more information.

We used defaultCharset() for the file's encoding. If you know the encoding, use it, else it's safe to use default
encoding.

Then, we used readAllLines() method to read all lines from the file. It takes the path of the file and its encoding
and returns all the lines as a list as shown in the output.

Since readAllLines may also throw an IOException, we have to define our main method as such

public static void main(String[] args) throws IOException

Example 2: Create String from a file

import java.io.IOException;

import java.nio.charset.Charset;

import java.nio.file.Files;

import java.nio.file.Paths;

public class FileString {

public static void main(String[] args) throws IOException {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

Charset encoding = Charset.defaultCharset();

byte[] encoded = Files.readAllBytes(Paths.get(path));


String lines = new String(encoded, encoding);

System.out.println(lines);

Output

This is a

Test file.

In the above program, instead of getting a list of string, we get a single string, lines, with all the contents.

For this, we used readAllBytes() method to read all bytes from the given path. These bytes are then converted to
a string using the default encoding.

86. Java Program to Append Text to an Existing File


In this program, you'll learn different techniques to append text to an existing file in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java Exception Handling

Before we append text to an existing file, we assume we have a file named test.txt in our src folder.

Here's the content of test.txt

This is a

Test file.

Example 1: Append text to existing file

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;
public class AppendFile {

public static void main(String[] args) {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

String text = "Added text";

try {

Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND);

} catch (IOException e) {

When you run the program, the test.txt file now contains:

This is a

Test file.Added text

In the above program, we use System's user.dir property to get the current directory stored in the variable path.
Check Java Program to get the current directory for more information.

Likewise, the text to be added is stored in the variable text. Then, inside a try-catch block we use Files' write()
method to append text to the existing file.

The write() method takes the path of the given file, the text to the written, and how the file should be open for
writing. In our case, we used APPEND option for writing.

Since the write() method may return an IOException, we use a try-catch block to catch the exception properly.

Example 2: Append text to an existing file using FileWriter


import java.io.FileWriter;

import java.io.IOException;

public class AppendFile {

public static void main(String[] args) {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

String text = "Added text";

try {

FileWriter fw = new FileWriter(path, true);

fw.write(text);

fw.close();

catch(IOException e) {

The output of the program is the same as Example 1.

In the above program, instead of using write() method, we use an instance (object) FileWriter to append text to
an existing file.

When creating a FileWriter object, we pass the path of the file and true as the second parameter. true means we
allow the file to be appended.

Then, we use write() method to append the given text and close the filewriter.

87. Java Program to Convert File to byte array and Vice-Versa


In this program, you'll learn to convert a File object to byte[] and vice-versa in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java Arrays

Before we convert a file to byte array and vice-versa, we assume we have a file named test.txt in our src folder.

Here's the content of test.txt

This is a

Test file.

Example 1: Convert File to byte[]

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.Arrays;

public class FileByte {

public static void main(String[] args) {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

try {

byte[] encoded = Files.readAllBytes(Paths.get(path));

System.out.println(Arrays.toString(encoded));

} catch (IOException e) {

}
v

[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

In the above program, we store the path to the file in the variable path.

Then, inside the try block, we read all the bytes from the given path using readAllBytes() method.

Then, we use Arrays' toString() method to print the byte array.

Since, readAllBytes() might throw an IOException, we've used the try-catch block in the program.

Example 2: Convert byte[] to File

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

public class ByteFile {

public static void main(String[] args) {

String path = System.getProperty("user.dir") + "\\src\\test.txt";

String finalPath = System.getProperty("user.dir") + "\\src\\final.txt";

try {

byte[] encoded = Files.readAllBytes(Paths.get(path));

Files.write(Paths.get(finalPath), encoded);

} catch (IOException e) {

}
}

When you run the program, the contents of test.txt is copied to final.txt.

In the above program, we've used the same method as Example 1 to read all the bytes from the File stored in
path. These bytes are stored in the array encoded.

We also have a finalPath where the bytes are to be written.

Then, we simply use the Files' write() method to write the encoded byte array to a File in the given finalPath.

88. Java Program to Convert InputStream to String


In this program, you'll learn to convert input stream to a string using InputStreamReader in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java InputStream Class

Java String

Example: Convert InputStream to String

import java.io.*;

public class InputStreamString {

public static void main(String[] args) throws IOException {

InputStream stream = new ByteArrayInputStream("Hello there!".getBytes());

StringBuilder sb = new StringBuilder();

String line;

BufferedReader br = new BufferedReader(new InputStreamReader(stream));

while ((line = br.readLine()) != null) {


sb.append(line);

br.close();

System.out.println(sb);

Output

Hello there!

In the above program, the input stream is created from a String and stored in a variable stream. We also require
a string builder sb to create the string from the stream.

Then, we created a buffered reader br from the InputStreamReader to read the lines from the stream. Using a
while loop, we read each line and append it to the string builder. Finally, we closed

the bufferedReader.

Since, the reader can throw IOException, we have the throws IOException in the main function as:

public static void main(String[] args) throws IOException

89. Java Program to Convert OutputStream to String


In this program, you'll learn to convert outputstream to a string using String initializer in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java OutputStream Class

Java String

Example: Convert OutputStream to String

import java.io.*;
public class OutputStreamString {

public static void main(String[] args) throws IOException {

ByteArrayOutputStream stream = new ByteArrayOutputStream();

String line = "Hello there!";

stream.write(line.getBytes());

String finalString = new String(stream.toByteArray());

System.out.println(finalString);

Output

Hello there!

In the above program, we've created an OutputStream based on the given string line. This is done using stream's
write() method.

Then, we simply convert the OutputStream to finalString using String's constructor which takes byte array. For
this, we use stream's toByteArray() method.

90. Java Program to Lookup enum by String value


In this program, you'll learn to convert a string value to a enum in Java using enum's valueOf() method.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java enums

Example: Lookup enum by string value

public class EnumString {


public enum TextStyle {

BOLD, ITALICS, UNDERLINE, STRIKETHROUGH

public static void main(String[] args) {

String style = "Bold";

TextStyle textStyle = TextStyle.valueOf(style.toUpperCase());

System.out.println(textStyle);

Output

BOLD

In the above program, we have an enum TextStyle which represents the different styles a block of text can have,
i.e. Bold, Italics, Underline, Strikethrough.

We also have a string named style which holds the current style we want. However, it is not in all-caps.

We then use the enum TextStyle's valueOf() method to pass the style and get the enum value we require.

Since valueOf() takes a case-sensitive string value, we had to use the toUpperCase() method to convert the given
string to upper case.

If, instead, we'd used:

TextStyle.valueOf(style)

the program would've thrown an exception No enum constant EnumString.TextStyle.Bold.


91. Java Program to Sort a Map By Values
In this program, you'll learn to sort a given map by values in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Map Interface

Java LinkedHashMap

Example: Sort a map by values

import java.util.*;

public class SortMap {

public static void main(String[] args) {

LinkedHashMap<String, String> capitals = new LinkedHashMap<>();

capitals.put("Nepal", "Kathmandu");

capitals.put("India", "New Delhi");

capitals.put("United States", "Washington");

capitals.put("England", "London");

capitals.put("Australia", "Canberra");

Map<String, String> result = sortMap(capitals);

for (Map.Entry<String, String> entry : result.entrySet())

System.out.print("Key: " + entry.getKey());

System.out.println(" Value: " + entry.getValue());

}
public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {

List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());

Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

LinkedHashMap<String, String> result = new LinkedHashMap<>();

for (Map.Entry<String, String> entry : capitalList)

result.put(entry.getKey(), entry.getValue());

return result;

Output

Key: Australia Value: Canberra

Key: Nepal Value: Kathmandu

Key: England Value: London

Key: India Value: New Delhi

Key: United States Value: Washington

In the above program, we have a LinkedHashMap with countries and their respective capitals stored in variable
capital.

We have a method sortMap() that takes a linked hash map and returns the sorted linked hash map.

Inside the method, we converted the hash map to a list capitalList. Then, we use sort() method which takes a list
and a comparator.

In our case, the comparator is the lambda which compares (o1, o2) -> o1.getValue().compareTo(o2.getValue())
two values of the items in the list o1 and o2.
After the operation, we get the sorted list capitalList. Then, we simply convert the list to LinkedHashMap result
and return it.

Back in the main() method, we loop through each item in the map and print its key and value.

92. Java Program to Sort ArrayList of Custom Objects By Property


In this program, you'll learn to sort an arraylist of custom object by their given property in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java ArrayList Class

Example: Sort ArrayList of Custom Objects By Property

import java.util.*;

public class CustomObject {

private String customProperty;

public CustomObject(String property) {

this.customProperty = property;

public String getCustomProperty() {

return this.customProperty;

public static void main(String[] args) {

ArrayList<Customobject> list = new ArrayList<>();


list.add(new CustomObject("Z"));

list.add(new CustomObject("A"));

list.add(new CustomObject("B"));

list.add(new CustomObject("X"));

list.add(new CustomObject("Aa"));

list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty()));

for (CustomObject obj : list) {

System.out.println(obj.getCustomProperty());

Output

Aa

In the above program, we've defined a CustomObject class with a String property, customProperty.

We've also added a constructor that initializes the property, and a getter function getCustomProperty() which
returns customProperty.

In the main() method, we've created an array list of custom objects list, initialized with 5 objects.

For sorting the list with the given property, we use list's sort() method. The sort() method takes the list to be
sorted (final sorted list is also the same) and a comparator.

In our case, the comparator is a lambda which


takes two objects from the list o1 and o2,

compares the two object's customProperty using compareTo() method,

and finally returns positive number if o1's property is greater than o2's, negative if o1's property is lesser than
o2's, and zero if they are equal.

Based on this, list is sorted based on least property to greatest and stored back to list.

93. Java Program to Create Directories


In this example, we will learn to create directories in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java if, if...else Statement

The Java File class provides the mkdir() method to create a new directory. The method returns

true if the new directory is created

false if the directory already exists

Example 1: Create a new directory in Java

import java.io.File;

class Main {

public static void main(String[] args) {

// creates a file object with specified path

File file = new File("Java Example\\directory");

// tries to create a new directory

boolean value = file.mkdir();

if(value) {

System.out.println("The new directory is created.");


}

else {

System.out.println("The directory already exists.");

In the above example, we have created a file object named file. The object includes information about the
specified directory path.

File file = new File("Java Example\\directory");

Here, we have used the mkdir() method to create a new directory in the specified path.

If the directory doesn't exist in the specified location, the new directory is created and this message is shown.

The new directory is created.

However, if the directory already exists, we will see this message.

The directory already exists.

It is important to note that, the directory is created inside the Java Example parent directory.

However, if the Java Example parent directory doesn't exist, then the mkdir() method cannot create the
directory.

In this case, we can use the mkdirs() method of the Java File class. The method allows us to create the parent
directory as well if it's not already there.

Example 2: Create a new Directory using the mkdirs() method

import java.io.File;

class Main {
public static void main(String[] args) {

// creates a file object in the current path

File file = new File("Java Tutorial\\abc");

// tries to create a new directory

boolean value = file.mkdirs();

if(value) {

System.out.println("The new directory is created.");

else {

System.out.println("The directory already exists.");

In the above example, we have created a file object named file. The object includes information about the
directory path.

File file = new File("Tutorial\\directory");

Here, we have used the mkdirs() method to create a new directory with the specified path.

If the directory doesn't exist in the current location, the new directory is created and this message is shown.

The new directory is created.

However, if the directory already exists, we will see this message.

The directory already exists.

Here, if the Tutorial directory doesn't exist, then the mkdirs() method creates the Tutorial directory as well along
with the directory.
Note: We have used double-backslash while specifying the path. It is because the \ character is used as an
escape character in Java. Hence the first backslash is used as an escape character for

the second one.

94. Java Program to Rename File


In this tutorial, we will learn to rename file in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java Exception Handling

Java if, if...else Statement

The Java File class provides the renameTo() method to change the name of the file. It returns true if the
renaming operation succeeds otherwise returns false.

Example: Rename a File in Java

import java.io.File;

class Main {

public static void main(String[] args) {

// create a file object

File file = new File("oldName");

// create a file

try {

file.createNewFile();

catch(Exception e) {

e.getStackTrace();

}
// create an object that contains the new name of file

File newFile = new File("newName");

// change the name of file

boolean value = file.renameTo(newFile);

if(value) {

System.out.println("The name of the file is changed.");

else {

System.out.println("The name cannot be changed.");

In the above example, we have created a file object named file. The object holds information about the specified
file path.

File file = new File("oldName");

We then create a new file with the specified file path.

// create a new file with the specified path

file.createNewFile();

Here, we have created another file object named newFile. The object holds information about the specified file
path.

File newFile = new File("newFile");

To change the name of the file, we have used the renameTo() method. The name specified by the newFile object
is used to rename the file specified by the file object.

file.renameTo(newFile);
If the operation succeeds, then the following message is shown.

The name of the file is changed.

If the operation cannot succeed, the following message is shown.

The name cannot be changed.

95. Java Program to Get all Files Present in a Directory


In this example, we will learn to list all the files and sub-directories present inside a directory.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java Exception Handling

The list() method of the Java File class is used to list all the files and subdirectories present inside a directory. It
returns all the files and directories as a string array.

Example 1: Java Program to List all files

import java.io.File;

class Main {

public static void main(String[] args) {

// creates a file object

File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

// returns an array of all files

String[] fileList = file.list();

for(String str : fileList) {

System.out.println(str);
}

Output

.vscode

file.txt

directory

newFile.txt

In the above example, we have created a file object named file. The object holds information about the specified
path.

File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

We have used the list() method to list all the files and subdirectories present in the specified path.

file.list();

Note: We have used double-backslash while specifying the path. It is because the \ character is used as an
escape character in Java. Hence the first backslash is used as an escape character for

the second one.

Example 2: List files present in a Directory excluding Subdirectories

import java.io.File;

class Main {

public static void main(String[] args) {

try {

File folder = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Java Article");


// list all the files

File[] files = folder.listFiles();

for(File file : files) {

if(file.isFile()) {

System.out.println(file);

} catch (Exception e) {

e.getStackTrace();

Output

C:\Users\Unknown\Desktop\Java Article\Language.class

C:\Users\Unknown\Desktop\Java Article\Languages.class

C:\Users\Unknown\Desktop\Java Article\Main.class

C:\Users\Unknown\Desktop\Java Article\Main.java

C:\Users\Unknown\Desktop\Java Article\sidebar.html

C:\Users\Unknown\Desktop\Java Article\Test.class

C:\Users\Unknown\Desktop\Java Article\Time.class

C:\Users\Unknown\Desktop\Java Article\Time.java

In the above example, we have used the listFiles() method to store all files in an array.

96. Java Program to Copy File


In this tutorial, we will learn to copy files in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class


Java I/O Streams

The Java File class doesn't provide any method to copy one file to another. However, we can use Java I/O
Streams to read content from one file and write to another.

Example: Copy files using i/o streams

import java.io.FileInputStream;

import java.io.FileOutputStream;

class Main {

public static void main(String[] args) {

byte[] array = new byte[50];

try {

FileInputStream sourceFile = new FileInputStream("input.txt");

FileOutputStream destFile = new FileOutputStream("newFile");

// reads all data from input.txt

sourceFile.read(array);

// writes all data to newFile

destFile.write(array);

System.out.println("The input.txt file is copied to newFile.");

// closes the stream

sourceFile.close();

destFile.close();

catch (Exception e) {

e.getStackTrace();

}
}

Output

The input.txt file is copied to newFile.

In the above example, we have used the FileInputStream and FileOutputStream to copy one file to another.

Here,

FileInputStream reads all the content from input.txt to an array

FileOutputStream writes all the content from the array to newFile

Note:

The FileUtils class of org.apache.commons.io package provides the copyFile() method to copy the file.

The Files class of java.nio package provides the copy() method to copy the file.

97. Java Program to convert char type variables to int


In this program, we will learn to convert the character (char) type variable into an integer (int) in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Basic Input and Output

Example 1: Java Program to Convert char to int

class Main {

public static void main(String[] args) {

// create char variables

char a = '5';

char b = 'c';

// convert char variables to int


// ASCII value of characters is assigned

int num1 = a;

int num2 = b;

// print the values

System.out.println(num1); // 53

System.out.println(num2); // 99

In the above example, we have char type variables a and b. Note that we have assigned the char variables to int
variables.

Here, instead of the characters, the ASCII value of the characters are assigned to the int variables. Hence, we get
the value 53 (ASCII value of '5') and 99 (ASCII value of 'c') as output.

Example 2: char to int using getNumericValue() method

We can also use the getNumericValue() method of the Character class to convert the char type variable into int
type.

class Main {

public static void main(String[] args) {

// create char variables

char a = '5';

char b = '9';

// convert char variables to int

// Use getNumericValue()

int num1 = Character.getNumericValue(a);

int num2 = Character.getNumericValue(b);


// print the numeric value of characters

System.out.println(num1); // 5

System.out.println(num2); // 9

Here, as we can see the getNumericValue() method returns the numeric value of the character. The character '5'
is converted into an integer 5 and the character '9' is converted into an integer 9.

To learn more about the getNumericValue() method, visit Java getNumericValue() (Official Oracle
Documentation).

Example 3: char to int using parseInt() method

We can also use the parseInt() method of the Integer class to convert the char type variable to an int type.

class Main {

public static void main(String[] args) {

// create char variables

char a = '5';

char b = '9';

// 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); // 5

System.out.println(num2); // 9

}
}

Notice the expression,

Integer.parseInt(String.valueOf(a))

Here,

String.valueOf(a) - converts the char type variable a into a String

Integer.parseInt() - converts the string into an int

Note: The Integer.parseInt() method only works with string type variables. Hence, the character 'a' is converted
into a String.

Example 4: char to int by subtracting with '0'

In Java, we can also convert the character into an integer by subtracting it with character 0. For example,

class Main {

public static void main(String[] args) {

// create char variables

char a = '9';

char b = '3';

// convert char variables to int

// by subtracting with char 0

int num1 = a - '0';

int num2 = b - '0';

// print numeric value

System.out.println(num1); // 9

System.out.println(num2); // 3

}
In the above example, notice the line,

int num1 = a -'0';

Here, we have subtracted the character 'a' by the character '0'. In this case, the characters are converted into
integers. And subtracting a value by zero gives the same value. That is, 9 - 0 = 9.

Hence, we get the integer values 9 and 3 of the character '9' and '3' respectively.

98. Java Program to convert int type variables to char


In this program, we will learn to convert the integer (int) variable into a character (char) in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Basic Input and Output

Example 1: Java Program to Convert int to char

class Main {

public static void main(String[] args) {

// create int variables

int num1 = 80;

int num2 = 81;

// convert int to char

// typecasting

char a = (char)num1;

char b = (char)num2;

// print value

System.out.println(a); // P

System.out.println(b); // Q
}

In the above example, we have int type variables num1 and num2. Notice the line,

char a = (char)num1;

Here, we are using typecasting to covert an int type variable into the char type variable. To learn more, visit Java
Typecasting.

Note that the int values are treated as ASCII values. Hence, we get P for int value 80 and Q for int value 81. It is
because the ASCII value of P and Q are 80 and 81 respectively.

Example 2: int to char by using forDigit()

We can also use the forDigit() method of the Character class to convert the int type variable into char type.

class Main {

public static void main(String[] args) {

// create int variables

int num1 = 1;

int num2 = 13;

// convert int to char

// for value between 0-9

char a = Character.forDigit(num1, 10);

// for value between 0-9

char b = Character.forDigit(num2, 16);

// print value

System.out.println(a); // 1

System.out.println(b); // d
}

Notice the expression,

char a = Character.forDigit(num1, 10);

We have used the forDigit() method converts the specified int value into char value.

Here, 10 and 16 are radix values for decimal and hexadecimal numbers respectively. That is, if the int value is
between 0 to 9, we use 10 as radix value, if the int value is between 0 to 15, we

use 16, and so on.

To learn more about the forDigit() method, visit Java Character.forDigit() (Official Oracle Documentation).

Example 3: int to char by adding '0'

In Java, we can also convert the integer into a character by adding the character '0' with it. For example,

class Main {

public static void main(String[] args) {

// create int variables

int num1 = 1;

int num2 = 9;

// convert int to char

char a = (char)(num1 + '0');

char b = (char)(num2 + '0');

// print value

System.out.println(a); // 1
System.out.println(b); // 9

In the above example, notice the line,

char a = (char)(num1 + '0');

Here, the character '0' is converted into ASCII value 48. The value 48 is added to the value of num1 (i.e. 1). The
result 49 is the ASCII value of 1. Hence, we get the character '1' as the output.

Note: This is only applicable for int value 0 to 9.

99. Java Program to convert long type variables into int


In this program, we will learn to convert the long variable into an integer (int) in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Example 1: Java Program to Convert long to int using Typecasting

class Main {

public static void main(String[] args) {

// create long variables

long a = 2322331L;

long b = 52341241L;

// convert long into int

// using typecasting

int c = (int)a;

int d = (int)b;

System.out.println(c); // 2322331
System.out.println(d); // 52341241

In the above example, we have long type variables a and b. Notice the lines,

int c = (int)a;

Here, the higher data type long is converted into the lower data type int. Hence, this is called narrowing
typecasting. To learn more, visit Java Typecasting.

This process works fine when the value of the long variable is less than or equal to the maximum value of int
(2147483647). However, if the value of the long variable is greater than the maximum

int value, then there will be a loss in data.

Example 2: long to int conversion using toIntExact()

We can also use the toIntExact() method of the Math class to convert the long value into an int.

class Main {

public static void main(String[] args) {

// create long variable

long value1 = 52336L;

long value2 = -445636L;

// change long to int

int num1 = Math.toIntExact(value1);

int num2 = Math.toIntExact(value2);

// print the int value

System.out.println(num1); // 52336

System.out.println(num2); // -445636
}

Here, the Math.toIntExact(value1) method converts the long variable value1 into int and returns it.

The toIntExact() method throws an exception if the returned int value is not within the range of the int data
type. That is,

// value out of range of int

long value = 32147483648L

// throws the integer overflow exception

int num = Math.toIntExact(value);

To learn more on toIntExact() method, visit Java Math.toIntExact().

Example 3: Convert object of the Long class to int

In Java, we can also convert the object of wrapper class Long into an int. For this, we can use the intValue()
method. For, example,

class Main {

public static void main(String[] args) {

// create an object of Long class

Long obj = 52341241L;

// convert object of Long into int

// using intValue()

int a = obj.intValue();

System.out.println(a); // 52341241

}
}

Here, we have created an object of the Long class named obj. We then used the intValue() method to convert
the object into int type.

To learn more about wrapper class, visit the Java Wrapper Class.

100. Java Program to convert int type variables to long


In this program, we will learn to convert integer (int) variables into the long variables in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Example 1: Java Program to Convert int to long using Typecasting

class Main {

public static void main(String[] args) {

// create int variables

int a = 25;

int b = 34;

// convert int into long

// using typecasting

long c = a;

long d = b;

System.out.println(c); // 25

System.out.println(d); // 34

In the above example, we have int type variables a and b. Notice the lines,
long c = a;

Here, the int type variable is automatically converted into long. It is because long is a higher data type and int is
a lower data type.

Hence, there will be no loss in data while converting from int to long. This is called widening typecasting. To
learn more, visit Java Typecasting.

Example 2: Java Program to Convert int into object of Long using valueof()

We can convert the int type variable into an object of the Long class. For example,

class Main {

public static void main(String[] args) {

// create int variables

int a = 251;

// convert to an object of Long

// using valueOf()

Long obj = Long.valueOf(a);

System.out.println(obj); // 251

In the above example, we have used the Long.valueOf() method to convert the variable a into an object of Long.

Here, Long is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

101. Java Program to convert boolean variables into string


In this program, we will learn to convert the boolean type variables into string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types

Java String

Example 1: Convert boolean to string using valueOf()

class Main {

public static void main(String[] args) {

// create boolean variables

boolean booleanValue1 = true;

boolean booleanValue2 = false;

// convert boolean to string

// using valueOf()

String stringValue1 = String.valueOf(booleanValue1);

String stringValue2 = String.valueOf(booleanValue2);

System.out.println(stringValue1); // true

System.out.println(stringValue2); // true

In the above example, we have used the valueOf() method of String class to convert the boolean variables into
strings.

Example 2: Convert boolean to String using toString()

We can also convert the boolean variables into strings using the toString() method of the Boolean class. For
example,

class Main {

public static void main(String[] args) {


// create boolean variables

boolean booleanValue1 = true;

boolean booleanValue2 = false;

// convert boolean to string

// using toString()

String stringValue1 = Boolean.toString(booleanValue1);

String stringValue2 = Boolean.toString(booleanValue2);

System.out.println(stringValue1); // true

System.out.println(stringValue2); // true

In the above example, the toString() method of Boolean class converts the boolean variables into strings. Here,
Boolean is a wrapper class. To learn more, visit the Java Wrapper Class.

102. Java Program to convert string type variables into boolean


In this program, we will learn to convert the String type variables into boolean in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java String

Example 1: Convert string to boolean using parseBoolean()

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "true";

String str2 = "false";


// convert string to boolean

// using parseBoolean()

boolean b1 = Boolean.parseBoolean(str1);

boolean b2 = Boolean.parseBoolean(str2);

// print boolean values

System.out.println(b1); // true

System.out.println(b2); // false

In the above example, we have used the parseBoolean() method of the Boolean class to convert the string
variables into boolean.

Here, Boolean is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

Example 2: Convert string to boolean using valueOf()

We can also convert the string variables into boolean using the valueOf() method. For example,

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "true";

String str2 = "false";

// convert string to boolean

// using valueOf()

boolean b1 = Boolean.valueOf(str1);

boolean b2 = Boolean.valueOf(str2);
// print boolean values

System.out.println(b1); // true

System.out.println(b2); // false

In the above example, the valueOf() method of Boolean class converts the string variables into boolean.

Here, the valueOf() method actually returns an object of the Boolean class. However, the object is automatically
converted into a primitive type. This is called unboxing in Java. To learn more,

visit Java autoboxing and unboxing.

That is,

// valueOf() returns object of Boolean

// object is converted onto boolean value

boolean b1 = Boolean obj = Boolean.valueOf(str1)

103. Java Program to convert string type variables into int


In this program, we will learn to convert the String type variables into the integer (int) in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java String

Example 1: Java Program to Convert string to int using parseInt()

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "23";

String str2 = "4566";


// convert string to int

// using parseInt()

int num1 = Integer.parseInt(str1);

int num2 = Integer.parseInt(str2);

// print int values

System.out.println(num1); // 23

System.out.println(num2); // 4566

In the above example, we have used the parseInt() method of the Integer class to convert the string variables
into the int.

Here, Integer is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

Note: The string variables should represent the int values. Otherwise the compiler will throw an exception. For
example,

class Main {

public static void main(String[] args) {

// create a string variable

String str1 = "Programiz";

// convert string to int

// using parseInt()

int num1 = Integer.parseInt(str1);

// print int values


System.out.println(num1); // throws NumberFormatException

Example 2: Java Program to Convert string to int using valueOf()

We can also convert the string variables into an object of Integer using the valueOf() method. For example,

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "643";

String str2 = "1312";

// convert String to int

// using valueOf()

int num1 = Integer.valueOf(str1);

int num2 = Integer.valueOf(str2);

// print int values

System.out.println(num1); // 643

System.out.println(num2); // 1312

In the above example, the valueOf() method of Integer class converts the string variables into the int.

Here, the valueOf() method actually returns an object of the Integer class. However, the object is automatically
converted into the primitive type. This is called unboxing in Java. To learn more,

visit Java autoboxing and unboxing.

That is,
// valueOf() returns object of Integer

// object is converted onto int

int num1 = Integer obj = Integer.valueOf(str1)

104. Java Program to convert int type variables to String


In this program, we will learn to convert the integer (int) variables into the string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java String

Example 1: Java Program to Convert int to string using valueOf()

class Main {

public static void main(String[] args) {

// create int variable

int num1 = 36;

int num2 = 99;

// convert int to string

// using valueOf()

String str1 = String.valueOf(num1);

String str2 = String.valueOf(num2);

// print string variables

System.out.println(str1); // 36

System.out.println(str2); // 99

}
In the above example, we have used the valueOf() method of the String class to convert the int variables into
string.

Note: This is the most preferred way of converting int variables to string in Java.

Example 2: Java Program to Convert int to string using toString()

We can also convert the int variable into string using the toString() method of the Integer class. For example,

class Main {

public static void main(String[] args) {

// create int variables

int num1 = 476;

int num2 = 78656;

// convert int to string

// using toString()

String str1 = Integer.toString(num1);

String str2 = Integer.toString(num2);

// print string variables

System.out.println(str1); // 476

System.out.println(str2); // 78656

In the above example, we have used the toString() method of the Integer class to convert the int variables into
string.

Here, Integer is the wrapper class. To learn more, visit the Java Wrapper Class.
Example 3: Java Program to Convert int to String using + Operator

class Main {

public static void main(String[] args) {

// create int variables

int num1 = 3476;

int num2 = 8656;

// convert int to string

// using + sign

String str1 = "" + num1;

String str2 = "" + num2;

// print string variables

System.out.println(str1); // 3476

System.out.println(str2); // 8656

Notice the line,

String str1 = "" + num1;

Here, we are using the string concatenation operation to convert an integer into the string. To learn more, visit
Java String concatenation.

Example 4: Java Program to Convert int to String using format()

class Main {

public static void main(String[] args) {

// create a int variable

int num = 9999;


// convert int to string using format()

String str = String.format("%d", num);

System.out.println(str); // 9999

Here, we have used the format() method to format the specified int variable into a string. To learn more about
formatting string, visit Java String format().

105. Java Program to convert int type variables to double


In this program, we will learn to convert the integer (int) variables into the double in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Basic Input and Output

Example 1: Java Program to Convert int to double using Typecasting

class Main {

public static void main(String[] args) {

// create int variables

int a =33;

int b = 29;

// convert int into double

// using typecasting

double c = a;

double d = b;

System.out.println(c); // 33.0

System.out.println(d); // 29.0
}

In the above example, we have int type variables a and b. Notice the line,

double c = a;

Here, the int type variable is automatically converted into double. It is because double is a higher data type (data
type with larger size) and int is a lower data type (data type with smaller

size).

Hence, there will be no loss in data while converting from int to double. This is called widening typecasting. To
learn more, visit Java Typecasting.

Example 2: Convert int to object of Double using valueOf()

We can also convert the int type variable into an object of the Double class. For example,

class Main {

public static void main(String[] args) {

// create int variables

int a = 332;

// convert to an object of Double

// using valueOf()

Double obj = Double.valueOf(a);

System.out.println(obj); // 332.0

In the above example, we have used the Double.valueOf() method to convert the variable a into an object of
Double.
Here, Double is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

106. Java Program to convert double type variables to int


In this program, we will learn to convert the double variables into the integer (int) in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Example 1: Java Program to Convert double to int using Typecasting

class Main {

public static void main(String[] args) {

// create double variables

double a = 23.78D;

double b = 52.11D;

// convert double into int

// using typecasting

int c = (int)a;

int d = (int)b;

System.out.println(c); // 23

System.out.println(d); // 52

In the above example, we have double type variables a and b. Notice the line,

int c = (int)a;

Here, the higher data type double is converted into a lower data type int. Hence, we need to explicitly use int
inside the bracket.
This is called narrowing typecasting. To learn more, visit Java Typecasting.

Note: This process works when the value of double is less than or equal to the maximum value of int
(2147483647). Otherwise, there will be a loss in data.

Example 2: Convert double to int using Math.round()

We can also convert the double type variable into int using the Math.round() method. For example,

class Main {

public static void main(String[] args) {

// create double variables

double a = 99.99D;

double b = 52.11D;

// convert double into int

// using typecasting

int c = (int)Math.round(a);

int d = (int)Math.round(b);

System.out.println(c); // 100

System.out.println(d); // 52

In the above example, we have created two double variables named a and b. Notice the line,

int c = (int)Math.round(a);

Here,
Math.round(a) - converts the decimal value into long value

(int) - converts the long value into int using typecasting

The Math.round() method rounds the decimal value to the closest long value. To learn more, visit the Java Math
round().

Example 3: Java Program to Convert Double to int

We can also convert an instance of Double class to int using the intValue() method. For example,

class Main {

public static void main(String[] args) {

// create an instance of Double

Double obj = 78.6;

// convert obj to int

// using intValue()

int num = obj.intValue();

// print the int value

System.out.println(num); // 78

Here, we have used the intValue() method to convert the object of Double to int.

The Double is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

107. Java Program to convert string variables to double


In this tutorial, we will learn to convert the string variables into double in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types

Java String

Example 1: Java Program to Convert string to double using parseDouble()

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "23";

String str2 = "456.6";

// convert string to double

// using parseDouble()

double num1 = Double.parseDouble(str1);

double num2 = Double.parseDouble(str2);

// print double values

System.out.println(num1); // 23.0

System.out.println(num2); // 456.6

In the above example, we have used the parseDouble() method of the Double class to convert the string
variables into double.

Here, Double is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

Note: The string variables should represent the number value. Otherwise, the compiler will throw an exception.
For example,

class Main {

public static void main(String[] args) {


// create a string variable

String str1 = "Programiz";

// convert string to double

// using parseDouble()

double num1 = Double.parseDouble(str1);

// print double values

System.out.println(num1); // throws NumberFormatException

Example 2: Java Program to Convert string to double using valueOf()

We can also convert the string variables into a double using the valueOf() method. For example,

class Main {

public static void main(String[] args) {

// create string variables

String str1 = "6143";

String str2 = "21312";

// convert String to double

// using valueOf()

double num1 = Double.valueOf(str1);

double num2 = Double.valueOf(str2);

// print double values

System.out.println(num1); // 6143.0

System.out.println(num2); // 21312.0

}
}

In the above example, the valueOf() method of Double class converts the string values into the double.

Here, the valueOf() method actually returns an object of the Double class. However, the object is automatically
converted into the primitive type. This is called unboxing in Java. To learn more,

visit Java autoboxing and unboxing.

That is,

// valueOf() returns object of Double

// object is converted into double

double num1 = Double obj = Double.valueOf(str1);

Example 3: Java Program to Convert a String containing comma to double

class Main {

public static void main(String[] args) {

// create string variables

String str = "614,33";

// replace the , with .

str = str.replace(",", ".");

// convert String to double

// using valueOf()

double value = Double.parseDouble(str);

// print double value

System.out.println(value); // 614.33

}
}

In the above example, we have created a string named str. Notice the line,

str = str.replace(",", ".");

Here, the replace() method replaces the comma present in the string with the dot character. To learn more
about replacing the character, visit Java String replace().

We then used the parseDouble() method to convert the string into double.

108. Java Program to convert double type variables to string


In this tutorial, we will learn to convert double variables into the string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java String

Example 1: Java Program to Convert double to string using valueOf()

class Main {

public static void main(String[] args) {

// create double variable

double num1 = 36.33;

double num2 = 99.99;

// convert double to string

// using valueOf()

String str1 = String.valueOf(num1);

String str2 = String.valueOf(num2);

// print string variables

System.out.println(str1); // 36.33
System.out.println(str2); // 99.99

In the above example, we have used the valueOf() method of the String class to convert the double variables
into strings.

Note: This is the most preferred way of converting double variables to string in Java.

Example 2: Java Program to Convert double to string using toString()

We can also convert the double variables into strings using the toString() method of the Double class. For
example,

class Main {

public static void main(String[] args) {

// create double variables

double num1 = 4.76;

double num2 = 786.56;

// convert double to string

// using toString()

String str1 = Double.toString(num1);

String str2 = Double.toString(num2);

// print string variables

System.out.println(str1); // 4.76

System.out.println(str2); // 786.56

Here, we have used the toString() method of the Double class to convert the double variables into a string.
The Double is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

Example 3: Java Program to Convert double to String using + Operator

class Main {

public static void main(String[] args) {

// create double variables

double num1 = 347.6D;

double num2 = 86.56D;

// convert double to string

// using + sign

String str1 = "" + num1;

String str2 = "" + num2;

// print string variables

System.out.println(str1); // 347.6

System.out.println(str2); // 86.56

Notice the line,

String str1 = "" + num1;

Here, we are using the string concatenation operation to convert a double variable into the string. To learn
more, visit Java String concatenation.

Example 4: Java Program to Convert double to String using format()

class Main {

public static void main(String[] args) {


// create a double variable

double num = 99.99;

// convert double to string using format()

String str = String.format("%f", num);

System.out.println(str); // 99.990000

Here, we have used the format() method to format the specified double variable into a string. To learn more
about formatting string, visit Java String format().

109. Java Program to convert primitive types to objects and vice versa
In this tutorial, we will learn to convert the primitive data types to their corresponding wrapper objects and vice
versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Variables and (Primitive) Data Types

Java Class and Objects

Example 1: Java Program to Convert Primitive Types to Wrapper Objects

class Main {

public static void main(String[] args) {

// create primitive types

int var1 = 5;

double var2 = 5.65;

boolean var3 = true;

//converts into wrapper objects


Integer obj1 = Integer.valueOf(var1);

Double obj2 = Double.valueOf(var2);

Boolean obj3 = Boolean.valueOf(var3);

// checks if obj are objects of

// corresponding wrapper class

if(obj1 instanceof Integer) {

System.out.println("An object of Integer is created.");

if(obj2 instanceof Double) {

System.out.println("An object of Double is created.");

if(obj3 instanceof Boolean) {

System.out.println("An object of Boolean is created");

Output

An object of Integer is created.

An object of Double is created.

An object of Boolean is created.

In the above example, we have created variables of primitive types (int, double, and boolean). Here, we have
used the valueOf() method of the Wrapper class (Integer, Double, and Boolean) to

convert the primitive types to the objects.

To learn about wrapper classes in Java, visit Java Wrapper Class.


Example 2: Java Program to Convert Wrapper Objects to Primitive Types

class Main {

public static void main(String[] args) {

// creates objects of wrapper class

Integer obj1 = Integer.valueOf(23);

Double obj2 = Double.valueOf(5.55);

Boolean obj3 = Boolean.valueOf(true);

// converts into primitive types

int var1 = obj1.intValue();

double var2 = obj2.doubleValue();

boolean var3 = obj3.booleanValue();

// print the primitive values

System.out.println("The value of int variable: " + var1);

System.out.println("The value of double variable: " + var2);

System.out.println("The value of boolean variable: " + var3);

Output

The value of int variable: 23

The value of double variable: 5.55

The value of boolean variable: true

In the above example, we have created objects of Wrapper class (Integer, Double, and Boolean).

We then change the objects into corresponding primitive types (int, double, and boolean) using the intValue(),
doubleValue(), and booleanValue() methods respectively.
Note: The Java compiler automatically converts the primitive types into corresponding objects and vice versa.
This process is known as autoboxing and unboxing. To learn more, visit Java autoboxing

and unboxing.

110. Java Program to Implement Bubble Sort algorithm


In this example, we will learn to execute bubble sort algorithm in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java for Loop

Java Arrays

Example: Java Program to Implement Bubble Sort Algorithm

// import the Class

import java.util.Arrays;

import java.util.Scanner;

class Main {

// create an object of scanner

// to take input from the user

Scanner input = new Scanner(System.in);

// method to perform bubble sort

void bubbleSort(int array[]) {

int size = array.length;

// for ascending or descending sort

System.out.println("Choose Sorting Order:");

System.out.println("1 for Ascending \n2 for Descending");

int sortOrder = input.nextInt();


// run loops two times

// first loop access each element of the array

for (int i = 0; i < size - 1; i++)

// second loop performs the comparison in each iteration

for (int j = 0; j < size - i - 1; j++)

// sort the array in ascending order

if (sortOrder == 1) {

// compares the adjacent element

if (array[j] > array[j + 1]) {

// swap if left element is greater than right

int temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

// sort the array in descending order

else {

// compares the adjacent element

if (array[j] < array[j + 1]) {

// swap if left element is smaller than right

int temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}
}

// driver code

public static void main(String args[]) {

// create an array

int[] data = { -2, 45, 0, 11, -9 };

// create an object of Main class

Main bs = new Main();

// call the method bubbleSort using object bs

// pass the array as the method argument

bs.bubbleSort(data);

System.out.println("Sorted Array in Ascending Order:");

// call toString() of Arrays class

// to convert data into the string

System.out.println(Arrays.toString(data));

Output 1

Choose Sorting Order:

1 for Ascending

2 for Descending

Sorted Array:
[-9, -2, 0, 11, 45]

In this case, we have entered 1 as input. Hence, the program sort the array in ascending order.

Output 2

Choose Sorting Order:

1 for Ascending

2 for Descending

Sorted Array:

[45, 11, 0, -2, -9]

In this case, we have entered 2 as input. Hence, the program sort the array in descending order.

If you want to learn more about the bubble sort algorithm, visit Bubble Sort Algorithm.

Note: We have used the Java Scanner Class to take input from the user.

111. Java Program to Implement Quick Sort Algorithm


In this example, we will learn to implement quick sort algorithm in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java for Loop

Java Arrays

Example: Java Program to Implement Quick Sort Algorithm

// Quick sort in Java

import java.util.Arrays;

class Main {
// divide the array on the basis of pivot

int partition(int array[], int low, int high) {

// select last element as pivot

int pivot = array[high];

// initialize the second pointer

int i = (low - 1);

// Put the elements smaller than pivot on the left and

// greater than pivot on the right of pivot

for (int j = low; j < high; j++) {

// compare all elements with pivot

// swap the element greater than pivot

// with element smaller than pivot

// to sort in descending order

// if (array[j] >= pivot)

if (array[j] <= pivot) {

// increase the second pointer if

// smaller element is swapped with greater

i++;

int temp = array[i];

array[i] = array[j];

array[j] = temp;

}
// put pivot in position

// so that element on left are smaller

// element on right are greater than pivot

int temp = array[i + 1];

array[i + 1] = array[high];

array[high] = temp;

return (i + 1);

void quickSort(int array[], int low, int high) {

if (low < high) {

// Select pivot position and put all the elements smaller

// than pivot on the left and greater than pivot on right

int pi = partition(array, low, high);

// sort the elements on the left of the pivot

quickSort(array, low, pi - 1);

// sort the elements on the right of pivot

quickSort(array, pi + 1, high);

// Driver code

public static void main(String args[]) {

// create an unsorted array

int[] data = { 8, 7, 2, 1, 0, 9, 6 };

int size = data.length;


// create an object of the Main class

Main qs = new Main();

// pass the array with the first and last index

qs.quickSort(data, 0, size - 1);

System.out.println("Sorted Array: ");

System.out.println(Arrays.toString(data));

Output 1

Unsorted Array:

[8, 7, 2, 1, 0, 9, 6]

Sorted Array:

[0, 1, 2, 6, 7, 8, 9]

Here, the elements of the array are sorted in ascending order. If we want to sort the elements in descending
order, then inside the for loop of the partition() method, we can change the code as:

// the less than sign is changed to greater than

if (array[j] >= pivot) {

If you want to learn more about the quick sort algorithm, visit Quick Sort Algorithm.

112. Java Program to Implement Merge Sort Algorithm


In this example, we will learn to execute merge sort algorithm in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java while and do...while Loop

Java Arrays
Example: Java Program to Implement Merge Sort Algorithm

import java.util.Arrays;

// Merge sort in Java

class Main {

// Merge two sub arrays L and M into array

void merge(int array[], int p, int q, int r) {

int n1 = q - p + 1;

int n2 = r - q;

int L[] = new int[n1];

int M[] = new int[n2];

// fill the left and right array

for (int i = 0; i < n1; i++)

L[i] = array[p + i];

for (int j = 0; j < n2; j++)

M[j] = array[q + 1 + j];

// Maintain current index of sub-arrays and main array

int i, j, k;

i = 0;

j = 0;

k = p;

// Until we reach either end of either L or M, pick larger among

// elements L and M and place them in the correct position at A[p..r]


// for sorting in descending

// use if(L[i] >= <[j])

while (i < n1 && j < n2) {

if (L[i] <= M[j]) {

array[k] = L[i];

i++;

} else {

array[k] = M[j];

j++;

k++;

// When we run out of elements in either L or M,

// pick up the remaining elements and put in A[p..r]

while (i < n1) {

array[k] = L[i];

i++;

k++;

while (j < n2) {

array[k] = M[j];

j++;

k++;

// Divide the array into two sub arrays, sort them and merge them

void mergeSort(int array[], int left, int right) {


if (left < right) {

// m is the point where the array is divided into two sub arrays

int mid = (left + right) / 2;

// recursive call to each sub arrays

mergeSort(array, left, mid);

mergeSort(array, mid + 1, right);

// Merge the sorted sub arrays

merge(array, left, mid, right);

public static void main(String args[]) {

// created an unsorted array

int[] array = { 6, 5, 12, 10, 9, 1 };

Main ob = new Main();

// call the method mergeSort()

// pass argument: array, first index and last index

ob.mergeSort(array, 0, array.length - 1);

System.out.println("Sorted Array:");

System.out.println(Arrays.toString(array));

Output 1
Unsorted Array:

[6, 5, 12, 10, 9, 1]

Sorted Array:

[1, 5, 6, 9, 10, 12]

Here, the elements of the array are sorted in ascending order. If we want to sort the elements in descending
order, then inside the first while loop of the merge() method, we can change the code

as:

// the less than sign is changed to greater than

if (L[i] >= M[j]) {

If you want to learn more about the merge sort algorithm, visit Merge Sort Algorithm.

113. Java Program to Implement Binary Search Algorithm


In this example, we will learn to implement binary search algorithm in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java while and do...while Loop

Java if, if...else Statement

Java Arrays

Example: Java Program to Implement Binary Search Algorithm

import java.util.Scanner;

// Binary Search in Java

class Main {

int binarySearch(int array[], int element, int low, int high) {

// Repeat until the pointers low and high meet each other

while (low <= high) {


// get index of mid element

int mid = low + (high - low) / 2;

// if element to be searched is the mid element

if (array[mid] == element)

return mid;

// if element is less than mid element

// search only the left side of mid

if (array[mid] < element)

low = mid + 1;

// if element is greater than mid element

// search only the right side of mid

else

high = mid - 1;

return -1;

public static void main(String args[]) {

// create an object of Main class

Main obj = new Main();

// create a sorted array

int[] array = { 3, 4, 5, 6, 7, 8, 9 };

int n = array.length;
// get input from user for element to be searched

Scanner input = new Scanner(System.in);

System.out.println("Enter element to be searched:");

// element to be searched

int element = input.nextInt();

input.close();

// call the binary search method

// pass arguments: array, element, index of first and last element

int result = obj.binarySearch(array, element, 0, n - 1);

if (result == -1)

System.out.println("Not found");

else

System.out.println("Element found at index " + result);

Output 1

Enter element to be searched:

Element found at index 3

Here, we have used the Java Scanner Class to take input from the user. Based on the input from user, we used
the binary search to check if the element is present in the array.

We can also use the recursive call to perform the same task.

int binarySearch(int array[], int element, int low, int high) {


if (high >= low) {

int mid = low + (high - low) / 2;

// check if mid element is searched element

if (array[mid] == element)

return mid;

// Search the left half of mid

if (array[mid] > element)

return binarySearch(array, element, low, mid - 1);

// Search the right half of mid

return binarySearch(array, element, mid + 1, high);

return -1;

Here, the method binarySearch() is calling itself until the element is found or, the if condition fails.

If you want to learn more about the binary search algorithm, visit Binary Search Algorithm.

114. Java Program to Call One Constructor from another


In this example, we will learn how we can call one constructor from another constructor in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Constructors

Java Methods

Example 1: Java program to call one constructor from another

class Main {
int sum;

// first constructor

Main() {

// calling the second constructor

this(5, 2);

// second constructor

Main(int arg1, int arg2) {

// add two value

this.sum = arg1 + arg2;

void display() {

System.out.println("Sum is: " + sum);

// main class

public static void main(String[] args) {

// call the first constructor

Main obj = new Main();

// call display method

obj.display();

Output
Sum is: 7

In the above example, we have created a class named Main. Here, you have created two constructors inside the
Main class.

Main() {..}

Main(int arg1, int arg2) {...}

Inside the first constructor, we have used this keyword to call the second constructor.

this(5, 2);

Here, the second constructor is called from the first constructor by passing arguments 5 and 2.

Note: The line inside a constructor that calls another constructor should be the first line of the constructor. That
is, this(5, 2) should be the first line of Main().

Example 2: Call the constructor of the superclass from the constructor of the child class

We can also call the constructor of the superclass from the constructor of child class using super().

// superclass

class Languages {

// constructor of the superclass

Languages(int version1, int version2) {

if (version1 > version2) {

System.out.println("The latest version is: " + version1);

else {
System.out.println("The latest version is: " + version2);

// child class

class Main extends Languages {

// constructor of the child class

Main() {

// calling the constructor of super class

super(11, 8);

// main method

public static void main(String[] args) {

// call the first constructor

Main obj = new Main();

Output

The latest version is: 11

In the above example, we have created a superclass named Languages and a subclass Main. Inside the
constructor of the Main class, notice the line,

super(11, 8);
Here, we are calling the constructor of the superclass (i.e. Languages(int version1, int version2)) from the
constructor of the subclass (Main()).

115. Java Program to implement private constructors


In this example, we will learn to implement private constructors in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Constructors

Java Singleton

Example 1: Java program to create a private constructor

class Test {

// create private constructor

private Test () {

System.out.println("This is a private constructor.");

// create a public static method

public static void instanceMethod() {

// create an instance of Test class

Test obj = new Test();

class Main {

public static void main(String[] args) {


// call the instanceMethod()

Test.instanceMethod();

Output

This is a private constructor.

In the above example, we have created a private constructor of the Test class. Hence, we cannot create an
object of the Test class outside of the class.

This is why we have created a public static method named instanceMethod() inside the class that is used to
create an object of the Test class. And from the Main class, we call the method using the

class name.

Example 2: Java Singleton design using a private constructor

The Java Singleton design pattern ensures that there should be only one instance of a class. To achieve this we
use the private constructor.

class Language {

// create a public static variable of class type

private static Language language;

// private constructor

private Language() {

System.out.println("Inside Private Constructor");

// public static method

public static Language getInstance() {


// create object if it's not already created

if(language == null) {

language = new Language();

// returns the singleton object

return language;

public void display() {

System.out.println("Singleton Pattern is achieved");

class Main {

public static void main(String[] args) {

Language db1;

// call the getInstance method

db1= Language.getInstance();

db1.display();

Output

Inside Private Constructor

Singleton Pattern is achieved

In the above example, we have created a class named Languages. The class contains,
language - class type private variable

Language() - private constructor

getInstance() - public static class type method

display() - public method

Since the constructor is private, we cannot create objects of Language from the outer class. Hence, we have
created an object of the class inside the getInstance() method.

However, we have set the condition in such a way that only one object is created. And, the method returns the
object.

Notice the line,

db1 = Language.getInstance();

Here,

db1 is a variable of Language type

Language.getInstance() - calls the method getInstance()

Since, getInstance() returns the object of the Language class, the db1 variable is assigned with the returned
object.

Finally, we have called the display() method using the object.

116. Java Program to pass lambda expression as a method argument


In this example, we will learn to pass lambda expression as the method argument in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Lambda Expressions

Java ArrayList Class

Java Methods

Example 1: Define lambda expressions as method parameters


import java.util.ArrayList;

class Main {

public static void main(String[] args) {

// create an ArrayList

ArrayList<String> languages = new ArrayList<>();

// add elements to the ArrayList

languages.add("java");

languages.add("swift");

languages.add("python");

System.out.println("ArrayList: " + languages);

// pass lambda expression as parameter to replaceAll() method

languages.replaceAll(e -> e.toUpperCase());

System.out.println("Updated ArrayList: " + languages);

Output

ArrayList: [java, swift, python]

Updated ArrayList: [JAVA, SWIFT, PYTHON]

In the above example, we have created an arraylist named languages. Notice the line,

languages.replaceAll(e -> e.toUpperCase());

Here, e -> e.toUpperCase() is a lambda expression. It takes all elements of the arraylist and converts them into
uppercase.

Example 2: Pass multiline lambda body as function arguments

import java.util.ArrayList;
import java.util.Arrays;

class Main {

public static void main(String[] args) {

// create an ArrayList

ArrayList<String> languages = new ArrayList<>(Arrays.asList("java", "python"));

System.out.println("ArrayList: " + languages);

// call the foEach() method

// pass lambda as argument fo forEach()

// reverse each element of ArrayList

System.out.print("Reversed ArrayList: ");

languages.forEach((e) -> {

// body of lambda expression

String result = "";

for (int i = e.length()-1; i >= 0 ; i--)

result += e.charAt(i);

System.out.print(result + ", ");

});

Output

ArrayList: [java, python]

Reversed ArrayList: avaj, nohtyp,

In the above example, we have created an arraylist languages. Notice the line,
languages.forEach((e) -> {

// body of lambda expression

String result = "";

for (int i = e.length()-1; i >= 0 ; i--)

result += e.charAt(i);

System.out.print(result + ", ");

});

Here, we are passing lambda expression as an argument to the ArrayList forEach() method. The lambda
expression will reverse each element of the arraylist.

117. Java Program to pass methods as arguments to other methods


In this example, we will learn to pass methods as arguments to other methods in Java

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Class and Objects

Example 1: Java program to pass method as a parameter to other method

class Main {

// calculate the sum

public int add(int a, int b) {

// calculate sum

int sum = a + b;

return sum;

// calculate the square

public void square(int num) {


int result = num * num;

System.out.println(result); // prints 576

public static void main(String[] args) {

Main obj = new Main();

// call the square() method

// passing add() as parameter

obj.square(obj.add(15, 9));

In the above example, we have created two methods named square() and add(). Notice the line,

obj.square(obj.add(15, 9));

Here, we are calling the square() method. The square() method takes the method add() as its argument.

With the introduction lambda expression, now passing methods as arguments has been made easy in Java. To
learn more, visit Passing Lambda Expression as method argument in Java.

118. Java Program to Calculate the Execution Time of Methods


In this example, we will learn to calculate the execution time of normal methods and recursive methods in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Recursion

Example 1: Java Program to calculate the method execution time

class Main {
// create a method

public void display() {

System.out.println("Calculating Method execution time:");

// main method

public static void main(String[] args) {

// create an object of the Main class

Main obj = new Main();

// get the start time

long start = System.nanoTime();

// call the method

obj.display();

// get the end time

long end = System.nanoTime();

// execution time

long execution = end - start;

System.out.println("Execution time: " + execution + " nanoseconds");

Output

Calculating Method execution time:

Execution time: 656100 nanoseconds


In the above example, we have created a method named display(). The method prints a statement to the
console. The program calculates the execution time of the method display().

Here, we have used the method nanoTime() of the System class. The nanoTime() method returns the current
value of the running JVM in nanoseconds.

Example 2: Calculate the execution time of Recursive method

class Main {

// create a recursive method

public int factorial( int n ) {

if (n != 0) // termination condition

return n * factorial(n-1); // recursive call

else

return 1;

// main method

public static void main(String[] args) {

// create object of Main class

Main obj = new Main();

// get the start time

long start = System.nanoTime();

// call the method

obj.factorial(128);

// get the end time

long end = System.nanoTime();


// execution time in seconds

long execution = (end - start);

System.out.println("Execution time of Recursive Method is");

System.out.println(execution + " nanoseconds");

Output

Execution time of Recursive Method is

18600 nanoseconds

In the above example, we are calculating the execution time of recursive method named factorial().

119. Java Program to Convert a String into the InputStream


In this program, we will learn to convert a string to an inputstream in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java InputStream Class

Java ByteArrayInputStream Class

Example: Java Program to convert String to InputStream

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.nio.charset.StandardCharsets;

public class Main {

public static void main(String args[]) {

// Creates a string

String name = "Programiz";


System.out.println("String is: " + name);

try {

InputStream stream = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8));

System.out.println("InputStream: " + stream);

// Returns the available number of bytes

System.out.println("Available bytes at the beginning: " + stream.available());

// Reads 3 bytes from the stream stream

stream.read();

stream.read();

stream.read();

// After reading 3 bytes

// Returns the available number of bytes

System.out.println("Available bytes at the end: " + stream.available());

stream.close();

catch (Exception e) {

e.getStackTrace();

Output

String is: Programiz


InputStream: java.io.ByteArrayInputStream@5479e3f

Available bytes at the beginning: 9

Available bytes at the end: 6

In the above example, we have created a string named name. Here, we have are converting the string into the
input stream named stream.

The getBytes() method converts the string into bytes. To learn more, visit Java String getBytes()

120. Java Program to Convert the InputStream into Byte Array


In this example, we will learn to convert an input stream into the byte array in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java InputStream Class

Java ByteArrayInputStream Class

Java ByteArrayOutputStream Class

Example 1: Java Program to Convert InputStream to Byte Array

import java.io.InputStream;

import java.util.Arrays;

import java.io.ByteArrayInputStream;

public class Main {

public static void main(String args[]) {

try {

// create an input stream

byte[] input = {1, 2, 3, 4};

InputStream stream = new ByteArrayInputStream(input);


System.out.println("Input Stream: " + stream);

// convert the input stream to byte array

byte[] array = stream.readAllBytes();

System.out.println("Byte Array: " + Arrays.toString(array));

stream.close();

catch (Exception e) {

e.getStackTrace();

Output

Input Stream: java.io.ByteArrayInputStream@27082746

Byte Array: [1, 2, 3, 4]

In the above example, we have created an input stream named stream. Note the line,

byte[] array = stream.readAllBytes();

Here, the readAllBytes() method returns all the data from the stream and stores in the byte array.

Note: We have used the Arrays.toString() method to convert all the entire array into a string.

Example 2: Convert InputStream to Byte Array using Output Stream

import java.io.InputStream;

import java.util.Arrays;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;
public class Main {

public static void main(String args[]) {

try {

// create an input stream

byte[] input = {1, 2, 3, 4};

InputStream stream = new ByteArrayInputStream(input);

System.out.println("Input Stream: " + stream);

// create an output stream

ByteArrayOutputStream output = new ByteArrayOutputStream();

// create a byte array to store input stream

byte[] array = new byte[4];

int i;

// read all data from input stream to array

while ((i = stream.read(array, 0, array.length)) != -1) {

// write all data from array to output

output.write(array, 0, i);

byte[] data = output.toByteArray();

// convert the input stream to byte array

System.out.println("Byte Array: " + Arrays.toString(data));


stream.close();

catch (Exception e) {

e.getStackTrace();

Output

Input Stream: java.io.ByteArrayInputStream@27082746

Byte Array: [1, 2, 3, 4]

In the above example, we have created an input stream from the array input. Notice the expression,

stream.read(array, 0, array.length)

Here, all elements from stream are stored in array, starting from index 0. We then store all elements of array to
the output stream named output.

output.write(array, 0, i)

Finally, we call the toByteArray() method of the ByteArrayOutputStream class, to convert the output stream into
a byte array named data.

121. Java Program to Load File as InputStream


In this example, we will learn to load a file as an input stream using the FileInputStream class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java InputStream Class

Java FileInputStream Class

Example 1: Java Program to Load a Text File as InputStream

import java.io.InputStream;
import java.io.FileInputStream;

public class Main {

public static void main(String args[]) {

try {

// file input.txt is loaded as input stream

// input.txt file contains:

// This is a content of the file input.txt

InputStream input = new FileInputStream("input.txt");

System.out.println("Data in the file: ");

// Reads the first byte

int i = input.read();

while(i != -1) {

System.out.print((char)i);

// Reads next byte from the file

i = input.read();

input.close();

catch(Exception e) {

e.getStackTrace();

}
}

Output

Data in the file:

This is a content of the file input.txt.

In the above example, we have a file named input.txt. The content of the file is

This is a content of the file input.txt.

Here, we used the FileInputStream class to load the input.txt file as input stream. We then used the read()
method to read all the data from the file.

Example 2: Java Program to Load Java File as InputStream

Consider we have a Java file named Test.java,

class Test {

public static void main(String[] args) {

System.out.println("This is Java File");

We can also load this Java file as input stream.

import java.io.InputStream;

import java.io.FileInputStream;

public class Main {

public static void main(String args[]) {

try {
// file Test.java is loaded as input stream

InputStream input = new FileInputStream("Time.java");

System.out.println("Data in the file: ");

// Reads the first byte

int i = input.read();

while(i != -1) {

System.out.print((char)i);

// Reads next byte from the file

i = input.read();

input.close();

catch(Exception e) {

e.getStackTrace();

Output

Data in the file:

class Test {

public static void main(String[] args) {

System.out.println("This is Java File");

}
}

In the above example, we have used the FileInputStream class to load the Java file as an input stream.

122. Java Program to Create File and Write to the File


In this example, we will learn to create files in Java and write some information to the file.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java FileWriter Class

Example 1: Java Program to Create a File

// importing the File class

import java.io.File;

class Main {

public static void main(String[] args) {

// create a file object for the current location

File file = new File("JavaFile.java");

try {

// create a new file with name specified

// by the file object

boolean value = file.createNewFile();

if (value) {

System.out.println("New Java File is created.");

else {

System.out.println("The file already exists.");

}
catch(Exception e) {

e.getStackTrace();

In the above example, we have created a file object named file. The file object is linked with the specified path.

// javaFile.java is equivalent to

// currentdirectory/JavaFile.java

File file = new File("JavaFile.java");

We then use the createNewFile() method of the File class to create new file to the specified path.

Note: If the file JavaFile.java is not already present, then only the new file is created. Otherwise the program
returns The file already exists.

Example 2: Java Program to Write Content to the File

In Java, we can use the FileWriter class to write data to a file. In the previous example, we have created the file
named JavaFile.java. Now let's write a program to the file.

// importing the FileWriter class

import java.io.FileWriter;

class Main {

public static void main(String args[]) {

// creates a multiline string using + operator

// the string is a Java Program

String program = "class JavaFile { " +

"public static void main(String[] args) { " +

"System.out.println(\"This is file\");"+

"}"+
"}";

try {

// Creates a Writer using FileWriter

FileWriter output = new FileWriter("JavaFile.java");

// Writes the program to file

output.write(program);

System.out.println("Data is written to the file.");

// Closes the writer

output.close();

catch (Exception e) {

e.getStackTrace();

In the above example, we have used the FileWriter lass to write the string data to the file Javafile.java.

When you run the program, the file JavaFile.java will includes the data present in the string program.

123. Java Program to Read the Content of a File Line by Line


In this example, we will learn to read a the content of a file using various class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java BufferedInputStream Class

Java FileReader Class

Example 1: Java Program to Read File Using BufferedInputStream

import java.io.BufferedInputStream;
import java.io.FileInputStream;

class Main {

public static void main(String[] args) {

try {

// Creates a FileInputStream

FileInputStream file = new FileInputStream("input.txt");

// Creates a BufferedInputStream

BufferedInputStream input = new BufferedInputStream(file);

// Reads first byte from file

int i = input .read();

while (i != -1) {

System.out.print((char) i);

// Reads next byte from the file

i = input.read();

input.close();

catch (Exception e) {

e.getStackTrace();

Output
First Line

Second Line

Third Line

Fourth Line

Fifth Line

In the above example, we have used the BufferedInputStream Class to read each line from the file named
input.txt.

Note: In order to run this file, you should have a file named input.txt in your current working directory.

Example 2: Java Program to Read File Using BufferedReader

import java.io.FileReader;

import java.io.BufferedReader;

class Main {

public static void main(String[] args) {

// Creates an array of character

char[] array = new char[100];

try {

// Creates a FileReader

FileReader file = new FileReader("input.txt");

// Creates a BufferedReader

BufferedReader input = new BufferedReader(file);

// Reads characters

input.read(array);

System.out.println("Data in the file: ");


System.out.println(array);

// Closes the reader

input.close();

catch(Exception e) {

e.getStackTrace();

Output

Data in the file:

First Line

Second Line

Third Line

Fourth Line

Fifth Line

In the above example, we have used the BufferedReader Class to read the file named input.txt.

Example 3: Java Program to Read File Using Scanner

import java.io.File;

import java.util.Scanner;

class Main {

public static void main(String[] args) {

try {
// create a new file object

File file = new File("input.txt");

// create an object of Scanner

// associated with the file

Scanner sc = new Scanner(file);

// read each line from file and print it

System.out.println("Reading File Using Scanner:");

while(sc.hasNextLine()) {

System.out.println(sc.nextLine());

// close scanner

sc.close();

} catch (Exception e) {

e.getStackTrace();

Output

Reading File Using Scanner:

First Line

Second Line

Third Line

Fourth Line

Fifth Line

In the above example, we have created an object of File class named file. We then created a Scanner object
associated with the file.
Here, we have used the scanner methods

hasNextLine() - returns true if there is next line in the file

nextLine() - returns the entire line from the file

To learn more on scanner, visit Java Scanner.

124. Java Program to Delete File in Java


In this example, we will learn to delete file in using the File and Files class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java if, if...else Statement

Example 1: Java Program to Delete a file using delete()

import java.io.File;

class Main {

public static void main(String[] args) {

// creates a file object

File file = new File("JavaFile.java");

// deletes the file

boolean value = file.delete();

if(value) {

System.out.println("JavaFile.java is successfully deleted.");

else {

System.out.println("File doesn't exit");

}
}

In the above example, we have used the delete() method of the File class to delete the file named JavaFile.java.

Here, if the file is present, then the message JavaFile.java is successfully deleted is shown. Otherwise, File
doesn't exit is shown.

Example 2: Java Program to Delete a file using deleteIfExists()

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

class Main {

public static void main(String[] args) {

try {

// creates a file object

Path path = Paths.get("JavaFile.java");

// deletes the file

boolean value = Files.deleteIfExists(path);

if(value) {

System.out.println("JavaFile.java is successfully deleted.");

else {

System.out.println("File doesn't exit");

} catch (Exception e) {

e.getStackTrace();

}
}

Here, we have used the deleteIfExists() method of java.nio.file.Files class. The method deletes the file if it is
present in the specified path.

Note: java.nio.file is a new package introduced to deal with files in Java.

125. Java Program to Delete Empty and Non-empty Directory


In this example, we will learn to delete an empty directory, a non-empty directory, and a directory with non-
empty subdirectory in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java Recursion

Example 1: Java Program to delete an empty directory

import java.io.File;

class Main {

public static void main(String[] args) {

try {

// create a new file object

File directory = new File("Directory");

// delete the directory

boolean result = directory.delete();

if(result) {

System.out.println("Directory Deleted");

else {
System.out.println("Directory not Found");

} catch (Exception e) {

e.getStackTrace();

In the above example, we have used the delete() method of the File class to delete the directory named
Directory.

Here, if the directory is present, then the message Directory Deleted is shown. Otherwise, Directory not Found is
shown.

Example 2: Delete a non-empty directory

In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can
delete the directory.

import java.io.File;

class Main {

public static void main(String[] args) {

try {

// create a new file object

File directory = new File("Directory");

// list all the files in an array

File[] files = directory.listFiles();

// delete each file from the directory


for(File file : files) {

System.out.println(file + " deleted.");

file.delete();

// delete the directory

if(directory.delete()) {

System.out.println("Directory Deleted");

else {

System.out.println("Directory not Found");

} catch (Exception e) {

e.getStackTrace();

In the above example, we have used the for-each loop to delete all the files present in the directory. Once, all
files are deleted, we used the delete() method to delete the directory.

Example 3: Delete non-empty directory recursively

import java.io.File;

class Main {

public static void deleteDirectory(File directory) {

// if the file is directory or not

if(directory.isDirectory()) {
File[] files = directory.listFiles();

// if the directory contains any file

if(files != null) {

for(File file : files) {

// recursive call if the subdirectory is non-empty

deleteDirectory(file);

if(directory.delete()) {

System.out.println(directory + " is deleted");

else {

System.out.println("Directory not deleted");

public static void main(String[] args) {

try {

// create a new file object

File directory = new File("Directory");

Main.deleteDirectory(directory);

} catch (Exception e) {

e.getStackTrace();

}
}

Here, suppose we have a non-empty directory named Directory. The Directory contains 2 files named file1.txt
and file2.txt and a non-empty subdirectory named Subdirectory. Again, the Subdirectory

contains a file named file11.txt.

Now, when we run the program, we will get the following output.

Directory\file1.txt is deleted

Directory\file2.txt is deleted

Directory\Subdirectory\file11.txt is deleted

Directory\Subdirectory is deleted

Directory is deleted

Here, first 2 files are deleted, then the recursive function delete the files inside the Subdirectory. Once, the
Subdirectory is empty, it is deleted. And, finally the Directory is deleted.

126. Java Program to Get the File Extension


In this example, we will learn to get the file extension in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java String lastIndexOf()

Java String substring()

Example 1: Java Program to get the file extension

import java.io.File;

class Main {

public static void main(String[] args) {

File file = new File("Test.java");


// convert the file name into string

String fileName = file.toString();

int index = fileName.lastIndexOf('.');

if(index > 0) {

String extension = fileName.substring(index + 1);

System.out.println("File extension is " + extension);

In the above example,

file.toString() - Converts the File object into a string.

fileName.lastIndexOf('.') - Returns the last occurrence of character. Since all file extension starts with '.', we use
the character '.'.

fileName.substring() - Returns the string after character '.'.

Example 2: Get the file extension of all files present in a directory

Now, suppose we want to get the file extension of all the files present in a directory. We can use the above
process in the loop.

import java.io.File;

class Main {

public static void main(String[] args) {

File directory = new File("Directory");

// list all files present in the directory

File[] files = directory.listFiles();


System.out.println("Files\t\t\tExtension");

for(File file : files) {

// convert the file name into string

String fileName = file.toString();

int index = fileName.lastIndexOf('.');

if(index > 0) {

String extension = fileName.substring(index + 1);

System.out.println(fileName + "\t" + extension);

Output

Files Extension

Directory\file1.txt txt

Directory\file2.svg svg

Directory\file3.java java

Directory\file4.py py

Directory\file5.html html

Note: The output of the program depends on the directory you use and the files in the directory.

If you are using the Gauva Library, you can directly use the getFileExtension() method to get the file extension.
For example,

String fileName = "Test.java";

String extension = Files.getFileExtension(fileName);


And, also the Apache Commons IO provides the FilenameUtils class provides the getExtension method to get the
extension of the file.

String extension = FilenameUtils.getExtension("file.py") // returns py

127. Java Program to Get the name of the file from the absolute path
In this example, we will learn to get the name of the file from the absolute path in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java File Class

Java String

Example 1: Get file name from the absolute path using getName()

import java.io.File;

class Main {

public static void main(String[] args) {

// link to file Test.class

File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class");

// get file name using getName()

String fileName = file.getName();

System.out.println("File Name: " + fileName);

Output

File Name: Test.class


In the above example, we have used the getName() method of the File class to get the name of the file.

Example 2: Get the file name using string methods

We can also get the name of the file from its absolute path using the string methods.

import java.io.File;

class Main {

public static void main(String[] args) {

File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class");

// convert the file into the string

String stringFile = file.toString();

int index = stringFile.lastIndexOf('\\');

if(index > 0) {

String fileName = stringFile.substring(index + 1);

System.out.println("File Name: " + fileName);

Output

File Name: Test.class

In the above example,

file.toString() - Converts the File object into the string.

stringFile.lastIndexOf() - Returns the last occurrence of character '\\' in stringFile. To learn more, visit Java String
lastindexOf().
stringFile.substring(index + 1) - Returns all the substring after position index + 1. To learn more, visit Java String
substring().

128. Java Program to Get the relative path from two absolute paths
In this example, we will learn to get the relative path from two absolute paths in Java using String methods, URI
class, and java.nio.file package.

Example 1: Get a relative path from two absolute paths using URI class

import java.io.File;

import java.net.URI;

class Main {

public static void main(String[] args) {

try {

// Two absolute paths

File absolutePath1 = new File("C:\\Users\\Desktop\\Programiz\\Java\\Time.java");

System.out.println("Absolute Path1: " + absolutePath1);

File absolutePath2 = new File("C:\\Users\\Desktop");

System.out.println("Absolute Path2: " + absolutePath2);

// convert the absolute path to URI

URI path1 = absolutePath1.toURI();

URI path2 = absolutePath2.toURI();

// create a relative path from the two paths

URI relativePath = path2.relativize(path1);

// convert the URI to string

String path = relativePath.getPath();


System.out.println("Relative Path: " + path);

} catch (Exception e) {

e.getStackTrace();

Output

Absolute Path1: C:\Users\Desktop\Programiz\Java\Time.java

Absolute Path2: C:\Users\Desktop

Relative Path: Programiz/Java/Time.java

In the above example, we have two absolute paths named absolutePath1 and absolutePath2. We have used the
URI class to convert the absolute paths into the relative path.

toURI() - converts the File object to a Uri

relativize() - extracts the relative path by comparing two absolute paths with one another

getPath() - converts the Uri into a string

Recommended Reading:

Java File

Java URI class

Example 2: Get a relative path from two absolute path using String methods

import java.io.File;

class Main {

public static void main(String[] args) {

// Create file objects

File file1 = new File("C:\\Users\\Desktop\\Programiz\\Java\\Time.java");


File file2 = new File("C:\\Users\\Desktop");

// convert file objects to string

String absolutePath1 = file1.toString();

System.out.println("Absolute Path1: " + absolutePath1);

String absolutePath2 = file2.toString();

System.out.println("Absolute Path2: " + absolutePath2);

// get the relative path

String relativePath = absolutePath1.substring(absolutePath2.length());

System.out.println("Absolute Path: " + relativePath);

Output

Absolute Path1: C:\Users\Desktop\Programiz\Java\Time.java

Absolute Path2: C:\Users\Desktop

Absolute Path: \Programiz\Java\Time.java

In the above example, we have converted the file paths to strings. Notice the expression,

absolutePath1.substring(absolutePath2.length())

Here, the substring() method returns the part of absolutePath1 starting from index equal to the length of
absolutePath2. That is, the string represented by absolutePath2 is removed from

absolutePath1.

To learn more about how substring works, visit Java String substring().

Example 3: Get a relative path from two absolute paths using java.nio.file package

import java.nio.file.Path;
import java.nio.file.Paths;

class Main {

public static void main(String[] args) {

// Create file objects

Path absolutePath1 = Paths.get("C:\\Users\\Desktop\\Programiz\\Java\\Time.java");

Path absolutePath2 = Paths.get("C:\\Users\\Desktop");

// convert the absolute path to relative path

Path relativePath = absolutePath2.relativize(absolutePath1);

System.out.println("Relative Path: " + relativePath);

Output

Relative Path: Programiz\Java\Time.java

In the above example, we have used the relativize() method of the Path interface to get a relative path from two
absolute paths.

Recommended Readings:

Java Paths Class

Java Path Interface

129. Java Program to Count number of lines present in the file


In this example, we will learn to count the number of lines present in a file in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java File Class

Java Scanner Class

Example 1: Java program to count the number of lines in a file using Scanner class

import java.io.File;

import java.util.Scanner;

class Main {

public static void main(String[] args) {

int count = 0;

try {

// create a new file object

File file = new File("input.txt");

// create an object of Scanner

// associated with the file

Scanner sc = new Scanner(file);

// read each line and

// count number of lines

while(sc.hasNextLine()) {

sc.nextLine();

count++;

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

// close scanner

sc.close();

} catch (Exception e) {
e.getStackTrace();

In the above example, we have used the nextLine() method of the Scanner class to access each line of the file.
Here, depending on the number of lines the file input.txt file contains, the program

shows the output.

In this case, we have a file name input.txt with the following content

130. Java Program to Check if a string is a valid shuffle of two strings


In this example, we will check if a string is the valid shuffle of two other strings in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java while and do...while Loop

Example: Check if a string is a valid shuffle of two other strings

class Main {

// check if result string is valid shuffle of string first and second

static boolean shuffleCheck(String first, String second, String result) {

// check length of result is same as

// sum of result of first and second

if(first.length() + second.length() != result.length()) {

return false;

// variables to track each character of 3 strings

int i = 0, j = 0, k = 0;
// iterate through all characters of result

while (k != result.length()) {

// check if first character of result matches with first character of first string

if (i < first.length() && first.charAt(i) == result.charAt(k))

i++;

// check if first character of result matches the first character of second string

else if (j < second.length() && second.charAt(j) == result.charAt(k))

j++;

// if the character doesn't match

else {

return false;

// access next character of result

k++;

// after accessing all characters of result

// if either first or second has some characters left

if(i < first.length() || j < second.length()) {

return false;

return true;

}
public static void main(String[] args) {

String first = "XY";

String second = "12";

String[] results = {"1XY2", "Y12X"};

// call the method to check if result string is

// shuffle of the string first and second

for (String result : results) {

if (shuffleCheck(first, second, result) == true) {

System.out.println(result + " is a valid shuffle of " + first + " and " + second);

else {

System.out.println(result + " is not a valid shuffle of " + first + " and " + second);

Output

1XY2 is a valid shuffle of XY and 12

Y12X is not a valid shuffle of XY and 12

In the above example, we have a string array named results. It contains two strings: 1XY2 and Y12X. We are
checking if these two strings are valid shuffle of strings first(XY) and second(12).

Here, the program says 1XY2 is a valid shuffle of XY and 12. However, Y12X is not a valid shuffle.

This is because Y12X has altered the order of string XY. Here, Y is used before X. Hence, to be a valid shuffle, the
order of string should be maintained.

131. Java Program to Implement the graph data structure


In this example, we will implement the graph data structure in Java.
To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Implement Graph Data Structure

class Graph {

// inner class

// to keep track of edges

class Edge {

int src, dest;

// number of vertices and edges

int vertices, edges;

// array to store all edges

Edge[] edge;

Graph(int vertices, int edges) {

this.vertices = vertices;

this.edges = edges;

// initialize the edge array

edge = new Edge[edges];

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

// each element of the edge array

// is an object of Edge type

edge[i] = new Edge();


}

public static void main(String[] args) {

// create an object of Graph class

int noVertices = 5;

int noEdges = 8;

Graph g = new Graph(noVertices, noEdges);

// create graph

g.edge[0].src = 1; // edge 1---2

g.edge[0].dest = 2;

g.edge[1].src = 1; // edge 1---3

g.edge[1].dest = 3;

g.edge[2].src = 1; // edge 1---4

g.edge[2].dest = 4;

g.edge[3].src = 2; // edge 2---4

g.edge[3].dest = 4;

g.edge[4].src = 2; // edge 2---5

g.edge[4].dest = 5;

g.edge[5].src = 3; // edge 3---4

g.edge[5].dest = 4;

g.edge[6].src = 3; // edge 3---5


g.edge[6].dest = 5;

g.edge[7].src = 4; // edge 4---5

g.edge[7].dest = 5;

// print graph

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

System.out.println(g.edge[i].src + " - " + g.edge[i].dest);

Output

1-2

1-3

1-4

2-4

2-5

3-4

3-5

4-5

Graph data structure in Java with 5 nodes

Graph Output

In the above example, we have implemented the graph data structure in Java. To learn more about graphs, visit
Graph Data Structure.

132. Java Program to Check Whether a Number is Positive or Negative


In this program, you'll learn to check whether a given number is positive or negative. This is done by using a if
else statement in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java if, if...else Statement

Java Operators

Example: Check if a Number is Positive or Negative using if else

public class PositiveNegative {

public static void main(String[] args) {

double number = 12.3;

// true if number is less than 0

if (number < 0.0)

System.out.println(number + " is a negative number.");

// true if number is greater than 0

else if ( number > 0.0)

System.out.println(number + " is a positive number.");

// if both test expression is evaluated to false

else

System.out.println(number + " is 0.");

Output

12.3 is a positive number.

If you change the value of number to a negative number (say -12.3), the output will be:

-12.3 is a negative number.

In the above program, it is quite clear how the variable number is checked to be positive or negative, by
comparing it to 0.
If you're not sure, here is the breakdown:

If a number is greater than zero, it is a positive number.

If a number is less than zero, it is a negative number.

If a number equals to zero, it is zero.

133. Java Program to Differentiate String == operator and equals() method


In this tutorial, we will learn to differentiate the string == operator and equals() method in Java

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java String equals()

Example 1: Java program to differentiate == and equals()

class Main {

public static void main(String[] args) {

String name1 = new String("Programiz");

String name2 = new String("Programiz");

System.out.println("Check if two strings are equal");

// check if two strings are equal

// using == operator

boolean result1 = (name1 == name2);

System.out.println("Using == operator: " + result1);

// using equals() method


boolean result2 = name1.equals(name2);

System.out.println("Using equals(): " + result2);

Output

Check if two strings are equal

Using == operator: false

Using equals(): true

In the above example, we have used the == operator and equals() method to check if two strings are equal.
Here,

== checks if the reference to string objects are equal or not. Here, name1 and name2 are two different
references. Hence, it returns false.

equals() checks if the content of the string object are equal. Here, the content of both the objects name1 and
name2 is the same Programiz. Hence, it returns true.

Example 2: Differentiate == and equals()

class Main {

public static void main(String[] args) {

String name1 = new String("Programiz");

String name2 = name1;

System.out.println("Check if two strings are equal");

// check if two strings are equal

// using == operator

boolean result1 = (name1 == name2);

System.out.println("Using == operator: " + result1);


// using equals() method

boolean result2 = name1.equals(name2);

System.out.println("Using equals(): " + result2);

Output

Check if two strings are equal

Using == operator: true

Using equals(): true

Here, name1 and name2 both are refering to the same object. Hence, name1 == name2 returns true.

134. Java Program to Implement switch statement on strings


In this example, we will learn to implement the switch statement on strings in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java switch Statement

Java String

Example: Implement the switch statement on Strings

// Java Program to implement String on switch statements in Java

class Main {

public static void main(String[] args) {

// create a string

String language = "Java";

switch(language) {
case "Java":

System.out.println(language + " is famous for enterprise applications.");

break;

case "JavaScript":

System.out.println(language + " is famous for frontend and backend.");

break;

case "Python":

System.out.println(language + " is famous for ML and AI.");

break;

default:

System.out.println(language + " not found on record.");

break;

Output

Java is famous for enterprise applications.

In the above example, we have implemented the switch statement on Strings. This feature was introduced in
Java 7.

135. Java Program to Calculate simple interest and compound interest


In this example, we will learn to calculate the simple interest and compound interest in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Scanner Class

Java Operators
Example 1: Calculate Simple Interest in Java

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// create an object of Scanner class

Scanner input = new Scanner(System.in);

// take input from users

System.out.print("Enter the principal: ");

double principal = input.nextDouble();

System.out.print("Enter the rate: ");

double rate = input.nextDouble();

rate = rate/100;

System.out.print("Enter the time: ");

double time = input.nextDouble();

double interest = (principal * time * rate) / 100;

System.out.println("Principal: " + principal);

System.out.println("Interest Rate: " + rate);

System.out.println("Time Duration: " + time);

System.out.println("Simple Interest: " + interest);

input.close();

}
Output

Enter the principal: 1000

Enter the rate: 8

Enter the time: 2

Principal: 1000.0

Interest Rate: 8.0

Time Duration: 2.0

Simple Interest: 160.0

In the above example, we have used the Scanner class to take principal, rate, and time as input from the user.
We then use the formula of simple interest to compute the simple interest.

Simple Interest = (Principal * Rate * Time) / 100

Example 2: Calculate Compound Interest

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// create an object of Scanner class

Scanner input = new Scanner(System.in);

// take input from users

System.out.print("Enter the principal: ");

double principal = input.nextDouble();

System.out.print("Enter the rate: ");

double rate = input.nextDouble();

System.out.print("Enter the time: ");


double time = input.nextDouble();

System.out.print("Enter number of times interest is compounded: ");

int number = input.nextInt();

double interest = principal * (Math.pow((1 + rate/100), (time * number))) - principal;

System.out.println("Principal: " + principal);

System.out.println("Interest Rate: " + rate);

System.out.println("Time Duration: " + time);

System.out.println("Number of Time interest Compounded: " + number);

System.out.println("Compound Interest: " + interest);

input.close();

Output

Enter the principal: 1000

Enter the rate: 10

Enter the time: 3

Enter number of times interest is compounded: 1

Principal: 1000.0

Interest Rate: 10.0

Time Duration: 3.0

Number of Time interest Compounded: 1

Compound Interest: 331.00000000000045

In the above example, we have used the formula of compound interest to calculate the compound interest.

Here, we have used the Math.pow() method to calculate the power of the number.
136. Java Program to Implement multiple inheritance
In this example, we will learn to implement multiple inheritance in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Inheritance

Java Interface

Java Class and Objects

When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java
does not support multiple inheritance.

To achieve multiple inheritance in Java, we must use the interface.

Example: Multiple Inheritance in Java

interface Backend {

// abstract class

public void connectServer();

class Frontend {

public void responsive(String str) {

System.out.println(str + " can also be used as frontend.");

// Language extends Frontend class

// Language implements Backend interface

class Language extends Frontend implements Backend {


String language = "Java";

// implement method of interface

public void connectServer() {

System.out.println(language + " can be used as backend language.");

public static void main(String[] args) {

// create object of Language class

Language java = new Language();

java.connectServer();

// call the inherited method of Frontend class

java.responsive(java.language);

Output

Java can be used as backend language.

Java can also be used as frontend.

In the above example, we have created an interface named Backend and a class named Frontend. The class
Language extends the Frontend class and implements the Backend interface.

Multiple inheritance in Java

Multiple Inheritancy in Java

Here, the Language class is inheriting the property of both Backend and Frontend. Hence, we can say it is an
example of multiple inheritance.
137. Java Program to Determine the name and version of the operating
system
In this example, we will learn to get the name and version of operating system in which the program run using
Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java Basic Input and Output

Example: Determine the Operating System

class Main {

public static void main(String[] args) {

// get the name of operating system

String operatingSystem = System.getProperty("os.name");

System.out.println(operatingSystem);

Output

Windows 10

In the above example, we have used the getProperty() method of the System class. Here, we have passed the
os.name key as an argument to the method.

The method returns the property of the system specified by the key.

There are other keys that can be used to get other system properties. For example,

// returns the version of Operating system

// 10.0

System.getProperty("os.version");
Here, the key os.version returns the version of the operating system.

To learn more, visit the Java System Class.

138. Java Program to Check if two of three boolean variables are true
In this example, we will learn to check if two of the three boolean variables are true in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Ternary Operator

Example: Check if two of the three boolean variables are true

// Java Program to check if 2 variables

// among the 3 variables are true

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// create 3 boolean variables

boolean first;

boolean second;

boolean third;

boolean result;

// get boolean input from the user

Scanner input = new Scanner(System.in);

System.out.print("Enter first boolean value: ");

first = input.nextBoolean();

System.out.print("Enter second boolean value: ");


second = input.nextBoolean();

System.out.print("Enter third boolean value: ");

third = input.nextBoolean();

// check if two are true

if(first) {

// if first is true

// and one of the second and third is true

// result will be true

result = second || third;

else {

// if first is false

// both the second and third should be true

// so result will be true

result = second && third;

if(result) {

System.out.println("Two boolean variables are true.");

else {

System.out.println("Two boolean variables are not true.");

input.close();

}
}

Output 1

Enter first boolean value: true

Enter second boolean value: false

Enter third boolean value: true

Two boolean variables are true.

Output 2

Enter first boolean value: false

Enter second boolean value: true

Enter third boolean value: false

Two boolean variables are not true.

In the above example, we have three boolean variables named first, second, and third. Here, we have checked if
two of the boolean variables among the three are true or not.

We have used the if...else statement to check if two boolean variables are true or not.

if(first) {

result = second || third;

else {

result = second && third;

Here, instead of the if...else statement, we can also use the ternary operator.

result = first ? second || third : second && third;

139. Java Program to Iterate over enum


In this example, we will learn to iterate over the elements of enum in Java by converting the enum into an array
and enumset.
To understand this example, you should have the knowledge of the following Java programming topics:

Java enums

Java EnumSet

Example 1: Loop through enum using forEach loop

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

class Main {

public static void main(String[] args) {

System.out.println("Access each enum constants");

// use foreach loop to access each value of enum

for(Size size : Size.values()) {

System.out.print(size + ", ");

Output 1

Access each enum constants

SMALL, MEDIUM, LARGE, EXTRALARGE,

In the above example, we have an enum named Size. Notice the expression,

Size.values()
Here, the values() method converts the enum constants in an array of the Size type. We then used the forEach
loop to access each element of the enum.

Example 2: Loop through enum using EnumSet Class

import java.util.EnumSet;

// create an enum

enum Size {

SMALL, MEDIUM, LARGE, EXTRALARGE

class Main {

public static void main(String[] args) {

// create an EnumSet class

// convert the enum Size into the enumset

EnumSet<Size> enumSet = EnumSet.allOf(Size.class);

System.out.println("Elements of EnumSet: ");

// loop through the EnumSet class

for (Size constant : enumSet) {

System.out.print(constant + ", ");

Output

Elements of EnumSet:

SMALL, MEDIUM, LARGE, EXTRALARGE,


Here, we have used the allOf() method to create an EnumSet class from the enum Size. We then access each
element of the enumset class using the forEach loop.

140. Java Program to Check the birthday and print Happy Birthday message
In this example, we will learn to check the current day with the birthday and print the Happy Birthday message
in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java if, if...else Statement

Java Basic Input and Output

Example: Check birthday and return Happy Birthday message

import java.time.LocalDate;

import java.time.Month;

public class Main {

public static void main(String args[]) {

// declare variables for birthday

int birthDate = 23;

Month birthMonth = Month.SEPTEMBER;

// get current date

LocalDate currentDate = LocalDate.now();

System.out.println("Todays Date: " + currentDate);

// get current date and month

int date = currentDate.getDayOfMonth();

Month month = currentDate.getMonth();

if(date == birthDate && month == birthMonth) {

System.out.println("HAPPY BIRTHDAY TO YOU !!");


}

else {

System.out.println("Today is not my birthday.");

Output 1

Todays Date: 2020-07-28

HAPPY BIRTHDAY TO YOU !!

In the above example,

LocalDate.now() - returns the current date

getDayOfMonth() - returns the current day

getMonth() - returns the current month

Here, we have used the if...else statement to check if the current date matches the birthdate. If true, the Happy
Birthday message is printed.

141. Java Program to Implement LinkedList


In this example, we will learn to implement the linked list data structure in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java LinkedList

Java Generics

Example 1: Java program to implement LinkedList

class LinkedList {

// create an object of Node class

// represent the head of the linked list

Node head;
// static inner class

static class Node {

int value;

// connect each node to next node

Node next;

Node(int d) {

value = d;

next = null;

public static void main(String[] args) {

// create an object of LinkedList

LinkedList linkedList = new LinkedList();

// assign values to each linked list node

linkedList.head = new Node(1);

Node second = new Node(2);

Node third = new Node(3);

// connect each node of linked list to next node

linkedList.head.next = second;

second.next = third;

// printing node-value

System.out.print("LinkedList: ");
while (linkedList.head != null) {

System.out.print(linkedList.head.value + " ");

linkedList.head = linkedList.head.next;

Output

LinkedList: 1 2 3

In the above example, we have implemented the singly linked list in Java. Here, the linked list consists of 3
nodes.

Each node consists of value and next. The value variable represents the value of the node and the next
represents the link to the next node.

To learn about the working of LinkedList, visit LinkedList Data Structure.

Example 2: Implement LinkedList using LinkedList class

Java provides a built LinkedList class that can be used to implement a linked list.

import java.util.LinkedList;

class Main {

public static void main(String[] args){

// create a linked list using the LinkedList class

LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList

animals.add("Dog");
// add element at the beginning of linked list

animals.addFirst("Cat");

// add element at the end of linked list

animals.addLast("Horse");

System.out.println("LinkedList: " + animals);

// access first element

System.out.println("First Element: " + animals.getFirst());

// access last element

System.out.println("Last Element: " + animals.getLast());

Output

LinkedList: [Cat, Dog, Horse]

First Element: Cat

Last Element: Horse

In the above example, we have used the LinkedList class to implement the linked list in Java. Here, we have used
methods provided by the class to add elements and access elements from the linked

list.

Notice, we have used the angle brackets (<>) while creating the linked list. It represents that the linked list is of
the generic type.

142. Java Program to Implement stack data structure


In this example, we will learn to implement the stack data structure in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java Stack Class

Java Generics

Example 1: Java program to implement Stack

// Stack implementation in Java

class Stack {

// store elements of stack

private int arr[];

// represent top of stack

private int top;

// total capacity of the stack

private int capacity;

// Creating a stack

Stack(int size) {

// initialize the array

// initialize the stack variables

arr = new int[size];

capacity = size;

top = -1;

// push elements to the top of stack

public void push(int x) {

if (isFull()) {

System.out.println("Stack OverFlow");

// terminates the program


System.exit(1);

// insert element on top of stack

System.out.println("Inserting " + x);

arr[++top] = x;

// pop elements from top of stack

public int pop() {

// if stack is empty

// no element to pop

if (isEmpty()) {

System.out.println("STACK EMPTY");

// terminates the program

System.exit(1);

// pop element from top of stack

return arr[top--];

// return size of the stack

public int getSize() {

return top + 1;

// check if the stack is empty

public Boolean isEmpty() {


return top == -1;

// check if the stack is full

public Boolean isFull() {

return top == capacity - 1;

// display elements of stack

public void printStack() {

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

System.out.print(arr[i] + ", ");

public static void main(String[] args) {

Stack stack = new Stack(5);

stack.push(1);

stack.push(2);

stack.push(3);

System.out.print("Stack: ");

stack.printStack();

// remove element from stack

stack.pop();

System.out.println("\nAfter popping out");

stack.printStack();
}

Output

Inserting 1

Inserting 2

Inserting 3

Stack: 1, 2, 3,

After popping out

1, 2,

In the above example, we have implemented the stack data structure in Java.

To learn more, visit Stack Data Structure.

Example 2: Implement stack using Stack class

Java provides a built Stack class that can be used to implement a stack.

import java.util.Stack;

class Main {

public static void main(String[] args) {

// create an object of Stack class

Stack<String> animals= new Stack<>();

// push elements to top of stack

animals.push("Dog");

animals.push("Horse");

animals.push("Cat");
System.out.println("Stack: " + animals);

// pop element from top of stack

animals.pop();

System.out.println("Stack after pop: " + animals);

Output

Stack: [Dog, Horse, Cat]

Stack after pop: [Dog, Horse]

In the above example, we have used the Stack class to implement the stack in Java. Here,

animals.push() - insert elements to top of the stack

animals.pop() - remove element from the top of the stack

Notice, we have used the angle brackets <String> while creating the stack. It represents that the stack is of the
generic type.

143. Java Program to Implement the queue data structure


In this example, we will learn to implement the queue data structure in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Queue Interface

Java Generics

Example 1: Java program to implement Stack

public class Queue {

int SIZE = 5;

int items[] = new int[SIZE];

int front, rear;


Queue() {

front = -1;

rear = -1;

// check if the queue is full

boolean isFull() {

if (front == 0 && rear == SIZE - 1) {

return true;

return false;

// check if the queue is empty

boolean isEmpty() {

if (front == -1)

return true;

else

return false;

// insert elements to the queue

void enQueue(int element) {

// if queue is full

if (isFull()) {

System.out.println("Queue is full");

else {

if (front == -1) {
// mark front denote first element of queue

front = 0;

rear++;

// insert element at the rear

items[rear] = element;

System.out.println("Insert " + element);

// delete element from the queue

int deQueue() {

int element;

// if queue is empty

if (isEmpty()) {

System.out.println("Queue is empty");

return (-1);

else {

// remove element from the front of queue

element = items[front];

// if the queue has only one element

if (front >= rear) {

front = -1;

rear = -1;

else {
// mark next element as the front

front++;

System.out.println( element + " Deleted");

return (element);

// display element of the queue

void display() {

int i;

if (isEmpty()) {

System.out.println("Empty Queue");

else {

// display the front of the queue

System.out.println("\nFront index-> " + front);

// display element of the queue

System.out.println("Items -> ");

for (i = front; i <= rear; i++)

System.out.print(items[i] + " ");

// display the rear of the queue

System.out.println("\nRear index-> " + rear);

public static void main(String[] args) {


// create an object of Queue class

Queue q = new Queue();

// try to delete element from the queue

// currently queue is empty

// so deletion is not possible

q.deQueue();

// insert elements to the queue

for(int i = 1; i < 6; i ++) {

q.enQueue(i);

// 6th element can't be added to queue because queue is full

q.enQueue(6);

q.display();

// deQueue removes element entered first i.e. 1

q.deQueue();

// Now we have just 4 elements

q.display();

Output

Queue is empty

Insert 1
Insert 2

Insert 3

Insert 4

Insert 5

Queue is full

Front index-> 0

Items ->

1 2 3 4 5

Rear index-> 4

1 Deleted

Front index-> 1

Items ->

2 3 4 5

Rear index-> 4

In the above example, we have implemented the queue data structure in Java.

To learn the working about the queue, visit Queue Data Structure.

Example 2: Implement stack using Queue interface

Java provides a built Queue interface that can be used to implement a queue.

import java.util.Queue;

import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// Creating Queue using the LinkedList class

Queue<Integer> numbers = new LinkedList<>();

// enqueue

// insert element at the rear of the queue

numbers.offer(1);

numbers.offer(2);

numbers.offer(3);

System.out.println("Queue: " + numbers);

// dequeue

// delete element from the front of the queue

int removedNumber = numbers.poll();

System.out.println("Removed Element: " + removedNumber);

System.out.println("Queue after deletion: " + numbers);

Output

Queue: [1, 2, 3]

Removed Element: 1

Queue after deletion: [2, 3]

In the above example, we have used the Queue interface to implement the queue in Java. Here, we have used
the LinkedList class that implements the Queue interface.

numbers.offer() - insert elements to the rear of the queue

numbers.poll() - remove an element from the front of the queue

Notice, we have used the angle brackets <Integer> while creating the queue. It represents that the queue is of
the generic type.
We can also use other interfaces and classes instead of Queue and LinkedList. For example,

Deque Interface

ArrayDeque Class

PriorityQueue Class

144. Java Program to Get the middle element of LinkedList in a single


iteration
In this example, we will learn to get the middle element of the linked list in a single iteration in Java.

To understand this example, make sure you first visit the following tutorials,

Java LinkedList Class

LinkedList Data Structure

Example 1: Get the middle element of LinkedList in a single search

class LinkedList {

// create an object of Node class

// represent the head of the linked list

Node head;

// static inner class

static class Node {

int value;

// connect each node to next node

Node next;

Node(int d) {

value = d;

next = null;
}

public static void main(String[] args) {

// create an object of LinkedList

LinkedList linkedList = new LinkedList();

// assign values to each linked list node

linkedList.head = new Node(1);

Node second = new Node(2);

Node third = new Node(3);

// connect each node of linked list to next node

linkedList.head.next = second;

second.next = third;

// print the linked list

Node pointer = linkedList.head;

System.out.print("LinkedList: " );

while (pointer != null) {

System.out.print(pointer.value + " ");

pointer = pointer.next;

// Find the middle element

Node ptr1 = linkedList.head;

Node ptr2 = linkedList.head;

while (ptr1.next != null) {


// increase the ptr1 by 2 and ptr2 by 1

// if ptr1 points to last element

// ptr2 will points to middle element

ptr1 = ptr1.next;

if(ptr1.next !=null) {

ptr1 = ptr1.next;

ptr2 = ptr2.next;

System.out.println("\nMiddle Element: " + ptr2.value);

Output

LinkedList: 1 2 3

Middle Element: 2

In the above example, we have implemented the linked list data structure in Java. We then find the middle
element of the linked list in a single loop. Notice the code,

while (ptr1.next != null) {

// increase the ptr1 by 2 and ptr2 by 1

// if ptr1 points to last element

// ptr2 will points to middle element

ptr1 = ptr1.next;

if(ptr1.next !=null) {

ptr1 = ptr1.next;

ptr2 = ptr2.next;
}

Here, we have two variables ptr1 and ptr2. We use these variables to iterate through the linked list.

In each iteration, the ptr1 will access the two nodes and the ptr2 will access the single node of the linked list.

Now, when the ptr1 reaches the end of the linked list, the ptr2 will be in the middle. In this way, we are able to
get the middle of linked list in a single iteration.

Example 2: Get the middle element of LinkedList using the LinkedList class

import java.util.LinkedList;

class Main {

public static void main(String[] args){

// create a linked list using the LinkedList class

LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList

animals.add("Dog");

animals.addFirst("Cat");

animals.addLast("Horse");

System.out.println("LinkedList: " + animals);

// access middle element

String middle = animals.get(animals.size()/2);

System.out.println("Middle Element: " + middle);

Output
LinkedList: [Cat, Dog, Horse]

Middle Element: Dog

In the above example, we have used the LinkedList class to implement the linked list data structure. Notice the
expression,

animals.get(animals.size()/2)

size()/2 - returns the position of middle element

get() - returns the element at the middle position

145. Java Program to Convert the LinkedList into an Array and vice versa
In this example, we will learn to convert the linked list into an array and vice versa in Java.

Before you learn about the example, make sure you first visit the following tutorials,

Java LinkedList Class

Java Array

LinkedList Data Structure

Example 1: Convert the LinkedList into Array

import java.util.LinkedList;

class Main {

public static void main(String[] args) {

LinkedList<String> languages= new LinkedList<>();

// Add elements in the linked list

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

System.out.println("LinkedList: " + languages);


// Create a new array of String type

String[] arr = new String[languages.size()];

// Convert LinkedList into the string array

languages.toArray(arr);

System.out.print("Array: ");

for(String item:arr) {

System.out.print(item+", ");

Output

LinkedList: [Java, Python, JavaScript]

Array: Java, Python, JavaScript,

In the above example, we have created a linked list named languages. Notice the line,

languages.toArray(arr);

Here, the toArray() method converts the linked list languages into an array. And stores it in the string array arr.

Note: If we don't pass any argument to the toArray() method, the method returns an array of the Object type.

Example 2: Convert Array to LinkedList

import java.util.Arrays;

import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// create an array

String[] array = {"Java", "Python", "C"};

System.out.println("Array: " + Arrays.toString(array));

// convert array to a linked list

LinkedList<String> languages= new LinkedList<>(Arrays.asList(array));

System.out.println("LinkedList: " + languages);

Output

Array: [Java, Python, C]

LinkedList: [Java, Python, C]

In the above example, we have created an array of String type. Notice the expression,

Arrays.asList(array)

Here, the asList() method of the Arrays class converts the specified array into the linked list.

146. Java Program to Convert the ArrayList into a string and vice versa
In this example, we will learn to convert the arraylist into a string and vice versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java String

Example 1: Convert the Arraylist into a String

import java.util.ArrayList;

class Main {
public static void main(String[] args) {

ArrayList<String> languages= new ArrayList<>();

// Add elements in the array list

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

System.out.println("ArrayList: " + languages);

// convert the arraylist into a string

String arraylist = languages.toString();

System.out.println("String: " + arraylist);

Output

ArrayList: [Java, Python, JavaScript]

String: [Java, Python, JavaScript]

In the above example, we have created an arraylist named languages. Notice the line,

languages.toString();

Here, the toString() method converts arraylist into a string. The entire arraylist is converted as a single string.

Note: We can also convert the arraylist into a string array. To learn more, visit Java ArrayList to Array
Conversion.

Example 2: Convert ArrayList to String Using join()

import java.util.ArrayList;

class Main {
public static void main(String[] args) {

ArrayList<String> languages= new ArrayList<>();

// Add elements in the array list

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

System.out.println("ArrayList: " + languages);

// convert the arraylist into a string

String arraylist = String.join(", ", languages);

System.out.println("String: " + arraylist);

Output

ArrayList: [Java, Python, JavaScript]

String: Java, Python, JavaScript

In the above example, we have used the join() method of the String class to convert the arraylist into a string. To
learn more, visit Java String join().

Example 3: Convert a String to ArrayList

import java.util.ArrayList;

import java.util.Arrays;

class Main {

public static void main(String[] args) {

// create a string
String str = "Java, JavaScript, Python";

System.out.println("String: " + str);

// convert the string into an array

String[] arr = str.split(",");

// create an arraylist from the string

ArrayList<String> languages = new ArrayList<>(Arrays.asList(arr));

System.out.println("ArrayList: " + languages);

Output

String: Java, JavaScript, Python

ArrayList: [Java, JavaScript, Python]

In the above example, we have created a string named str. We have used the split() method to convert the given
string into an array. To learn more about splitting a string, visit Java String

split().

Notice the expression,

Arrays.asList(arr)

The asList() method converts the string array into an arraylist.

147. Java Program to Iterate over an ArrayList


In this example, we will learn to iterate over the elements of an arraylist in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java for Loop


Java for-each Loop

Java ListIterator Interface

Example 1: Iterate through ArrayList using for loop

import java.util.ArrayList;

class Main {

public static void main(String[] args) {

// Creating an array list

ArrayList<String> languages = new ArrayList<>();

languages.add("Java");

languages.add("JavaScript");

languages.add("Python");

System.out.println("ArrayList: " + languages);

// Using for loop

System.out.println("Iterating over ArrayList using for loop: ");

for(int i = 0; i < languages.size(); i++) {

System.out.print(languages.get(i));

System.out.print(", ");

Output

ArrayList: [Java, JavaScript, Python]

Iterating over ArrayList using for loop:

Java, JavaScript, Python,

In the above example, we have created an arraylist named languages. Here, we have used the for loop to access
each element of the arraylist.
Example 2: Iterate through ArrayList using for-each loop

import java.util.ArrayList;

class Main {

public static void main(String[] args) {

// Creating an array list

ArrayList<String> languages = new ArrayList<>();

languages.add("Java");

languages.add("JavaScript");

languages.add("Python");

System.out.println("ArrayList: " + languages);

// Using forEach loop

System.out.println("Iterating over ArrayList using for-each loop:");

for(String language : languages) {

System.out.print(language);

System.out.print(", ");

Output

ArrayList: [Java, JavaScript, Python]

Iterating over ArrayList using for-each loop:

Java, JavaScript, Python,

Here, we have used the for-each loop to iterate over the ArrayList and print each element.

Example 3: Iterate over ArrayList using listIterator()

import java.util.ArrayList;
import java.util.ListIterator;

class Main {

public static void main(String[] args) {

// Creating an ArrayList

ArrayList<Integer> numbers = new ArrayList<>();

numbers.add(1);

numbers.add(3);

numbers.add(2);

System.out.println("ArrayList: " + numbers);

// Creating an instance of ListIterator

ListIterator<Integer> iterate = numbers.listIterator();

System.out.println("Iterating over ArrayList:");

while(iterate.hasNext()) {

System.out.print(iterate.next() + ", ");

Output

ArrayList: [1, 3, 2]

Iterating over ArrayList:

1, 3, 2,

In the above example, we have used the listIterator() method to iterate over the arraylist. Here,

hasNext() - returns true if there is next element in the arraylist

next() - returns the next element of the arraylist

Note: We can also use the ArrayList iterator() method and the ArrayList forEach() method to iterate over the
arraylist.
148. Java Program to Iterate over a HashMap
In this example, we will learn to iterate over keys, values, and key/value mappings of a Java HashMap.

To understand this example, you should have the knowledge of the following Java programming topics:

Java HashMap

Java for-each Loop

Java Iterator Interface

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Example 1: Iterate through HashMap using the forEach loop

import java.util.HashMap;

import java.util.Map.Entry;

class Main {

public static void main(String[] args) {

// Creating a HashMap

HashMap<String, String> languages = new HashMap<>();

languages.put("Java", "Enterprise");

languages.put("Python", "ML/AI");

languages.put("JavaScript", "Frontend");

System.out.println("HashMap: " + languages);

// iterating through key/value mappings

System.out.print("Entries: ");

for(Entry<String, String> entry: languages.entrySet()) {

System.out.print(entry);

System.out.print(", ");

}
// iterating through keys

System.out.print("\nKeys: ");

for(String key: languages.keySet()) {

System.out.print(key);

System.out.print(", ");

// iterating through values

System.out.print("\nValues: ");

for(String value: languages.values()) {

System.out.print(value);

System.out.print(", ");

Output

HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}

Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI,

Keys: Java, JavaScript, Python,

Values: Enterprise, Frontend, ML/AI,

In the above example, we have created a hashmap named languages. Here, we have used the forEach loop to
iterate through the elements of the hashmap.

Notice that we are independently iterating through the keys, values, and key/value mappings.

languages.entrySet() - returns the set view of all the entries

languages.keySet() - returns the set view of all the keys

languages.values() - returns the set view of all the values


Note: We have used the Map.Entry class. It is the nested class that returns a view of the map.

Example 2: Iterate through HashMap using iterator()

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map.Entry;

class Main {

public static void main(String[] args) {

// create a HashMap

HashMap<String, String> languages = new HashMap<>();

languages.put("Java", "Enterprise");

languages.put("Python", "ML/AI");

languages.put("JavaScript", "Frontend");

System.out.println("HashMap: " + languages);

// create an object of Iterator

Iterator<Entry<String, String>> iterate1 = languages.entrySet().iterator();

// iterate through key/value mappings

System.out.print("Entries: ");

while(iterate1.hasNext()) {

System.out.print(iterate1.next());

System.out.print(", ");

// iterate through keys

Iterator<String> iterate2 = languages.keySet().iterator();

System.out.print("\nKeys: ");

while(iterate2.hasNext()) {
System.out.print(iterate2.next());

System.out.print(", ");

// iterate through values

Iterator<String> iterate3 = languages.values().iterator();

System.out.print("\nValues: ");

while(iterate3.hasNext()) {

System.out.print(iterate3.next());

System.out.print(", ");

Output

HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}

Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI,

Keys: Java, JavaScript, Python,

Values: Enterprise, Frontend, ML/AI,

In the above example, we are iterating through keys, values, and key/value mappings of the hash map. We have
used the iterator() method to iterate over the hashmap. Here,

hasNext() - returns true if there is next element in the hashmap

next() - returns the next element of the hashmap

Note: We can also use the HashMap forEach() method to iterate over the hashmap.

149. Java Program to Iterate over a Set


In this example, we will learn to iterate over the elements of a set in Java.

To understand this example, you should have the knowledge of the following Java programming topics:
Java HashSet Class

Java Iterator Interface

Java for-each Loop

Example 1: Iterate through Set using the forEach loop

import java.util.Set;

import java.util.HashSet;

class Main {

public static void main(String[] args) {

// Creating an set

Set<String> languages = new HashSet<>();

languages.add("Java");

languages.add("JavaScript");

languages.add("Python");

System.out.println("Set: " + languages);

// Using forEach loop

System.out.println("Iterating over Set using for-each loop:");

for(String language : languages) {

System.out.print(language);

System.out.print(", ");

Output

Set: [Java, JavaScript, Python]

Iterating over Set using for-each loop:

Java, JavaScript, Python,


In the above example, we have created a set using the HashSet class. Here, we have used the for-each loop to
iterate each element of the set.

Example 2: Iterate through Set using iterator()

import java.util.Set;

import java.util.HashSet;

import java.util.Iterator;

class Main {

public static void main(String[] args) {

// Creating an Set

Set<Integer> numbers = new HashSet<>();

numbers.add(1);

numbers.add(3);

numbers.add(2);

System.out.println("Set: " + numbers);

// Creating an instance of Iterator

Iterator<Integer> iterate = numbers.iterator();

System.out.println("Iterating over Set:");

while(iterate.hasNext()) {

System.out.print(iterate.next() + ", ");

Output

Set: [1, 2, 3]

Iterating over Set:

1, 2, 3,
In the above example, we have used the HashSet class to create a set. We have used the iterator() method to
iterate over the set. Here,

hasNext() - returns true if there is next element in the set

next() - returns the next element of the set

Example 3: Iterate through Set using forEach() method

import java.util.Set;

import java.util.HashSet;

class Main {

public static void main(String[] args) {

// create an Set

Set<Integer> numbers = new HashSet<>();

// add elements to the HashSet

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

System.out.println("Set: " + numbers);

// iterate each element of the set

System.out.print("Element of Set: ");

// access each element using forEach() method

// pass lambda expression to forEach()

numbers.forEach((e) -> {

System.out.print(e + " ");

});

}
Output

Set: [1, 2, 3, 4]

Element of Set: 1 2 3 4

In the above example, we have created a set named numbers using the HashSet class. Notice the code,

numbers.forEach((e) -> {

System.out.print(e + " ");

});

Here, we have used the forEach() method to access each element of the set. The method takes the lambda
expressions as it's argument. To learn more about lamnda expression, visit Java Lambda

Expressions.

150. Java Program to Merge two lists


In this example, we will learn to merge two lists with the help of the addAll() method and the Stream class in
Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java List

Example 1: Merge two lists using addAll()

import java.util.ArrayList;

import java.util.List;

class Main {

public static void main(String[] args) {

// create first list

List<Integer> prime = new ArrayList<>();

prime.add(2);
prime.add(3);

prime.add(5);

System.out.println("First List: " + prime);

// create second list

List<Integer> even = new ArrayList<>();

even.add(4);

even.add(6);

System.out.println("Second List: " + even);

// create merged list

List<Integer> numbers = new ArrayList<>();

numbers.addAll(prime);

numbers.addAll(even);

System.out.println("Merged List: " + numbers);

Output

First List: [2, 3, 5]

Second List: [4, 6]

Merged List: [2, 3, 5, 4, 6]

In the above example, have two lists named prime and even. Here, we have used the Java ArrayList addAll()
method to add all elements from prime and even to the new list named numbers.

Example 2: Merge two lists using the Stream class

import java.util.ArrayList;

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

import java.util.stream.Collectors;

import java.util.stream.Stream;

class Main {

public static void main(String[] args) {

// create first list

// asList() converts the array into the arraylist

List<Integer> prime = new ArrayList<>(Arrays.asList(2, 3, 5));

System.out.println("First List: " + prime);

// create second list

List<Integer> even = new ArrayList<>(Arrays.asList(4, 6));

System.out.println("Second List: " + even);

// convert both lists into stream

Stream<Integer> list1 = prime.stream();

Stream<Integer> list2 = even.stream();

// merge two streams

Stream<Integer> merged = Stream.concat(list1, list2);

// convert the merged stream into list

List<Integer> numbers = merged.collect(Collectors.toList());

System.out.println("Merged List: " + numbers);

}
Output

First List: [2, 3, 5]

Second List: [4, 6]

Merged List: [2, 3, 5, 4, 6]

In the above example, we have used the Stream class to merge the two lists. Here,

stream() - converts the list into a stream

concat() - merges the two streams

collect(Collectors.toList()) - convert the stream into a list

To learn more about stream, visit Java Stream Class.

151. Java Program to Update value of HashMap using key


In this example, we will learn to update the value of the Java HashMap using key.

To understand this example, you should have the knowledge of the following Java programming topics:

Java HashMap

Java Lambda Expressions

Example 1: Update value of HashMap using put()

import java.util.HashMap;

class Main {

public static void main(String[] args) {

HashMap<String, Integer> numbers = new HashMap<>();

numbers.put("First", 1);

numbers.put("Second", 2);

numbers.put("Third", 3);

System.out.println("HashMap: " + numbers);


// return the value of key Second

int value = numbers.get("Second");

// update the value

value = value * value;

// insert the updated value to the HashMap

numbers.put("Second", value);

System.out.println("HashMap with updated value: " + numbers);

Output

HashMap: {Second=2, Third=3, First=1}

HashMap with updated value: {Second=4, Third=3, First=1}

In the above example, we have used the HashMap put() method to update the value of the key Second. Here,
first, we access the value using the HashMap get() method.

Example 2: Update value of HashMap using computeIfPresent()

import java.util.HashMap;

class Main {

public static void main(String[] args) {

HashMap<String, Integer> numbers = new HashMap<>();

numbers.put("First", 1);

numbers.put("Second", 2);

System.out.println("HashMap: " + numbers);

// update the value of Second

// Using computeIfPresent()
numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2);

System.out.println("HashMap with updated value: " + numbers);

Output

HashMap: {Second=2, First=1}

HashMap with updated value: {Second=4, First=1}

In the above example, we have recomputed the value of the key Second using the computeIfPresent() method.
To learn more, visit HashMap computeIfPresent().

Here, we have used the lambda expression as the method argument to the method.

Example 3: Update value of Hashmap using merge()

import java.util.HashMap;

class Main {

public static void main(String[] args) {

HashMap<String, Integer> numbers = new HashMap<>();

numbers.put("First", 1);

numbers.put("Second", 2);

System.out.println("HashMap: " + numbers);

// update the value of First

// Using the merge() method

numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue);

System.out.println("HashMap with updated value: " + numbers);

}
}

Output

HashMap: {Second=2, First=1}

HashMap with updated value: {Second=2, First=5}

In the above example, the merge() method adds the old value and new value of the key First. And, insert the
updated value to HashMap. To learn more, visit HashMap merge().

152. Java Program to Remove duplicate elements from ArrayList


In this example, we will learn to convert the duplicate element from the ArrayList in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java Set Interface

Example 1: Remove duplicate elements from ArrayList using Set

import java.util.ArrayList;

import java.util.Arrays;

import java.util.LinkedHashSet;

import java.util.Set;

class Main {

public static void main(String[] args) {

// create an arraylist from the array

// using asList() method of the Arrays class

ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3));

System.out.println("ArrayList with duplicate elements: " + numbers);

// convert the arraylist into a set

Set<Integer> set = new LinkedHashSet<>();

set.addAll(numbers);
// delete al elements of arraylist

numbers.clear();

// add element from set to arraylist

numbers.addAll(set);

System.out.println("ArrayList without duplicate elements: " + numbers);

Output

ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3]

ArrayList without duplicate elements: [1, 2, 3, 4]

In the above example, we have created an arraylist named numbers. The arraylist contains duplicate elements.

To remove duplicate elements from the arraylist, we have

add all elements from arraylist to set

empty the arraylist using clear() method

add all elements from set to arraylist

Here, we have used the LinkedHashSet to create a set. It is because it removes the duplicate elements and
maintains insertion order. To learn more, visit Java LinkedHashSet.

Example 2: Remove duplicate elements from ArrayList using Stream

import java.util.ArrayList;

import java.util.Arrays;

import java.util.stream.Collectors;

import java.util.stream.Stream;

class Main {

public static void main(String[] args) {


// create an arraylist from the array

// using asList() method of the Arrays class

ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3));

System.out.println("ArrayList with duplicate elements: " + numbers);

// create a stream from arraylist

Stream<Integer> stream = numbers.stream();

// call the distinct() of Stream

// to remove duplicate elements

stream = stream.distinct();

// convert the stream to arraylist

numbers = (ArrayList<Integer>)stream.collect(Collectors.toList());

System.out.println("ArrayList without duplicate elements: " + numbers);

Output

ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3]

ArrayList without duplicate elements: [1, 2, 3, 4]

In the above example, we have created an arraylist named numbers. The arraylist contains duplicate elements.

Here, we have used the Stream class to remove duplicate elements from the arraylist.

numbers.stream() - create a stream from the arraylist

stream.distinct() - removes duplicate elements

stream.collect(Collectors.toList()) - returns a list from the stream


Here, we have used typecasting to convert the returned list into an arraylist.

153. Java Program to Get key from HashMap using the value
In this example, we will learn to get the key from HashMap using the value in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java HashMap

Java for-each Loop

Example: Get key for a given value in HashMap

import java.util.HashMap;

import java.util.Map.Entry;

class Main {

public static void main(String[] args) {

// create a hashmap

HashMap<String, Integer> numbers = new HashMap<>();

numbers.put("One", 1);

numbers.put("Two", 2);

numbers.put("Three", 3);

System.out.println("HashMap: " + numbers);

// value whose key is to be searched

Integer value = 3;

// iterate each entry of hashmap

for(Entry<String, Integer> entry: numbers.entrySet()) {

// if give value is equal to value from entry

// print the corresponding key


if(entry.getValue() == value) {

System.out.println("The key for value " + value + " is " + entry.getKey());

break;

Output

HashMap: {One=1, Two=2, Three=3}

The key for value 3 is Three

In the above example, we have created a hashmap named numbers. Here, we want to get the key for the value
3. Notice the line,

Entry<String, Integer> entry : numbers.entrySet()

Here, the entrySet() method returns a set view of all the entries.

entry.getValue() - get value from the entry

entry.getKey() - get key from the entry

Inside the if statement we check if the value from the entry is the same as the given value. And, for matching
value, we get the corresponding key.

154. Java Program to Detect loop in a LinkedList


In this example, we will learn to detect whether there is a loop in LinkedList in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java LinkedList

Java Methods

Example: Detect Loop in a LinkedList

class LinkedList {
// create an object of Node class

// represent the head of the linked list

Node head;

// static inner class

static class Node {

int value;

// connect each node to next node

Node next;

Node(int d) {

value = d;

next = null;

// check if loop is present

public boolean checkLoop() {

// create two references at start of LinkedList

Node first = head;

Node second = head;

while(first != null && first.next !=null) {

// move first reference by 2 nodes

first = first.next.next;

// move second reference by 1 node


second = second.next;

// if two references meet

// then there is a loop

if(first == second) {

return true;

return false;

public static void main(String[] args) {

// create an object of LinkedList

LinkedList linkedList = new LinkedList();

// assign values to each linked list node

linkedList.head = new Node(1);

Node second = new Node(2);

Node third = new Node(3);

Node fourth = new Node(4);

// connect each node of linked list to next node

linkedList.head.next = second;

second.next = third;

third.next = fourth;

// make loop in LinkedList

fourth.next = second;
// printing node-value

System.out.print("LinkedList: ");

int i = 1;

while (i <= 4) {

System.out.print(linkedList.head.value + " ");

linkedList.head = linkedList.head.next;

i++;

// call method to check loop

boolean loop = linkedList.checkLoop();

if(loop) {

System.out.println("\nThere is a loop in LinkedList.");

else {

System.out.println("\nThere is no loop in LinkedList.");

Output

LinkedList: 1 2 3 4

There is a loop in LinkedList.

In the above example, we have implemented a LinkedList in Java. We have used Floyd's cycle finding algorithm
to check if there is a loop in LinkedList.

Notice the code inside the checkLoop() method. Here, we have two variables named first and second that
traverse the nodes in LinkedList.

first - traverse with 2 nodes at single iteration


second - traverse with 1 node at single iteration

Two nodes are traversing at different speeds. Hence, they will meet if there is a loop in LinkedList.

155. Java Program to Calculate union of two sets


In this example, we will learn to calculate the union of two sets in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Set Interface

Java HashSet Class

Example 1: Calculate the union of two sets using addAll()

import java.util.HashSet;

import java.util.Set;

class Main {

public static void main(String[] args) {

// create the first set

Set<Integer> evenNumbers = new HashSet<>();

evenNumbers.add(2);

evenNumbers.add(4);

System.out.println("Set1: " + evenNumbers);

// create second set

Set<Integer> numbers = new HashSet<>();

numbers.add(1);

numbers.add(3);

System.out.println("Set2: " + numbers);

// Union of two sets

numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);

Output

Set1: [2, 4]

Set2: [1, 3]

Union is: [1, 2, 3, 4]

In the above example, we have created two sets named evenNumbers and numbers. We have implemented the
set using the HashSet class. Notice the line,

numbers.addAll(evenNumbers);

Here, we have used the addAll() method to get the union of two sets.

Example 2: Get union of two sets using Guava Library

import java.util.HashSet;

import java.util.Set;

import com.google.common.collect.Sets;

class Main {

public static void main(String[] args) {

// create the first set

Set<String> languages1 = new HashSet<>();

languages1.add("Java");

languages1.add("Python");

System.out.println("Programming Languages: " + languages1);

// create second set

Set<String> languages2 = new HashSet<>();


languages2.add("English");

languages2.add("Spanish");

System.out.println("Human Language: " + languages2);

Set<String> unionSet = Sets.union(languages1, languages2);

System.out.println("Union is: " + unionSet);

Output

Programming Languages: [Java, Python]

Human Languages: [English, Spanish]

Languages: [Java, Python, English, Spanish]

In the above example, we have used the Guava library to get the union of two sets. In order to run this program,
you need to implement Guava Library by adding it in your dependency.

Here, we have used the union() method of the Sets class present in the Guava library.

156. Java Program to Calculate the intersection of two sets


In this example, we will learn to calculate the intersection of two sets in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Set Interface

Java HashSet Class

Example 1: Calculate the intersection of two sets

import java.util.HashSet;

import java.util.Set;

class Main {

public static void main(String[] args) {


// create first set

Set<Integer> primeNumbers = new HashSet<>();

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("Prime Numbers: " + primeNumbers);

// create second set

Set<Integer> evenNumbers = new HashSet<>();

evenNumbers.add(2);

evenNumbers.add(4);

System.out.println("Even Numbers: " + evenNumbers);

// Intersection of two sets

evenNumbers.retainAll(primeNumbers);

System.out.println("Intersection: " + evenNumbers);

Output

Prime Numbers: [2, 3]

Even Numbers: [2, 4]

Intersection: [2]

In the above example, we have created two sets named primeNumbers and evenNumbers. We have
implemented the set using the HashSet class. Notice the line,

evenNumbers.retainAll(primeNumbers);

Here, we have used the retainAll() method to get the intersection of two sets.

Example 2: Get union of two sets using Guava Library

import java.util.HashSet;

import java.util.Set;
import com.google.common.collect.Sets;

class Main {

public static void main(String[] args) {

// create the first set

Set<String> backend = new HashSet<>();

backend.add("Java");

backend.add("JavaScript");

System.out.println("Backend Languages: " + backend);

// create second set

Set<String> frontend = new HashSet<>();

frontend.add("JavaScript");

frontend.add("CSS");

System.out.println("Frontend Languages: " + frontend);

Set<String> intersect = Sets.intersection(backend, frontend);

System.out.println("Common Languages: " + intersect);

Output

Backend Languages: [Java, JavaScript]

Frontend Languages: [JavaScript, CSS]

Common Languages: [JavaScript]

In the above example, we have used the Guava library to get the intersection of two sets. In order to run this
program, you need to implement Guava Library by adding it to your dependency.

Here, we have used the intersection() method of the Sets class present in the Guava library.
157. Java Program to Calculate the difference between two sets
In this example, we will learn to calculate the difference between two sets in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Set Interface

Java HashSet Class

Example 1: Calculate the difference between two sets

import java.util.HashSet;

import java.util.Set;

class Main {

public static void main(String[] args) {

// create first set

Set<Integer> numbers = new HashSet<>();

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

System.out.println("Numbers: " + numbers);

// create second set

Set<Integer> primeNumbers = new HashSet<>();

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("Prime Numbers: " + primeNumbers);

// Difference between HashSet1 and HashSet2

numbers.removeAll(primeNumbers);
System.out.println("Numbers without prime numbers: " + numbers);

Output

Numbers: [1, 2, 3, 4]

Prime Numbers: [2, 3]

Numbers without prime numbers: [1, 4]

In the above example, we have created two sets named numbers and primeNumbers. We have implemented
the set using the HashSet class. Notice the line,

numbers.retainAll(primeNumbers);

Here, we have used the removeAll() method to calculate the difference between two sets.

Example 2: Get difference between two sets using Guava Library

import java.util.HashSet;

import java.util.Set;

import com.google.common.collect.Sets;

class Main {

public static void main(String[] args) {

// create the first set

Set<String> languages1 = new HashSet<>();

languages1.add("Java");

languages1.add("JavaScript");

languages1.add("English");

languages1.add("Spanish");

System.out.println("Languages: " + languages1);


// create second set

Set<String> languages2 = new HashSet<>();

languages2.add("English");

languages2.add("Spanish");

System.out.println("Human Languages: " + languages2);

Set<String> intersect = Sets.difference(languages1, languages2);

System.out.println("Programming Languages: " + intersect);

Output

Languages: [Java, JavaScript, English, Spanish]

Human Languages: [English, Spanish]

Programming Languages: [Java, JavaScript]

In the above example, we have used the Guava library to get the difference between two sets. In order to run
this program, you need to implement Guava Library by adding it in your dependency.

Here, we have used the difference() method of the Sets class present in the Guava library.

158. Java Program to Check if a set is the subset of another set


In this example, we will learn to check if a set is the subset of another set in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Set Interface

Java HashSet Class

Java TreeSet

Example 1: Check subset of a Set using HashSet class

import java.util.HashSet;

import java.util.Set;
class Main {

public static void main(String[] args) {

// create the first set

Set<Integer> numbers = new HashSet<>();

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

System.out.println("Numbers: " + numbers);

// create the second set

Set<Integer> primeNumbers = new HashSet<>();

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("Prime Numbers: " + primeNumbers);

// check if primeNumbers is a subset of numbers

boolean result = numbers.containsAll(primeNumbers);

System.out.println("Is Prime Numbers is subset of Numbers? " + result);

Output

Numbers: [1, 2, 3, 4]

Prime Numbers: [2, 3]

Is Prime Numbers is subset of Numbers? true

In the above example, we have created two sets named numbers and primeNumbers. We have implemented
the set using the HashSet class. Notice the line,
numbers.containsAll(primeNumbers);

Here, we have used the containsAll() method to check if primeNumbers is the subset of numbers.

Example 2: Check subset of a Set using TreeSet class

import java.util.TreeSet;

import java.util.Set;

class Main {

public static void main(String[] args) {

// create the first set

Set<String> languages = new TreeSet<>();

languages.add("Java");

languages.add("JavaScript");

languages.add("Python");

languages.add("CSS");

System.out.println("Programming Languages: " + languages);

// create the second set

Set<String> frontend = new TreeSet<>();

frontend.add("CSS");

frontend.add("JavaScript");

System.out.println("Frontend Languages: " + frontend);

// check if frontend is a subset of languages

boolean result = languages.containsAll(frontend);

System.out.println("Is frontend is subset of languages? " + result);

}
Output

Programming Languages: [CSS, Java, JavaScript, Python]

Frontend Languages: [CSS, JavaScript]

Is frontend is subset of languages? true

Here, we have implemented the set using the TreeSet class.

159. Java Program to Sort map by keys


In this example, we will learn to sort the map by keys in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Map Interface

Java HashMap

Java TreeMap

Example: Sort a map by keys using TreeMap

import java.util.HashMap;

import java.util.Map;

import java.util.TreeMap;

class Main {

public static void main(String[] args) {

// create a hashmap

Map<String, String> languages = new HashMap<>();

languages.put("pos3", "JS");

languages.put("pos1", "Java");

languages.put("pos2", "Python");

System.out.println("Map: " + languages);

// create a tree map from the map


TreeMap<String, String> sortedNumbers = new TreeMap<>(languages);

System.out.println("Map with sorted Key" + sortedNumbers);

Output

Map: {pos1=Java, pos2=Python, pos3=JS}

Map with sorted Key{pos1=Java, pos2=Python, pos3=JS}

In the above example, we have created a map named languages using HashMap. Here, the map is not sorted.

To sort the map, we created a treemap from the map. Now, the map is sorted by its keys.

160. Java Program to Pass ArrayList as the function argument


In this example, we will learn to pass an arraylist as the funcion argument in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java Arrays

Example 1: Pass ArrayList as Function Parameter

import java.util.ArrayList;

class Main {

public static void display(ArrayList<String> languages) {

System.out.print("ArrayList: ");

for(String language : languages) {

System.out.print(language + ", ");

}
}

public static void main(String[] args) {

// create an arraylist

ArrayList<String> languages = new ArrayList<>();

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

// passing arraylist as function parameter

display(languages);

Output

ArrayList: Java, Python, JavaScript,

In the above example, we have created an arraylist named languages. Here, we have a method display(). It prints
elements of arraylist.

Notice the line,

display(languages);

Here, we have passed languages as the function parameter.

Example 2: Pass ArrayList as Function Parameter by converting into Array

import java.util.ArrayList;

class Main {

public static void percentage(Integer[] marks) {


int totalMarks = 300;

int obtainedMarks = 0;

for(int mark : marks) {

obtainedMarks += mark;

// compute average

double percent = (obtainedMarks * 100) / totalMarks;

System.out.println("Percentage: " + percent);

public static void main(String[] args) {

// create an arraylist

ArrayList<Integer> marks = new ArrayList<>();

marks.add(67);

marks.add(87);

marks.add(56);

System.out.println("Marks: " + marks);

// passing arraylist as function parameter

percentage(marks.toArray(new Integer[marks.size()]));

Output

Marks: [67, 87, 56]

Percentage: 70.0

In the above example, we have created an arraylist named marks. Notice the line,

percentage(marks.toArray(new Integer[0]));
Here, we are passing the arraylist as an argument to the percentage() method.

161. Java Program to Iterate over ArrayList using Lambda Expression


In this example, we will learn to iterate over each elements of the arraylist using lambda expression in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java ArrayList Class

Java Lambda Expressions

Example: Pass ArrayList as Function Parameter

import java.util.ArrayList;

class Main {

public static void main(String[] args) {

// create an ArrayList

ArrayList<String> languages = new ArrayList<>();

// add elements to the ArrayList

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

// print arraylist

System.out.print("ArrayList: ");

// iterate over each element of arraylist

// using forEach() method

languages.forEach((e) -> {

System.out.print(e + ", ");

});

}
Output

ArrayList: Java, Python, JavaScript,

In the above example, we have created an arraylist named languages. Notice the code,

languages.forEach((e) -> {

System.out.print(e + ", ");

});

Here, we are passing the lambda expression as an argument to ArrayList forEach().

162. Java Program to Implement Binary Tree Data Structure


In this example, we will learn to implement the binary tree data structure in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java Program to Implement Binary Tree

// class to create nodes

class Node {

int key;

Node left, right;

public Node(int item) {

key = item;

left = right = null;

class BinaryTree {

Node root;
// Traverse tree

public void traverseTree(Node node) {

if (node != null) {

traverseTree(node.left);

System.out.print(" " + node.key);

traverseTree(node.right);

public static void main(String[] args) {

// create an object of BinaryTree

BinaryTree tree = new BinaryTree();

// create nodes of the tree

tree.root = new Node(1);

tree.root.left = new Node(2);

tree.root.right = new Node(3);

tree.root.left.left = new Node(4);

System.out.print("\nBinary Tree: ");

tree.traverseTree(tree.root);

Output

Binary Tree: 4 2 1 3

Binary tree implementation in Java with 4 nodes

Binary Tree Output

In the above example, we have implemented the binary tree in Java. Unlike other data structures, Java doesn't
provide a built-in class for trees.
Here, we have created our own class of BinaryTree. To learn about the binary tree, visit Binary Tree Data
Structure.

163. Java Program to Perform the preorder tree traversal


In this example, we will learn to perform the preorder tree traversal in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java Program to perform preorder tree traversal

class Node {

int item;

Node left, right;

public Node(int key) {

item = key;

left = right = null;

class Tree {

// root of Tree

Node root;

Tree() {

root = null;

void preorder(Node node) {

if (node == null)
return;

// traverse the root node

System.out.print(node.item + "->");

// traverse the left child

preorder(node.left);

// traverse the right child

preorder(node.right);

public static void main(String[] args) {

// create object of tree

Tree tree = new Tree();

// create nodes of the tree

tree.root = new Node(1);

tree.root.left = new Node(12);

tree.root.right = new Node(9);

tree.root.left.left = new Node(5);

tree.root.left.right = new Node(6);

// preorder tree traversal

System.out.println("\nPreorder traversal ");

tree.preorder(tree.root);

Preorder Traversal of Tree

Preorder Traversal of Tree

Output
Preorder traversal

1->12->5->6->9->

In the above example, we have implemented the tree data structure in Java. Here, we are performing the
preorder traversal of the tree.

Recommended Reading:

Binary Tree Data Structure

Tree Traversal

Binary Tree Implementation in Java

164. Java Program to Perform the postorder tree traversal


In this example, we will learn to perform the postorder tree traversal in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java Program to perform postorder tree traversal

class Node {

int item;

Node left, right;

public Node(int key) {

item = key;

left = right = null;

class Tree {

// Root of Binary Tree

Node root;
Tree() {

root = null;

void postorder(Node node) {

if (node == null)

return;

// traverse the left child

postorder(node.left);

// traverse the right child

postorder(node.right);

// traverse the root node

System.out.print(node.item + "->");

public static void main(String[] args) {

// create an object of Tree

Tree tree = new Tree();

// create nodes of the tree

tree.root = new Node(1);

tree.root.left = new Node(12);

tree.root.right = new Node(9);

// child nodes of left child

tree.root.left.left = new Node(5);


tree.root.left.right = new Node(6);

// postorder tree traversal

System.out.println("Postorder traversal");

tree.postorder(tree.root);

Postorder Tree Traversal

Postorder Tree Traversal

Output

Postorder traversal

5->6->12->9->1->

In the above example, we have implemented the tree data structure in Java. Here, we are performing the
postorder traversal of the tree.

Recommended Reading:

Binary Tree Data Structure

Tree Traversal

Binary Tree Implementation in Java

165. Java Program to Perform the inorder tree traversal


In this example, we will learn to perform the inorder tree traversal in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java Program to perform inorder tree traversal

class Node {

int item;
Node left, right;

public Node(int key) {

item = key;

left = right = null;

class Tree {

// root of Tree

Node root;

Tree() {

root = null;

void inOrder(Node node) {

if (node == null)

return;

// traverse the left child

inOrder(node.left);

// traverse the root node

System.out.print(node.item + "->");

// traverse the right child

inOrder(node.right);

}
public static void main(String[] args) {

// create an object of Tree

Tree tree = new Tree();

// create nodes of tree

tree.root = new Node(1);

tree.root.left = new Node(12);

tree.root.right = new Node(9);

// create child nodes of left child

tree.root.left.left = new Node(5);

tree.root.left.right = new Node(6);

System.out.println("In Order traversal");

tree.inOrder(tree.root);

Inorder Tree Traversal

Inorder Tree Traversal

Output

In Order traversal

5->12->6->1->9->

In the above example, we have implemented the tree data structure in Java. Here, we are performing the
inorder traversal of the tree.

Recommended Reading:

Binary Tree Data Structure

Tree Traversal
Binary Tree Implementation in Java

166. Java Program to Count number of leaf nodes in a tree


In this example, we will learn to count the number of leaf nodes in a tree using Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Class and Objects

Java Methods

Example: Java Program to count the number of leaf nodes in a tree

class Node {

int item;

Node left, right;

public Node(int key) {

item = key;

left = right = null;

class Main {

// root of Tree

Node root;

Main() {

root = null;

// method to count leaf nodes

public static int countLeaf(Node node) {

if(node == null) {
return 0;

// if left and right of the node is null

// it is leaf node

if (node.left == null && node.right == null) {

return 1;

else {

return countLeaf(node.left) + countLeaf(node.right);

public static void main(String[] args) {

// create an object of Tree

Main tree = new Main();

// create nodes of tree

tree.root = new Node(5);

tree.root.left = new Node(3);

tree.root.right = new Node(8);

// create child nodes of left child

tree.root.left.left = new Node(2);

tree.root.left.right = new Node(4);

// create child nodes of right child

tree.root.right.left = new Node(7);

tree.root.right.right = new Node(9);


// call method to count leaf nodes

int leafNodes = countLeaf(tree.root);

System.out.println("Total Leaf Nodes = " + leafNodes);

Output

Total Leaf Nodes = 4

Treee data structure with 7 nodes and 4 leaf nodes

Count Number of Leaf Nodes

In the above example, we have implemented the tree data structure in Java. Here, we are using recursion to
count the number of leaf nodes in the tree.

Recommended Reading:

Tree Data Structure

Binary Tree Implementation in Java

167. Java Program to Check if a string contains a substring


In this example, we will learn to check if a string contains a substring using contains() and indexOf() method in
Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java String

Java String substring()

Example 1: Check if a string contains a substring using contains()

class Main {

public static void main(String[] args) {

// create a string

String txt = "This is Programiz";

String str1 = "Programiz";


String str2 = "Programming";

// check if name is present in txt

// using contains()

boolean result = txt.contains(str1);

if(result) {

System.out.println(str1 + " is present in the string.");

else {

System.out.println(str1 + " is not present in the string.");

result = txt.contains(str2);

if(result) {

System.out.println(str2 + " is present in the string.");

else {

System.out.println(str2 + " is not present in the string.");

Output

Programiz is present in the string.

Programming is not present in the string.

In the above example, we have three string txt, str1, and str2. Here, we have used the String contains() method
to check if strings str1 and str2 are present in txt.

Example 2: Check if a string contains a substring using indexOf()

class Main {
public static void main(String[] args) {

// create a string

String txt = "This is Programiz";

String str1 = "Programiz";

String str2 = "Programming";

// check if str1 is present in txt

// using indexOf()

int result = txt.indexOf(str1);

if(result == -1) {

System.out.println(str1 + " not is present in the string.");

else {

System.out.println(str1 + " is present in the string.");

// check if str2 is present in txt

// using indexOf()

result = txt.indexOf(str2);

if(result == -1) {

System.out.println(str2 + " is not present in the string.");

else {

System.out.println(str2 + " is present in the string.");

Output

Programiz is present in the string.


Programming is not present in the string.

In this example, we have used the String indexOf() method to find the position of the strings str1 and str2 in txt.
If the string is found the position of the string is returned. Otherwise, -1 is

returned.

168. Java Program to Access private members of a class


In this example, we will learn to access the private methods and fields of a class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Java Methods

Java Access Modifiers

Example 1: Access private fields using getter and setter methods

class Test {

// private variables

private int age;

private String name;

// initialize age

public void setAge(int age) {

this.age = age;

// initialize name

public void setName(String name) {

this.name = name;

// access age

public int getAge() {


return this.age;

// access name

public String getName() {

return this.name;

class Main {

public static void main(String[] args) {

// create an object of Test

Test test = new Test();

// set value of private variables

test.setAge(24);

test.setName("Programiz");

// get value of private variables

System.out.println("Age: " + test.getAge());

System.out.println("Name: " + test.getName());

Output

Age: 24

Name: Programiz

In the above example, we have private variables named age and name. Here, we are trying to access the private
variables from other class named Main.
We have used the getter and setter method to access the private variables. Here,

the setter methods setAge() and setName() initializes the private variables

the getter methods getAge() and getName() returns the value of private variables

Example 2: Access the private field and method using Reflection

import java.lang.reflect.*;

class Test {

// private variables

private String name;

// private method

private void display() {

System.out.println("The name is " + name);

class Main {

public static void main(String[] args) {

try {

// create an object of Test

Test test = new Test();

// create an object of the class named Class

Class obj = test.getClass();

// access the private variable


Field field = obj.getDeclaredField("name");

// make private field accessible

field.setAccessible(true);

// set value of field

field.set(test, "Programiz");

// get value of field

// and convert it in string

String value = (String)field.get(test);

System.out.println("Name: " + value);

// access the private method

Method[] methods = obj.getDeclaredMethods();

System.out.println("Method Name: " + methods[0].getName());

int modifier = methods[0].getModifiers();

System.out.println("Access Modifier: " + Modifier.toString(modifier));

catch(Exception e) {

e.printStackTrace();

Output

Name: Programiz

Method Name: display

Access Modifier: private

In this example, we have a private field named name and a private method named display(). Here, we are using
the reflection to access the private fields and methods of the class Test.
To learn about reflection, visit Java Reflection.

You might also like