Java Programs
Java Programs
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.Scanner;
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().
To understand this example, you should have the knowledge of the following Java programming topics:
Java Operators
}
}
Output:
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
char ch = 'a';
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Operators
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.
Java Operators
System.out.println("--Before swap--");
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
}
Output:
--Before swap--
--After swap--
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.
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.
System.out.println("--Before swap--");
System.out.println("--After swap--");
Output:
--Before swap--
--After swap--
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.
Then, we just add second (24.5f) to this number - calculated first (12.0f - 24.5f) to swap the number.
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;
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.Scanner;
if(num % 2 == 0)
else
}
}
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.
import java.util.Scanner;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
char ch = 'i';
else
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.
char ch = 'z';
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println(ch + " is vowel");
break;
default:
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Operators
else
Output
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
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
else
} else {
else
Output
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
Else,
ax2 + bx + c = 0, where
a≠0
The term b2-4ac is known as the determinant of a quadratic equation. The determinant tells the nature of the
roots.
double determinant = b * b - 4 * a * c;
if(determinant > 0) {
else if(determinant == 0) {
else {
Output
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:
To understand this example, you should have the knowledge of the following Java programming topics:
Java Operators
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.
if(year % 4 == 0)
if ( year % 400 == 0)
leap = true;
else
leap = false;
else
leap = true;
}
else
leap = false;
if(leap)
else
Output
When you change the value of year to 2012, the output will be:
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.
Java Operators
char c = '*';
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
else
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.
char c = 'A';
String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
? c + " is an alphabet."
System.out.println(output);
Output
A is an alphabet.
In the above program, the if else statement is replaced with ternary operator (? :).
class Main {
// declare a variable
char c = 'a';
// checks if c is an alphabet
if (Character.isAlphabetic(c)) {
else {
Output
a is an alphabet.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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.
1 + 2 + 3 + ... + n
// sum = sum + i;
sum += i;
Output
Sum = 5050
The above program loops from 1 to the given num(100) and adds all numbers to the variable sum.
sum += i;
i++;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
long factorial = 1;
// factorial = factorial * i;
factorial *= i;
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.
import java.math.BigInteger;
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
Output
Factorial of 30 = 265252859812191058636308480000000
Since, * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be casted to
BigInteger for multiplication.
int num = 5, i = 1;
long factorial = 1;
{
factorial *= i;
i++;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
int num = 5;
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.
int num = 9, i = 1;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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, ...
int n = 10, t1 = 0, t2 = 1;
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.
int i = 1, n = 10, t1 = 0, t2 = 1;
while (i <= n)
t1 = t2;
t2 = sum;
i++;
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.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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
gcd = i;
Output
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
while(n1 != n2)
n1 -= n2;
else
n2 -= 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
n1 = ( n1 > 0) ? n1 : -n1;
n2 = ( n2 > 0) ? n2 : -n2;
while(n1 != n2)
n1 -= n2;
else
n2 -= n1;
Output
G.C.D = 9
The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a
remainder).
// Always true
while(true) {
break;
++lcm;
Output
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.
We can also use GCD to find the LCM of two numbers using the following formula:
If you don't know how to calculate GCD in Java, check Java Program to find GCD of two numbers.
if(n1 % i == 0 && n2 % i == 0)
gcd = i;
}
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.
To understand this example, you should have the knowledge of the following Java programming topics:
char c;
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
You can loop through A to Z using for loop because they are stored as ASCII characters in Java.
char 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.
To understand this example, you should have the knowledge of the following Java programming topics:
while(num != 0)
// num = num/10
num /= 10;
++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.
Output
Number of digits: 6
In this program, instead of using a while loop, we use a for loop without any body.
Since, for loop doesn't have a body, you can change it to a single statement in Java as such:
To understand this example, you should have the knowledge of the following Java programming topics:
while(num != 0) {
num /= 10;
Output
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 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
Output
In the above program, the while loop is replaced by a for loop where:
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.
long result = 1;
while (exponent != 0)
result *= base;
--exponent;
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.
long result = 1;
result *= base;
Output
Answer = 81
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
Output
Answer = 0.012345679012345678
In this program, we use Java's Math.pow() function to calculate the power of the given base.
To understand this example, you should have the knowledge of the following Java programming topics:
originalInteger = num;
while( num != 0 )
num /= 10;
if (originalInteger == reversedInteger)
else
Output
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, 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.
121 true 1 0 * 10 + 1 = 1
12 true 2 1 * 10 + 2 = 12
1 true 1 12 * 10 + 1 = 121
0 false - 121
originalInteger = num;
if (originalInteger == reversedInteger)
else
System.out.println(originalInteger + " is not a palindrome.");
Output
To understand this example, you should have the knowledge of the following Java programming topics:
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.
flag = true;
break;
if (!flag)
else
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.
if(num % i == 0)
flag = true;
break;
++i;
if (!flag)
else
Output
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.
if(low % i == 0) {
flag = true;
break;
++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:
To understand this example, you should have the knowledge of the following Java programming topics:
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.
originalNumber = number;
while (originalNumber != 0)
originalNumber /= 10;
if(result == number)
else
Output
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, 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.
originalNumber = number;
originalNumber = number;
if(result == number)
else
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:
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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:
This program is built on the concept of how to check whether an integer is an Armstrong number or not.
int digits = 0;
int result = 0;
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
originalNumber = number;
while (originalNumber != 0) {
originalNumber /= 10;
if (result == number)
}
}
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
To find all prime numbers between two integers, checkPrimeNumber() function is created. This function checks
whether a number is prime or not.
if(checkPrimeNumber(low))
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.
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
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
To find all Armstrong numbers between two integers, checkArmstrong() function is created. This function checks
whether a number is Armstrong or not.
if (checkArmstrong(number))
int digits = 0;
int result = 0;
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
originalNumber = num;
while (originalNumber != 0) {
originalNumber /= 10;
if (result == num)
return true;
return false;
Output
In the above program, we've created a function named checkArmstrong() which takes a parameter num and
returns a boolean value.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
The checkPrime() returns 1 if the number passed to the function is a prime number.
if (checkPrime(i)) {
if (checkPrime(number - i)) {
// n = primeNumber1 + primeNumber2
flag = true;
if (!flag)
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.
if (num != 0)
else
return num;
Output
Sum = 210
Initially, the addNumbers() is called from the main() function with 20 passed as an argument.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Recursion
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
int num = 6;
if (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.
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.
if (n2 != 0)
else
return n1;
}
}
Output
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
2 hcf(60, 6) 60 6 0
Final hcf(6, 0) 6 0 -
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Operators
int decimalNumber = 0, i = 0;
long remainder;
while (num != 0)
num /= 10;
++i;
return decimalNumber;
Output
}
public static long convertDecimalToBinary(int n)
long binaryNumber = 0;
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
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Operators
int octalNumber = 0, i = 1;
while (decimal != 0)
octalNumber += (decimal % 8) * i;
decimal /= 8;
i *= 10;
return octalNumber;
Output
8 | 78
8 | 9 -- 6
8 | 1 -- 1
8 | 0 -- 1
(116)
int decimalNumber = 0, i = 0;
while(octal != 0)
++i;
octal/=10;
return decimalNumber;
}
}
Output
1 * 82 + 1 * 81 + 6 * 80 = 78
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Operators
In this program, we will first convert binary number to decimal. Then, the decimal number is converted to octal.
++i;
binaryNumber /= 10;
i = 1;
while (decimalNumber != 0)
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
return octalNumber;
Output
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)
In this program, the octal number to decimal to decimal at first. Then, the decimal number is converted to
binary number.
int decimalNumber = 0, i = 0;
long binaryNumber = 0;
while(octalNumber != 0)
++i;
octalNumber/=10;
i = 1;
while (decimalNumber != 0)
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
return binaryNumber;
Output
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)
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Recursion
Java String
if (sentence.isEmpty())
return sentence;
Output:
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
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"
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Recursion
if (powerRaised != 0)
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
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
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
sum += num;
Output
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 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
double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };
largest = num;
Output
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.
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.
double[] numArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double SD = calculateSD(numArray);
sum += num;
return Math.sqrt(standardDeviation/length);
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
System.out.println();
Output
-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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java 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
product[r1][c2]
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
System.out.println();
Output
24 29
6 25
|_ (a21 x b11) + (a22 x b21) + (a23 x b31) (a21 x b12) + (a22 x b22) + (a23 x b32) _|
|_ (3 x 2) + ( 0 x -9) + (4 x 0) = 6 (3 x 3) + ( 0 x 0) + (4 x 4) = 25 _|
To understand this example, you should have the knowledge of the following Java programming topics:
Java 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
product[r1][c2]
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
displayProduct(product);
public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) {
return product;
System.out.println();
}
Output
24 29
6 25
multiplyMatrices() which multiplies the two given matrices and returns the product matrix
displayProduct() which displays the output of the product matrix on the screen.
|- (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) _|
|_ (3 x 2) + ( 0 x -9) + (4 x 0) = 6 (3 x 3) + ( 0 x 0) + (4 x 4) = 25 _|
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
Java Methods
Transpose of a matrix is the process of swapping the rows to columns. For 2x3 matrix,
Matrix
Transposed Matrix
a11 a21
a12 a22
a13 a23
display(matrix);
transpose[j][i] = matrix[i][j];
display(transpose);
}
public static void display(int[][] matrix) {
System.out.println();
Output
2 3 4
5 6 4
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]
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
System.out.println(element);
Output
In the above program, the for-each loop is used to iterate over the given array, array.
import java.util.Arrays;
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.
import java.util.Arrays;
System.out.println(Arrays.deepToString(array));
}
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
import java.util.Arrays;
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.
import java.util.Arrays;
int pos = 0;
result[pos] = element;
pos++;
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
int toFind = 3;
if (n == toFind) {
found = true;
break;
if(found)
else
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.
import java.util.stream.IntStream;
int toFind = 7;
if(found)
else
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.
import java.util.Arrays;
if(found)
else
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:
char ch = 'e';
int frequency = 0;
if(ch == str.charAt(i)) {
++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.
To understand this example, you should have the knowledge of the following Java programming topics:
line = line.toLowerCase();
char ch = line.charAt(i);
|| ch == 'o' || ch == 'u') {
++vowels;
}
else if((ch >= 'a'&& ch <= 'z')) {
++consonants;
++digits;
++spaces;
Output
Vowels: 6
Consonants: 11
Digits: 3
White spaces: 3
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).
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
if (words[i].compareTo(words[j]) > 0) {
words[i] = words[j];
words[j] = temp;
}
}
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
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
double real;
double imag;
this.real = real;
this.imag = imag;
temp;
return(temp);
Output
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.
Java Methods
int seconds;
int minutes;
int hours;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
Time diff;
--stop.minutes;
stop.seconds += 60;
--stop.hours;
stop.minutes += 60;
return(diff);
}
}
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
}
Output
In the aboe program, we use String's replaceAll() method to remove and replace all whitespaces in the string
sentence.
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 {
sc.close();
}
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java instanceof
class Test1 {
// first class
class Test2 {
// second class
}
class Main {
// create objects
System.out.println(obj1.getClass());
System.out.println(obj2.getClass());
Output
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.
class Test {
// class
class Main {
else {
Output
In the above example, we have used the instanceof operator to check if the object obj is an instance of the class
Test.
class Test {
// first class
class Main {
// create an object
if(Test.class.isInstance(obj)){
else {
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java enums
enum Size{
// enum constants
switch(this) {
case SMALL:
return "small";
case MEDIUM:
return "medium";
case LARGE:
return "large";
case EXTRALARGE:
default:
return null;
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Test {
class Main {
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,
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
return "object";
class Main {
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
Example 2: Java program to count the number of lines in a file using java.nio.file package
import java.nio.file.*;
class Main {
try {
} catch (Exception e) {
e.getStackTrace();
To understand this example, you should have the knowledge of the following Java programming topics:
Java Exceptions
import java.util.ArrayList;
import java.util.Arrays;
super(message);
class Main {
if(languages.contains(language)) {
else {
languages.add(language);
try {
obj.checkLanguage("Swift");
obj.checkLanguage("Java");
catch(CustomException e) {
Output
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.
import java.util.ArrayList;
import java.util.Arrays;
// create a unchecked exception class
super(message);
class Main {
if(languages.contains(language)) {
else {
languages.add(language);
obj.checkLanguage("Swift");
obj.checkLanguage("Java");
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
this.name = name;
this.date = date;
return name;
return date;
class Main {
}
Output
Name: Programiz
Date: 2011
In Java, immutable classes are those classes whose values are not changed. To create an immutable class, here
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
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.io.PrintWriter;
import java.io.StringWriter;
try {
int division = 0 / 0;
} catch (ArithmeticException e) {
e.printStackTrace(new PrintWriter(sw));
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
Java Operators
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.
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.
if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
Output
Not Equal
System.out.println(result);
System.out.println(result);
System.out.println(result);
System.out.println(result);
Output
true
false
false
true
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
try {
} catch (NumberFormatException e) {
numeric = false;
if(numeric)
else
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.
numeric = string.matches("-?\\d+(\\.\\d+)?");
if(numeric)
else
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,
\\d+ checks the string must have at least 1 or more numbers (\\d).
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.
import java.util.Arrays;
class Main {
if(str1.length() == str2.length()) {
// convert strings to char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);
if(result) {
else {
Output
In Java, we have two strings named str1 and str2. Here, we are checking if str1 and str2 are anagram.
Here,
Example 2: Take string inputs from users and check if the strings are anagram
import java.util.Arrays;
import java.util.Scanner;
class Main {
if(str1.length() == str2.length()) {
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// if sorted char arrays are same
if(result) {
else {
input.close();
Output
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.
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].
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class Main {
if (str == null) {
return null;
} else if (str.length() == 0) {
permutations.add("");
return permutations;
return permutations;
Output
Permutations of ABC:
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
import java.util.Random;
class Main {
int length = 7;
sb.append(randomChar);
Output
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.
class Main {
sb.append(randomChar);
Output
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.
class Main {
str.append("Java");
str.append(" is");
str.append(" popular.");
// using delete()
str.delete(0, str.length());
Output
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.
class Main {
str.append("Java");
str.append(" is");
str.append(" awesome.");
// using setLength()
str.setLength(0);
Output
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.
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().
class Main {
str.append("Java");
str.append(" is");
str.append(" awesome.");
System.out.println("StringBuffer: " + str);
// using new
Output
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
class Main {
// create a string
String name = "programiz";
firstLetter = firstLetter.toUpperCase();
Output
Name: Programiz
In the example, we have converted the first letter of the string name to upper case.
class Main {
// create a string
if(Character.isLetter(charArray[i])) {
if(foundSpace) {
charArray[i] = Character.toUpperCase(charArray[i]);
foundSpace = false;
else {
foundSpace = true;
message = String.valueOf(charArray);
Output
Message: Everyone Loves Java
Here,
if the element is a white space, we convert the next element into uppercase
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// create a string
Output
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.
class Main {
// create a string
for(char c : name.toCharArray()) {
}
}
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
if (number % i == 0) {
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.Scanner;
switch(operator)
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
return;
Output
Enter two numbers: 1.5
4.5
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
This statement calculates the product and stores in the variable result and the break; the statement ends the
switch statement.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
**
***
****
*****
Source code
int rows = 5;
System.out.print("* ");
System.out.println();
12
123
1234
12345
Source Code
int rows = 5;
System.out.println();
BB
CCC
DDDD
EEEEE
Source Code
++alphabet;
System.out.println();
*****
****
***
**
Source Code
int rows = 5;
System.out.print("* ");
System.out.println();
}
}
12345
1234
123
12
Source Code
int rows = 5;
System.out.println();
***
*****
*******
*********
Source Code
int rows = 5, k = 0;
System.out.print(" ");
while(k != 2 * i - 1) {
System.out.print("* ");
++k;
System.out.println();
232
34543
4567654
567898765
Source Code
public class Pattern {
System.out.print(" ");
++count;
while(k != 2 * i - 1) {
++count;
else {
++count1;
++k;
count1 = count = k = 0;
System.out.println();
}
Example 8: Inverted full pyramid using *
*********
*******
*****
***
Source Code
int rows = 5;
System.out.print(" ");
System.out.print("* ");
System.out.print("* ");
System.out.println();
}
}
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Source Code
System.out.print(" ");
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
System.out.printf("%4d", coef);
System.out.println();
}
23
456
7 8 9 10
Source Code
++number;
System.out.println();
To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types
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.
import java.math.RoundingMode;
import java.text.DecimalFormat;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
Java Arrays
char ch = 'c';
String st = Character.toString(ch);
// Alternatively
// st = String.valueOf(ch);
Output
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.
If you have a char array instead of just a char, we can easily convert it to String using String methods as follows:
String st = String.valueOf(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.
We can also convert a string to char array (but not char) using String's method toCharArray().
import java.util.Arrays;
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.
Java Methods
if(isNullOrEmpty(str1))
else
if(isNullOrEmpty(str2))
else
return false;
return true;
Output
str1 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.
if(isNullOrEmpty(str1))
else
if(isNullOrEmpty(str2))
else
return false;
return true;
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.time.LocalDateTime;
Output
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.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Output
Then, we've used LocalDateTime's format() method to use the given formatter. This gets us the formatted string
output.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Output
In the above program, we've used a predefined format constant BASIC_ISO_DATE to get the current ISO date as
the output.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.concurrent.TimeUnit;
public class Milliseconds {
System.out.println("Or");
Output
Or
In the above program, we've converted given milliseconds to minutes using toMinutes() method. Likewise, we
used toSeconds() method to convert it to seconds.
while minutes is
Minutes = Seconds / 60
or
Output
And
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.
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.
import java.util.Calendar;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR));
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));
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java List
import java.util.ArrayList;
import java.util.List;
list1.add("a");
List<String> list2 = new ArrayList<String>();
list2.add("b");
joined.addAll(list1);
joined.addAll(list2);
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.
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
list1.add("a");
list2.add("b");
In the above program, we used union() method to join the given lists to joined.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
list2.add("b");
.collect(Collectors.toList());
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 Arrays
import java.util.ArrayList;
class Main {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.toArray(arr);
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
Output
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 {
// create an array
Output
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.
Java String
Output
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.
import java.nio.file.Paths;
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java HashMap
Java List
import java.util.*;
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(5, "e");
Output
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.
import java.util.*;
import java.util.stream.Collectors;
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(5, "e");
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
Example 1: Convert Array to Set
import java.util.*;
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.
import java.util.*;
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.
import java.util.*;
set.add("a");
set.add("b");
set.add("c");
set.toArray(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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
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.
String s = bytesToHex(bytes);
System.out.println(s);
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
Before we create a string from a file, we assume we have a file named test.txt in our src folder.
This is a
Test 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;
System.out.println(lines);
}
Output
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
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Before we append text to an existing file, we assume we have a file named test.txt in our src folder.
This is a
Test file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class AppendFile {
try {
} catch (IOException e) {
When you run the program, the test.txt file now contains:
This is a
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.
import java.io.IOException;
try {
fw.write(text);
fw.close();
catch(IOException e) {
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.
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.
This is a
Test file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
try {
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.
Since, readAllBytes() might throw an IOException, we've used the try-catch block in the program.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
try {
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.
Then, we simply use the Files' write() method to write the encoded byte array to a File in the given finalPath.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.io.*;
String 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:
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.io.*;
public class OutputStreamString {
stream.write(line.getBytes());
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
Java enums
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.
TextStyle.valueOf(style)
To understand this example, you should have the knowledge of the following Java programming topics:
Java LinkedHashMap
import java.util.*;
capitals.put("Nepal", "Kathmandu");
capitals.put("England", "London");
capitals.put("Australia", "Canberra");
}
public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {
result.put(entry.getKey(), entry.getValue());
return result;
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.*;
this.customProperty = property;
return this.customProperty;
list.add(new CustomObject("A"));
list.add(new CustomObject("B"));
list.add(new CustomObject("X"));
list.add(new CustomObject("Aa"));
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.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
The Java File class provides the mkdir() method to create a new directory. The method returns
import java.io.File;
class Main {
if(value) {
else {
In the above example, we have created a file object named file. The object includes information about the
specified directory path.
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.
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.
import java.io.File;
class Main {
public static void main(String[] args) {
if(value) {
else {
In the above example, we have created a file object named file. The object includes information about the
directory path.
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.
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
To understand this example, you should have the knowledge of the following Java programming topics:
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.
import java.io.File;
class Main {
// create a file
try {
file.createNewFile();
catch(Exception e) {
e.getStackTrace();
}
// create an object that contains the new name of file
if(value) {
else {
In the above example, we have created a file object named file. The object holds information about the specified
file path.
file.createNewFile();
Here, we have created another file object named newFile. The object holds information about the specified file
path.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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.
import java.io.File;
class Main {
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.
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
import java.io.File;
class Main {
try {
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.
To understand this example, you should have the knowledge of the following Java programming topics:
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.
import java.io.FileInputStream;
import java.io.FileOutputStream;
class Main {
try {
sourceFile.read(array);
destFile.write(array);
sourceFile.close();
destFile.close();
catch (Exception e) {
e.getStackTrace();
}
}
Output
In the above example, we have used the FileInputStream and FileOutputStream to copy one file to another.
Here,
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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
char a = '5';
char b = 'c';
int num1 = a;
int num2 = b;
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.
We can also use the getNumericValue() method of the Character class to convert the char type variable into int
type.
class Main {
char a = '5';
char b = '9';
// Use getNumericValue()
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).
We can also use the parseInt() method of the Integer class to convert the char type variable to an int type.
class Main {
char a = '5';
char b = '9';
// Use parseInt()
System.out.println(num1); // 5
System.out.println(num2); // 9
}
}
Integer.parseInt(String.valueOf(a))
Here,
Note: The Integer.parseInt() method only works with string type variables. Hence, the character 'a' is converted
into a String.
In Java, we can also convert the character into an integer by subtracting it with character 0. For example,
class Main {
char a = '9';
char b = '3';
System.out.println(num1); // 9
System.out.println(num2); // 3
}
In the above example, notice the line,
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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
// 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.
We can also use the forDigit() method of the Character class to convert the int type variable into char type.
class Main {
int num1 = 1;
// print value
System.out.println(a); // 1
System.out.println(b); // d
}
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
To learn more about the forDigit() method, visit Java Character.forDigit() (Official Oracle Documentation).
In Java, we can also convert the integer into a character by adding the character '0' with it. For example,
class Main {
int num1 = 1;
int num2 = 9;
// print value
System.out.println(a); // 1
System.out.println(b); // 9
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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
long a = 2322331L;
long b = 52341241L;
// 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
We can also use the toIntExact() method of the Math class to convert the long value into an int.
class Main {
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,
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 {
// 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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
int a = 25;
int b = 34;
// 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 {
int a = 251;
// using valueOf()
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types
Java String
class Main {
// using valueOf()
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.
We can also convert the boolean variables into strings using the toString() method of the Boolean class. For
example,
class Main {
// using toString()
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// using parseBoolean()
boolean b1 = Boolean.parseBoolean(str1);
boolean b2 = Boolean.parseBoolean(str2);
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.
We can also convert the string variables into boolean using the valueOf() method. For example,
class Main {
// 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,
That is,
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// using parseInt()
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 {
// using parseInt()
We can also convert the string variables into an object of Integer using the valueOf() method. For example,
class Main {
// using valueOf()
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,
That is,
// valueOf() returns object of Integer
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// using valueOf()
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.
We can also convert the int variable into string using the toString() method of the Integer class. For example,
class Main {
// using toString()
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 {
// using + sign
System.out.println(str1); // 3476
System.out.println(str2); // 8656
Here, we are using the string concatenation operation to convert an integer into the string. To learn more, visit
Java String concatenation.
class Main {
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().
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
int a =33;
int b = 29;
// 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.
We can also convert the int type variable into an object of the Double class. For example,
class Main {
int a = 332;
// using valueOf()
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.
To understand this example, you should have the knowledge of the following Java programming topics:
class Main {
double a = 23.78D;
double b = 52.11D;
// 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.
We can also convert the double type variable into int using the Math.round() method. For example,
class Main {
double a = 99.99D;
double b = 52.11D;
// 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
The Math.round() method rounds the decimal value to the closest long value. To learn more, visit the Java Math
round().
We can also convert an instance of Double class to int using the intValue() method. For example,
class Main {
// using intValue()
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Variables and (Primitive) Data Types
Java String
class Main {
// using parseDouble()
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 {
// using parseDouble()
We can also convert the string variables into a double using the valueOf() method. For example,
class Main {
// using valueOf()
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,
That is,
class Main {
// using valueOf()
System.out.println(value); // 614.33
}
}
In the above example, we have created a string named str. Notice the line,
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// using valueOf()
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.
We can also convert the double variables into strings using the toString() method of the Double class. For
example,
class Main {
// using toString()
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.
class Main {
// using + sign
System.out.println(str1); // 347.6
System.out.println(str2); // 86.56
Here, we are using the string concatenation operation to convert a double variable into the string. To learn
more, visit Java String concatenation.
class Main {
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:
class Main {
int var1 = 5;
Output
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
class Main {
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Arrays
import java.util.Arrays;
import java.util.Scanner;
class Main {
if (sortOrder == 1) {
array[j + 1] = temp;
else {
array[j + 1] = temp;
}
}
// driver code
// create an array
bs.bubbleSort(data);
System.out.println(Arrays.toString(data));
Output 1
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
1 for Ascending
2 for Descending
Sorted Array:
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Arrays
import java.util.Arrays;
class Main {
// divide the array on the basis of pivot
i++;
array[i] = array[j];
array[j] = temp;
}
// put pivot in position
array[i + 1] = array[high];
array[high] = temp;
return (i + 1);
quickSort(array, pi + 1, high);
// Driver code
int[] data = { 8, 7, 2, 1, 0, 9, 6 };
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:
If you want to learn more about the quick sort algorithm, visit Quick Sort Algorithm.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Arrays
Example: Java Program to Implement Merge Sort Algorithm
import java.util.Arrays;
class Main {
int n1 = q - p + 1;
int n2 = r - q;
int i, j, k;
i = 0;
j = 0;
k = p;
array[k] = L[i];
i++;
} else {
array[k] = M[j];
j++;
k++;
array[k] = L[i];
i++;
k++;
array[k] = M[j];
j++;
k++;
// Divide the array into two sub arrays, sort them and merge them
// m is the point where the array is divided into two sub arrays
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array));
Output 1
Unsorted Array:
Sorted Array:
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:
If you want to learn more about the merge sort algorithm, visit Merge Sort Algorithm.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
import java.util.Scanner;
class Main {
// Repeat until the pointers low and high meet each other
if (array[mid] == element)
return mid;
low = mid + 1;
else
high = mid - 1;
return -1;
int[] array = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
// get input from user for element to be searched
// element to be searched
input.close();
if (result == -1)
System.out.println("Not found");
else
Output 1
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.
if (array[mid] == element)
return mid;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Constructors
Java Methods
class Main {
int sum;
// first constructor
Main() {
this(5, 2);
// second constructor
void display() {
// main class
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() {..}
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 {
else {
System.out.println("The latest version is: " + version2);
// child class
Main() {
super(11, 8);
// main method
Output
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()).
To understand this example, you should have the knowledge of the following Java programming topics:
Java Constructors
Java Singleton
class Test {
private Test () {
class Main {
Test.instanceMethod();
Output
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.
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 {
// private constructor
private Language() {
if(language == null) {
return language;
class Main {
Language db1;
db1= Language.getInstance();
db1.display();
Output
In the above example, we have created a class named Languages. The class contains,
language - class type private variable
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.
db1 = Language.getInstance();
Here,
Since, getInstance() returns the object of the Language class, the db1 variable is assigned with the returned
object.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Main {
// create an ArrayList
languages.add("java");
languages.add("swift");
languages.add("python");
Output
In the above example, we have created an arraylist named languages. Notice the line,
Here, e -> e.toUpperCase() is a lambda expression. It takes all elements of the arraylist and converts them into
uppercase.
import java.util.ArrayList;
import java.util.Arrays;
class Main {
// create an ArrayList
languages.forEach((e) -> {
result += e.charAt(i);
});
Output
In the above example, we have created an arraylist languages. Notice the line,
languages.forEach((e) -> {
result += e.charAt(i);
});
Here, we are passing lambda expression as an argument to the ArrayList forEach() method. The lambda
expression will reverse each element of the arraylist.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Main {
// calculate sum
int sum = a + b;
return sum;
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java Recursion
class Main {
// create a method
// main method
obj.display();
// execution time
Output
Here, we have used the method nanoTime() of the System class. The nanoTime() method returns the current
value of the running JVM in nanoseconds.
class Main {
if (n != 0) // termination condition
else
return 1;
// main method
obj.factorial(128);
Output
18600 nanoseconds
In the above example, we are calculating the execution time of recursive method named factorial().
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
// Creates a string
try {
stream.read();
stream.read();
stream.read();
stream.close();
catch (Exception e) {
e.getStackTrace();
Output
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()
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
try {
stream.close();
catch (Exception e) {
e.getStackTrace();
Output
In the above example, we have created an input stream named stream. Note the line,
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.
import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class Main {
try {
int i;
output.write(array, 0, i);
catch (Exception e) {
e.getStackTrace();
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.InputStream;
import java.io.FileInputStream;
try {
int i = input.read();
while(i != -1) {
System.out.print((char)i);
i = input.read();
input.close();
catch(Exception e) {
e.getStackTrace();
}
}
Output
In the above example, we have a file named input.txt. The content of the file is
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.
class Test {
import java.io.InputStream;
import java.io.FileInputStream;
try {
// file Test.java is loaded as input stream
int i = input.read();
while(i != -1) {
System.out.print((char)i);
i = input.read();
input.close();
catch(Exception e) {
e.getStackTrace();
Output
class Test {
}
}
In the above example, we have used the FileInputStream class to load the Java file as an input stream.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.File;
class Main {
try {
if (value) {
else {
}
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
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.
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.
import java.io.FileWriter;
class Main {
"System.out.println(\"This is file\");"+
"}"+
"}";
try {
output.write(program);
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class Main {
try {
// Creates a FileInputStream
// Creates a BufferedInputStream
while (i != -1) {
System.out.print((char) i);
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.
import java.io.FileReader;
import java.io.BufferedReader;
class Main {
try {
// Creates a FileReader
// Creates a BufferedReader
// Reads characters
input.read(array);
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 BufferedReader Class to read the file named input.txt.
import java.io.File;
import java.util.Scanner;
class Main {
try {
// create a new file object
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
// close scanner
sc.close();
} catch (Exception e) {
e.getStackTrace();
Output
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
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.File;
class Main {
if(value) {
else {
}
}
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.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class Main {
try {
if(value) {
else {
} 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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Recursion
import java.io.File;
class Main {
try {
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.
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 {
try {
file.delete();
if(directory.delete()) {
System.out.println("Directory Deleted");
else {
} 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.
import java.io.File;
class Main {
if(directory.isDirectory()) {
File[] files = directory.listFiles();
if(files != null) {
deleteDirectory(file);
if(directory.delete()) {
else {
try {
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
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.io.File;
class Main {
if(index > 0) {
fileName.lastIndexOf('.') - Returns the last occurrence of character. Since all file extension starts with '.', we use
the character '.'.
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 {
if(index > 0) {
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,
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 String
Example 1: Get file name from the absolute path using getName()
import java.io.File;
class Main {
Output
We can also get the name of the file from its absolute path using the string methods.
import java.io.File;
class Main {
if(index > 0) {
Output
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 {
try {
} catch (Exception e) {
e.getStackTrace();
Output
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.
relativize() - extracts the relative path by comparing two absolute paths with one another
Recommended Reading:
Java File
Example 2: Get a relative path from two absolute path using String methods
import java.io.File;
class Main {
Output
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 {
Output
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:
To understand this example, you should have the knowledge of the following Java programming topics:
Java File 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 {
int count = 0;
try {
while(sc.hasNextLine()) {
sc.nextLine();
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
In this case, we have a file name input.txt with the following content
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
return false;
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
i++;
// check if first character of result matches the first character of second string
j++;
else {
return false;
k++;
return false;
return true;
}
public static void main(String[] args) {
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
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.
Java Methods
class Graph {
// inner class
class Edge {
Edge[] edge;
this.vertices = vertices;
this.edges = edges;
int noVertices = 5;
int noEdges = 8;
// create graph
g.edge[0].dest = 2;
g.edge[1].dest = 3;
g.edge[2].dest = 4;
g.edge[3].dest = 4;
g.edge[4].dest = 5;
g.edge[5].dest = 4;
g.edge[7].dest = 5;
// print graph
Output
1-2
1-3
1-4
2-4
2-5
3-4
3-5
4-5
Graph Output
In the above example, we have implemented the graph data structure in Java. To learn more about graphs, visit
Graph Data Structure.
To understand this example, you should have the knowledge of the following Java programming topics:
Java if, if...else Statement
Java Operators
else
Output
If you change the value of number to a negative number (say -12.3), the output will be:
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:
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// using == operator
Output
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.
class Main {
// using == operator
Output
Here, name1 and name2 both are refering to the same object. Hence, name1 == name2 returns true.
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// create a string
switch(language) {
case "Java":
break;
case "JavaScript":
break;
case "Python":
break;
default:
break;
Output
In the above example, we have implemented the switch statement on Strings. This feature was introduced in
Java 7.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Operators
Example 1: Calculate Simple Interest in Java
import java.util.Scanner;
class Main {
rate = rate/100;
input.close();
}
Output
Principal: 1000.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.
import java.util.Scanner;
class Main {
input.close();
Output
Principal: 1000.0
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
When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java
does not support multiple inheritance.
interface Backend {
// abstract class
class Frontend {
java.connectServer();
java.responsive(java.language);
Output
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.
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
class Main {
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,
// 10.0
System.getProperty("os.version");
Here, the key os.version returns the version of the operating system.
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:
import java.util.Scanner;
class Main {
boolean first;
boolean second;
boolean third;
boolean result;
first = input.nextBoolean();
third = input.nextBoolean();
if(first) {
// if first is true
else {
// if first is false
if(result) {
else {
input.close();
}
}
Output 1
Output 2
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) {
else {
Here, instead of the if...else statement, we can also use the ternary operator.
Java enums
Java EnumSet
enum Size {
class Main {
Output 1
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.
import java.util.EnumSet;
// create an enum
enum Size {
class Main {
Output
Elements of EnumSet:
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:
import java.time.LocalDate;
import java.time.Month;
else {
Output 1
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java LinkedList
Java Generics
class LinkedList {
Node head;
// static inner class
int value;
Node next;
Node(int d) {
value = d;
next = null;
linkedList.head.next = second;
second.next = third;
// printing node-value
System.out.print("LinkedList: ");
while (linkedList.head != null) {
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.
Java provides a built LinkedList class that can be used to implement a linked list.
import java.util.LinkedList;
class Main {
animals.add("Dog");
// add element at the beginning of linked list
animals.addFirst("Cat");
animals.addLast("Horse");
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Stack Class
Java Generics
class Stack {
// Creating a stack
Stack(int size) {
capacity = size;
top = -1;
if (isFull()) {
System.out.println("Stack OverFlow");
arr[++top] = x;
// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
System.exit(1);
return arr[top--];
return top + 1;
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
stack.printStack();
}
Output
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
1, 2,
In the above example, we have implemented the stack data structure in Java.
Java provides a built Stack class that can be used to implement a stack.
import java.util.Stack;
class Main {
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
animals.pop();
Output
In the above example, we have used the Stack class to implement the stack in Java. Here,
Notice, we have used the angle brackets <String> while creating the stack. It represents that the stack is of the
generic type.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Generics
int SIZE = 5;
front = -1;
rear = -1;
boolean isFull() {
return true;
return false;
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
// 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++;
items[rear] = element;
int deQueue() {
int element;
// if queue is empty
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
else {
element = items[front];
front = -1;
rear = -1;
else {
// mark next element as the front
front++;
return (element);
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
else {
q.deQueue();
q.enQueue(i);
q.enQueue(6);
q.display();
q.deQueue();
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.
Java provides a built Queue interface that can be used to implement a queue.
import java.util.Queue;
import java.util.LinkedList;
class Main {
// enqueue
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
// dequeue
Output
Queue: [1, 2, 3]
Removed Element: 1
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.
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
To understand this example, make sure you first visit the following tutorials,
class LinkedList {
Node head;
int value;
Node next;
Node(int d) {
value = d;
next = null;
}
linkedList.head.next = second;
second.next = third;
System.out.print("LinkedList: " );
pointer = pointer.next;
ptr1 = ptr1.next;
if(ptr1.next !=null) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
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,
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 {
animals.add("Dog");
animals.addFirst("Cat");
animals.addLast("Horse");
Output
LinkedList: [Cat, Dog, Horse]
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)
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 Array
import java.util.LinkedList;
class Main {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.toArray(arr);
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
Output
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.
import java.util.Arrays;
import java.util.LinkedList;
class Main {
Output
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 String
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
Output
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.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
Output
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().
import java.util.ArrayList;
import java.util.Arrays;
class Main {
// create a string
String str = "Java, JavaScript, Python";
Output
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().
Arrays.asList(arr)
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.ArrayList;
class Main {
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
System.out.print(languages.get(i));
System.out.print(", ");
Output
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 {
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
System.out.print(language);
System.out.print(", ");
Output
Here, we have used the for-each loop to iterate over the ArrayList and print each element.
import java.util.ArrayList;
import java.util.ListIterator;
class Main {
// Creating an ArrayList
numbers.add(1);
numbers.add(3);
numbers.add(2);
while(iterate.hasNext()) {
Output
ArrayList: [1, 3, 2]
1, 3, 2,
In the above example, we have used the listIterator() method to iterate over the arraylist. Here,
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
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
import java.util.HashMap;
import java.util.Map.Entry;
class Main {
// Creating a HashMap
languages.put("Java", "Enterprise");
languages.put("Python", "ML/AI");
languages.put("JavaScript", "Frontend");
System.out.print("Entries: ");
System.out.print(entry);
System.out.print(", ");
}
// iterating through keys
System.out.print("\nKeys: ");
System.out.print(key);
System.out.print(", ");
System.out.print("\nValues: ");
System.out.print(value);
System.out.print(", ");
Output
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.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
class Main {
// create a HashMap
languages.put("Java", "Enterprise");
languages.put("Python", "ML/AI");
languages.put("JavaScript", "Frontend");
System.out.print("Entries: ");
while(iterate1.hasNext()) {
System.out.print(iterate1.next());
System.out.print(", ");
System.out.print("\nKeys: ");
while(iterate2.hasNext()) {
System.out.print(iterate2.next());
System.out.print(", ");
System.out.print("\nValues: ");
while(iterate3.hasNext()) {
System.out.print(iterate3.next());
System.out.print(", ");
Output
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,
Note: We can also use the HashMap forEach() method to iterate over the hashmap.
To understand this example, you should have the knowledge of the following Java programming topics:
Java HashSet Class
import java.util.Set;
import java.util.HashSet;
class Main {
// Creating an set
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
System.out.print(language);
System.out.print(", ");
Output
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
class Main {
// Creating an Set
numbers.add(1);
numbers.add(3);
numbers.add(2);
while(iterate.hasNext()) {
Output
Set: [1, 2, 3]
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,
import java.util.Set;
import java.util.HashSet;
class Main {
// create an Set
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.forEach((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) -> {
});
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java List
import java.util.ArrayList;
import java.util.List;
class Main {
prime.add(2);
prime.add(3);
prime.add(5);
even.add(4);
even.add(6);
numbers.addAll(prime);
numbers.addAll(even);
Output
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.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
}
Output
In the above example, we have used the Stream class to merge the two lists. Here,
To understand this example, you should have the knowledge of the following Java programming topics:
Java HashMap
import java.util.HashMap;
class Main {
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Second", value);
Output
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.
import java.util.HashMap;
class Main {
numbers.put("First", 1);
numbers.put("Second", 2);
// Using computeIfPresent()
numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2);
Output
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.
import java.util.HashMap;
class Main {
numbers.put("First", 1);
numbers.put("Second", 2);
}
}
Output
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().
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
class Main {
set.addAll(numbers);
// delete al elements of arraylist
numbers.clear();
numbers.addAll(set);
Output
In the above example, we have created an arraylist named numbers. The arraylist contains duplicate elements.
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.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
stream = stream.distinct();
numbers = (ArrayList<Integer>)stream.collect(Collectors.toList());
Output
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.
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
import java.util.HashMap;
import java.util.Map.Entry;
class Main {
// create a hashmap
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
Integer value = 3;
break;
Output
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,
Here, the entrySet() method returns a set view of all the entries.
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java LinkedList
Java Methods
class LinkedList {
// create an object of Node class
Node head;
int value;
Node next;
Node(int d) {
value = d;
next = null;
first = first.next.next;
if(first == second) {
return true;
return false;
linkedList.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = second;
// printing node-value
System.out.print("LinkedList: ");
int i = 1;
while (i <= 4) {
linkedList.head = linkedList.head.next;
i++;
if(loop) {
else {
Output
LinkedList: 1 2 3 4
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.
Two nodes are traversing at different speeds. Hence, they will meet if there is a loop in LinkedList.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.HashSet;
import java.util.Set;
class Main {
evenNumbers.add(2);
evenNumbers.add(4);
numbers.add(1);
numbers.add(3);
numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);
Output
Set1: [2, 4]
Set2: [1, 3]
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.
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
class Main {
languages1.add("Java");
languages1.add("Python");
languages2.add("Spanish");
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.HashSet;
import java.util.Set;
class Main {
primeNumbers.add(2);
primeNumbers.add(3);
evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.retainAll(primeNumbers);
Output
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.
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
class Main {
backend.add("Java");
backend.add("JavaScript");
frontend.add("JavaScript");
frontend.add("CSS");
Output
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:
import java.util.HashSet;
import java.util.Set;
class Main {
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
primeNumbers.add(2);
primeNumbers.add(3);
numbers.removeAll(primeNumbers);
System.out.println("Numbers without prime numbers: " + numbers);
Output
Numbers: [1, 2, 3, 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.
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
class Main {
languages1.add("Java");
languages1.add("JavaScript");
languages1.add("English");
languages1.add("Spanish");
languages2.add("English");
languages2.add("Spanish");
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java TreeSet
import java.util.HashSet;
import java.util.Set;
class Main {
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
primeNumbers.add(2);
primeNumbers.add(3);
Output
Numbers: [1, 2, 3, 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.containsAll(primeNumbers);
Here, we have used the containsAll() method to check if primeNumbers is the subset of numbers.
import java.util.TreeSet;
import java.util.Set;
class Main {
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
languages.add("CSS");
frontend.add("CSS");
frontend.add("JavaScript");
}
Output
To understand this example, you should have the knowledge of the following Java programming topics:
Java HashMap
Java TreeMap
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
class Main {
// create a hashmap
languages.put("pos3", "JS");
languages.put("pos1", "Java");
languages.put("pos2", "Python");
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Arrays
import java.util.ArrayList;
class Main {
System.out.print("ArrayList: ");
}
}
// create an arraylist
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
display(languages);
Output
In the above example, we have created an arraylist named languages. Here, we have a method display(). It prints
elements of arraylist.
display(languages);
import java.util.ArrayList;
class Main {
int obtainedMarks = 0;
obtainedMarks += mark;
// compute average
// create an arraylist
marks.add(67);
marks.add(87);
marks.add(56);
percentage(marks.toArray(new Integer[marks.size()]));
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
import java.util.ArrayList;
class Main {
// create an ArrayList
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
// print arraylist
System.out.print("ArrayList: ");
languages.forEach((e) -> {
});
}
Output
In the above example, we have created an arraylist named languages. Notice the code,
languages.forEach((e) -> {
});
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Node {
int key;
key = item;
class BinaryTree {
Node root;
// Traverse tree
if (node != null) {
traverseTree(node.left);
traverseTree(node.right);
tree.traverseTree(tree.root);
Output
Binary Tree: 4 2 1 3
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Node {
int item;
item = key;
class Tree {
// root of Tree
Node root;
Tree() {
root = null;
if (node == null)
return;
System.out.print(node.item + "->");
preorder(node.left);
preorder(node.right);
tree.preorder(tree.root);
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:
Tree Traversal
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Node {
int item;
item = key;
class Tree {
Node root;
Tree() {
root = null;
if (node == null)
return;
postorder(node.left);
postorder(node.right);
System.out.print(node.item + "->");
System.out.println("Postorder traversal");
tree.postorder(tree.root);
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:
Tree Traversal
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Node {
int item;
Node left, right;
item = key;
class Tree {
// root of Tree
Node root;
Tree() {
root = null;
if (node == null)
return;
inOrder(node.left);
System.out.print(node.item + "->");
inOrder(node.right);
}
public static void main(String[] args) {
tree.inOrder(tree.root);
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:
Tree Traversal
Binary Tree Implementation in Java
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Node {
int item;
item = key;
class Main {
// root of Tree
Node root;
Main() {
root = null;
if(node == null) {
return 0;
// it is leaf node
return 1;
else {
Output
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:
To understand this example, you should have the knowledge of the following Java programming topics:
Java String
class Main {
// create a string
// using contains()
if(result) {
else {
result = txt.contains(str2);
if(result) {
else {
Output
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.
class Main {
public static void main(String[] args) {
// create a string
// using indexOf()
if(result == -1) {
else {
// using indexOf()
result = txt.indexOf(str2);
if(result == -1) {
else {
Output
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
class Test {
// private variables
// initialize age
this.age = age;
// initialize name
this.name = name;
// access age
// access name
return this.name;
class Main {
test.setAge(24);
test.setName("Programiz");
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
import java.lang.reflect.*;
class Test {
// private variables
// private method
class Main {
try {
field.setAccessible(true);
field.set(test, "Programiz");
catch(Exception e) {
e.printStackTrace();
Output
Name: Programiz
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.