You are on page 1of 83

Java Program to Calculate average using

Array
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

We will see two programs to find the average of numbers using array. First
Program finds the average of specified array elements. The second programs
takes the value of n (number of elements) and the numbers provided by user
and finds the average of them using array.

To understand these programs you should have the knowledge of


following Java Programming concepts:
1) Java Arrays
2) For loop

Example 1: Program to find the average of


numbers using array
public class JavaExample {

public static void main(String[] args) {


double[] arr = {19, 12.89, 16.5, 200, 13.7};
double total = 0;

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


total = total + arr[i];
}

/* arr.length returns the number of elements


* present in the array
*/
double average = total / arr.length;

/* This is used for displaying the formatted output


* if you give %.4f then the output would have 4 digits
* after decimal point.
*/
System.out.format("The average is: %.3f", average);
}
}
Output:

The average is: 52.418

Example 2: Calculate average of numbers


entered by user
In this example, we are using Scanner to get the value of n and all the
numbers from user.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {


System.out.println("How many numbers you want to enter?");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
/* Declaring array of n elements, the value
* of n is provided by the user
*/
double[] arr = new double[n];
double total = 0;

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


System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = scanner.nextDouble();
}
scanner.close();
for(int i=0; i<arr.length; i++){
total = total + arr[i];
}

double average = total / arr.length;

System.out.format("The average is: %.3f", average);


}
}
Output:

How many numbers you want to enter?


5
Enter Element No.1: 12.7
Enter Element No.2: 18.9
Enter Element No.3: 20
Enter Element No.4: 13.923
Enter Element No.5: 15.6
The average is: 16.225

Java Program to print Pascal Triangle


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this tutorial, we will write a java program to print Pascal Triangle.

Java Example to print Pascal’s Triangle


In this program, user is asked to enter the number of rows and based on the
input, the pascal’s triangle is printed with the entered number of rows.

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample {
static int fact(int num) {
int factorial;

for(factorial = 1; num > 1; num--){


factorial *= num;
}
return factorial;
}
static int ncr(int n,int r) {
return fact(n) / ( fact(n-r) * fact(r) );
}
public static void main(String args[]){
int rows, i, j;

//getting number of rows from user


System.out.println("Enter number of rows:");
Scanner scanner = new Scanner(System.in);
rows = scanner.nextInt();
scanner.close();

System.out.println("Pascal Triangle:");
for(i = 0; i < rows; i++) {
for(j = 0; j < rows-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+ncr(i, j));
}
System.out.println();
}
}
}
Output:
Java Program to Find square root of a
Number without sqrt
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Finding square root of a number is very easy, we can use the Math.sqrt()method


to find out the square root of any number. However in this tutorial we will do
something different, we will write a java program to find the square root of a
number without the sqrt() method.

Java Example to find the square root without


sqrt() method
In the following program we have created a method squareRoot(), in the
method we have written a equation which is used for finding out the square
root of a number. For the equation we have used do while loop.

package com.beginnersbook;
import java.util.Scanner;
class JavaExample {

public static double squareRoot(int number) {


double temp;

double sr = number / 2;

do {
temp = sr;
sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);

return sr;
}

public static void main(String[] args)


{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.close();

System.out.println("Square root of "+ num+ " is: "+squareRoot(num));


}
}
Output:
Java Program to Check if given Number is
Perfect Square
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this tutorial, we will write a java program to check if a given number is


perfect square.

Java Example to check if a number is perfect


square
In this program, we have created a user-defined method checkPerfectSquare()that
takes a number as an argument and returns true if the number is perfect
square else it returns false.

In the user defined method we are using two methods of the Math
class, sqrt() method and floor() method. The Math.sqrt() method finds the square
root of the given number and the floor() method finds the closest integer of the
square root value returned by sqrt() method. Later we have calculated the
difference between these two to check whether the difference is zero or non-
zero. For a perfect square number this difference should be zero as the
square root of perfect square number is integer itself.

package com.beginnersbook;
import java.util.Scanner;
class JavaExample {

static boolean checkPerfectSquare(double x)


{

// finding the square root of given number


double sq = Math.sqrt(x);

/* Math.floor() returns closest integer value, for


* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
}

public static void main(String[] args)


{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
double num = scanner.nextDouble();
scanner.close();

if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
}
}
Output:
Related Java Examples

Java Program to break Integer into Digits


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this tutorial, we will write a java program to break an input integer number
into digits. For example if the input number is 912 then the program should
display digits 2, 1, 9 along with their position in the output.

Java Example to break integer into digits


Here we are using Scanner class to get the input from user. In the first while
loop we are counting the digits in the input number and then in the second
while loop we are extracting the digits from the input number using modulus
operator.

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int num, temp, digit, count = 0;

//getting the number from user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter any number:");
num = scanner.nextInt();
scanner.close();

//making a copy of the input number


temp = num;

//counting digits in the input number


while(num > 0)
{
num = num / 10;
count++;
}
while(temp > 0)
{
digit = temp % 10;
System.out.println("Digit at place "+count+" is: "+digit);
temp = temp / 10;
count--;
}
}
}
Output:
Java******************************************************************************
**********************************************************************************
*******************************************************************************

Java Program to check Even or Odd


number
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

import java.util.Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output 1:

Enter an Integer number:


78
Entered number is even
Output 2:

Enter an Integer number:


77
Entered number is odd

Java program for linear search – Example


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
Example Program:

This program uses linear search algorithm to find out a number among all
other numbers entered by user.

/* Program: Linear Search Example


* Written by: Chaitanya from beginnersbook.com
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();

for (counter = 0; counter < num; counter++)


{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}
Output 1:

Enter number of elements:


6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3
Output 2:

Enter number of elements:


4
Enter 4 integers
11
22
4
5
Enter the search value:
99
99 doesn't exist in array.

Java program to perform binary search –


Example
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Example Program to perform binary search on a list of integer


numbers

This program uses binary search algorithm to search an element in given list


of elements.

/* Program: Binary Search Example


* Written by: Chaitanya from beginnersbook.com
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import java.util.Scanner;
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();

//Creating array to store the all the numbers


array = new int[num];

System.out.println("Enter " + num + " integers");


//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;

while( first <= last )


{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}
}
Output 1:

Enter number of elements:


7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.
Output 2:

Enter number of elements:


5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.
Java program to print Floyd’s triangle –
Example
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Example Program:

This program will prompt user for number of rows and based on the input, it
would print the Floyd’s triangle having the same number of rows.

/* Program: It Prints Floyd's triangle based on user inputs


* Written by: Chaitanya from beginnersbook.com
* Input: Number of rows
* output: floyd's triangle*/
import java.util.Scanner;
class FloydTriangleExample
{
public static void main(String args[])
{
int rows, number = 1, counter, j;
//To get the user's input
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows for floyd's triangle:");
//Copying user input into an integer variable named rows
rows = input.nextInt();
System.out.println("Floyd's triangle");
System.out.println("****************");
for ( counter = 1 ; counter <= rows ; counter++ )
{
for ( j = 1 ; j <= counter ; j++ )
{
System.out.print(number+" ");
//Incrementing the number value
number++;
}
//For new line
System.out.println();
}
}
}
Output:

Enter the number of rows for floyd's triangle:


6
Floyd's triangle
****************
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Java program to reverse a number using
for, while and recursion
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

There are three ways to reverse a number in Java.

1) Using while loop


2) Using for loop
3) Using recursion
4) Reverse the number without user interaction

Program 1: Reverse a number using while Loop


The program will prompt user to input the number and then it will reverse the same number
using while loop.

import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of input number is: "+reversenum);


}
}
Output:

Input your number and press enter:


145689
Reverse of input number is: 986541
Program 2: Reverse a number using for Loop
import java.util.Scanner;
class ForLoopReverseDemo
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
/* for loop: No initialization part as num is already
* initialized and no increment/decrement part as logic
* num = num/10 already decrements the value of num
*/
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of specified number is: "+reversenum);


}
}
Output:

Input your number and press enter:


56789111
Reverse of specified number is: 11198765
Program 3: Reverse a number using recursion
import java.util.Scanner;
class RecursionReverseDemo
{
//A method for reverse
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0;
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();
}
}
Output:
Input your number and press enter:
5678901
Reverse of the input number is:1098765
Example: Reverse an already initialized number
In all the above programs we are prompting user for the input number, however if do not
want the user interaction part and want to reverse an initialized number then this is how you
can do it.

class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of specified number is: "+reversenum);


}
}
Output:

Reverse of specified number is: 987654321

Java program to generate random number


– Example
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Example Program to generate random numbers

In the below program, we are using the nextInt() method of Random class to serve


our purpose.

/* Program: Random number generator


* Written by: Chaitanya from beginnersbook.com
* Input: None
* Output:Random number between o and 200*/
import java.util.*;
class GenerateRandomNumber {
public static void main(String[] args) {
int counter;
Random rnum = new Random();
/* Below code would generate 5 random numbers
* between 0 and 200.
*/
System.out.println("Random Numbers:");
System.out.println("***************");
for (counter = 1; counter <= 5; counter++) {
System.out.println(rnum.nextInt(200));
}
}
}
Output:

Random Numbers:
***************
135
173
5
17
15
The output of above program would not be same everytime. It would generate
any 5 random numbers between 0 and 200 whenever you run this code. For
e.g. When I ran it second time, it gave me the below output, which is entirely
different from the above one.

Output 2:

Random Numbers:
***************
46
99
191
7
134

Java Program to display first n or first 100


prime numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Program to display first n prime numbers

import java.util.Scanner;

class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
//The entered value is stored in the var n
n = scanner.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are:");
//2 is a known prime number
System.out.println(2);
}

for ( int i = 2 ; i <=n ; )


{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
Output:

Enter the value of n:


15
First 15 prime numbers are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
Program to display first 100 prime numbers
To display the first 100 prime numbers, you can either enter n value as 100
in the above program OR write a program like this:

class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
System.out.println("First 100 prime numbers are:");
System.out.println(2);
for ( int i = 2 ; i <=100 ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
Output:

First 100 prime numbers are:


2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541

Java Program to Sort Strings in an


Alphabetical Order
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this java tutorial, we will learn how to sort Strings in an Alphabetical Order.

Java Example: Arranging Strings in an


Alphabetical Order
In this program, we are asking user to enter the count of strings that he would
like to enter for sorting. Once the count is captured using Scanner class, we
have initialized a String array of the input count size and then are running a for
loop to capture all the strings input by user.

Once we have all the strings stored in the string array, we are comparing the
first alphabet of each string to get them sorted in the alphabetical order.

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings


System.out.print("Enter number of strings you would like to enter:");
count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored in an array


System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}

//Displaying the strings after sorting them based on alphabetical order


System.out.print("Strings in Sorted Order:");
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}
Output:

Java Program to reverse words in a String


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

This program reverses every word of a string and display the reversed string
as an output. For example, if we input a string as “Reverse the word of this
string” then the output of the program would be: “esrever eht drow fo siht
gnirts”.

To understand this program you should have the knowledge of following Java


Programming topics:

1. For loop in Java


2. Java String split() method
3. Java String charAt() method

Example: Program to reverse every word in a


String using methods
In this Program, we first split the given string into substrings using split()
method. The substrings are stored in an String array words. The program then
reverse each word of the substring using a reverse for loop.
public class Example
{
public void reverseWordInMyString(String str)
{
/* The split() method of String class splits
* a string in several strings based on the
* delimiter passed as an argument to it
*/
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(str);
System.out.println(reversedString);
}
public static void main(String[] args)
{
Example obj = new Example();
obj.reverseWordInMyString("Welcome to BeginnersBook");
obj.reverseWordInMyString("This is an easy Java Program");
}
}
Output:

Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP

Java program to reverse a number using


for, while and recursion
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

There are three ways to reverse a number in Java.

1) Using while loop


2) Using for loop
3) Using recursion
4) Reverse the number without user interaction

Program 1: Reverse a number using while Loop


The program will prompt user to input the number and then it will reverse the
same number using while loop.

import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of input number is: "+reversenum);


}
}
Output:

Input your number and press enter:


145689
Reverse of input number is: 986541
Program 2: Reverse a number using for Loop
import java.util.Scanner;
class ForLoopReverseDemo
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
/* for loop: No initialization part as num is already
* initialized and no increment/decrement part as logic
* num = num/10 already decrements the value of num
*/
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of specified number is: "+reversenum);


}
}
Output:

Input your number and press enter:


56789111
Reverse of specified number is: 11198765
Program 3: Reverse a number using recursion
import java.util.Scanner;
class RecursionReverseDemo
{
//A method for reverse
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0;
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();
}
}
Output:

Input your number and press enter:


5678901
Reverse of the input number is:1098765
Example: Reverse an already initialized number
In all the above programs we are prompting user for the input number,
however if do not want the user interaction part and want to reverse an
initialized number then this is how you can do it.

class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of specified number is: "+reversenum);


}
}
Output:

Reverse of specified number is: 987654321

Java Program to Reverse a String using


Recursion
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

We will see two programs to reverse a string. First program reverses the given
string using recursion and the second program reads the string entered by
user and then reverses it.

To understand these programs you should have the knowledge of


following core java concepts:
1) substring() in java
2) charAt() method

Example 1: Program to reverse a string


public class JavaExample {

public static void main(String[] args) {


String str = "Welcome to Beginnersbook";
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}

public static String reverseString(String str)


{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output:

The reversed string is: koobsrennigeB ot emocleW

Example 2: Program to reverse a string entered


by user
import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {


String str;
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
scanner.close();
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}

public static String reverseString(String str)


{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output:

Enter your username:


How are you doing?
The reversed string is: ?gniod uoy era woH

Java program to calculate area of Triangle


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will see how to calculate area of triangle. We will see two following
programs to do this:
1) Program 1: Prompt user for base-width and height of triangle.
2) Program 2: No user interaction: Width and height are specified in the
program itself.

Program 1:

/**
* @author: BeginnersBook.com
* @description: Program to Calculate area of Triangle in Java
* with user interaction. Program will prompt user to enter the
* base width and height of the triangle.
*/
import java.util.Scanner;
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the width of the Triangle:");


double base = scanner.nextDouble();

System.out.println("Enter the height of the Triangle:");


double height = scanner.nextDouble();

//Area = (width*height)/2
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
Output:

Enter the width of the Triangle:


2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0
Program 2:

/**
* @author: BeginnersBook.com
* @description: Program to Calculate area of Triangle
* with no user interaction.
*/
class AreaTriangleDemo2 {
public static void main(String args[]) {
double base = 20.0;
double height = 110.5;
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
Output:

Area of Triangle is: 1105.0


Java program to get IP address
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this example we are gonna see how to get IP address of a System. The
steps are as follows:

1) Get the local host address by calling getLocalHost() method of InetAddress


class.
2) Get the IP address by calling getHostAddress() method.

import java.net.InetAddress;

class GetMyIPAddress
{
public static void main(String args[]) throws Exception
{
/* public static InetAddress getLocalHost()
* throws UnknownHostException: Returns the address
* of the local host. This is achieved by retrieving
* the name of the host from the system, then resolving
* that name into an InetAddress. Note: The resolved
* address may be cached for a short period of time.
*/
InetAddress myIP=InetAddress.getLocalHost();

/* public String getHostAddress(): Returns the IP


* address string in textual presentation.
*/
System.out.println("My IP Address is:");
System.out.println(myIP.getHostAddress());
}
}
Output:

My IP Address is:
115.242.7.243
Reference:
InetAddress javadoc

Java Program to Swap two numbers using


Bitwise XOR Operator
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
This java program swaps two numbers using bitwise XOR operator. Before
going though the program, lets see what is a bitwise XOR operator: A bitwise
XOR compares corresponding bits of two operands and returns 1 if they are
equal and 0 if they are not equal. For example:

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */
num1 ^ num2 compares corresponding bits of num1 and num2 and
generates 1 if they are not equal, else it returns 0. In our example it would
return 29 which is equivalent to 00011101

Let’s write this in a Java program:

Example: Swapping two numbers using bitwise


operator
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner.nextInt();
System.out.print("Enter second number:");
num2 = scanner.nextInt();
/* To make you understand, lets assume I am going
* to enter value of first number as 10 and second
* as 5. Binary equivalent of 10 is 1010 and 5 is
* 0101
*/

//num1 becomes 1111 = 15


num1 = num1 ^ num2;
//num2 becomes 1010 = 10
num2 = num1 ^ num2;
//num1 becomes 0101 = 5
num1 = num1 ^ num2;
scanner.close();
System.out.println("The First number after swapping:"+num1);
System.out.println("The Second number after swapping:"+num2);
}
}
Output:

Enter first number:10


Enter second number:5
The First number after swapping:5
The Second number after swapping:10
Java Program to Sort Strings in an
Alphabetical Order
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this java tutorial, we will learn how to sort Strings in an Alphabetical Order.

Java Example: Arranging Strings in an


Alphabetical Order
In this program, we are asking user to enter the count of strings that he would
like to enter for sorting. Once the count is captured using Scanner class, we
have initialized a String array of the input count size and then are running a for
loop to capture all the strings input by user.

Once we have all the strings stored in the string array, we are comparing the
first alphabet of each string to get them sorted in the alphabetical order.

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings


System.out.print("Enter number of strings you would like to enter:");
count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored in an array


System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}

//Displaying the strings after sorting them based on alphabetical order


System.out.print("Strings in Sorted Order:");
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}
Output:

Related Ja

Java Program to calculate and display


Student Grades
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
This program calculates the grade of a student based on the marks entered by
user in each subject. Program prints the grade based on this logic.
If the average of marks is >= 80 then prints Grade ‘A’
If the average is <80 and >=60 then prints Grade ‘B’
If the average is <60 and >=40 then prints Grade ‘C’
else prints Grade ‘D’

To understand this Program you should have the knowledge of following


concepts of Java:

 Java For Loop


 Arrays in Java
 if..else-if in Java

Example: Program to display the grade of


student
import java.util.Scanner;

public class JavaExample


{
public static void main(String args[])
{
/* This program assumes that the student has 6 subjects,
* thats why I have created the array of size 6. You can
* change this as per the requirement.
*/
int marks[] = new int[6];
int i;
float total=0, avg;
Scanner scanner = new Scanner(System.in);

for(i=0; i<6; i++) {


System.out.print("Enter Marks of Subject"+(i+1)+":");
marks[i] = scanner.nextInt();
total = total + marks[i];
}
scanner.close();
//Calculating average here
avg = total/6;
System.out.print("The student Grade is: ");
if(avg>=80)
{
System.out.print("A");
}
else if(avg>=60 && avg<80)
{
System.out.print("B");
}
else if(avg>=40 && avg<60)
{
System.out.print("C");
}
else
{
System.out.print("D");
}
}
}
Output:

Enter Marks of Subject1:40


Enter Marks of Subject2:80
Enter Marks of Subject3:80
Enter Marks of Subject4:40
Enter Marks of Subject5:60
Enter Marks of Subject6:60
The student Grade is: B

Java program to display prime numbers


from 1 to 100 and 1 to n
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The number which is only divisible by itself and 1 is known as prime number.
For example 2, 3, 5, 7…are prime numbers. Here we will see two programs:
1) First program will print the prime numbers between 1 and 100 2) Second
program takes the value of n (entered by user) and prints the prime numbers
between 1 and n. If you are looking for a program that checks whether the
entered number is prime or not then see: Java Program to check prime
number.

Program to display the prime numbers from 1 to


100
It will display the prime numbers between 1 and 100.

class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
Output:

Prime numbers from 1 to 100 are :


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Program to display prime numbers from 1 to n


It will display all the prime numbers between 1 and n (n is the number, entered
by user).

import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
Output:

Enter the value of n:


150
Prime numbers from 1 to n are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149

Java Program to check if Number is


Positive or Negative
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this post, we will write two java programs, first java programs checks
whether the specified number is positive or negative. The second program
takes the input number (entered by user) and checks whether it is positive or
negative and displays the result.
→ If a number is greater than zero then it is a positive number
→ If a number is less than zero then it is a negative number
→ If a number is equal to zero then it is neither negative nor positive.

Lets write this logic in a Java Program.

Example 1: Program to check whether the given


number is positive or negative
In this program we have specified the value of number during declaration and
the program checks whether the specified number is positive or negative. To
understand this program you should have the basic knowledge of if-else-if
statement in Core Java Programming.

public class Demo


{
public static void main(String[] args)
{
int number=109;
if(number > 0)
{
System.out.println(number+" is a positive number");
}
else if(number < 0)
{
System.out.println(number+" is a negative number");
}
else
{
System.out.println(number+" is neither positive nor negative");
}
}
}
Output:

109 is a positive number

Example 2: Check whether the input


number(entered by user) is positive or negative
Here we are using Scanner to read the number entered by user and then the
program checks and displays the result.

import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
number = scan.nextInt();
scan.close();
if(number > 0)
{
System.out.println(number+" is positive number");
}
else if(number < 0)
{
System.out.println(number+" is negative number");
}
else
{
System.out.println(number+" is neither positive nor negative");
}
}
}
Output:

Enter the number you want to check:-12


-12 is negative number
Java Program to Add two Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will see two programs to add two numbers, In the first program we
specify the value of both the numbers in the program itself. The second
programs takes both the numbers (entered by user) and prints the sum.

First Example: Sum of two numbers


public class AddTwoNumbers {

public static void main(String[] args) {

int num1 = 5, num2 = 15, sum;


sum = num1 + num2;

System.out.println("Sum of these numbers: "+sum);


}
}
Output:

Sum of these numbers: 20

Second Example: Sum of two numbers using


Scanner
The scanner allows us to capture the user input so that we can get the values
of both the numbers from user. The program then calculates the sum and
displays it.

import java.util.Scanner;
public class AddTwoNumbers2 {

public static void main(String[] args) {

int num1, num2, sum;


Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();

System.out.println("Enter Second Number: ");


num2 = sc.nextInt();

sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140

How to convert a char array to a string in


Java?
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

There are two ways to convert a char array (char[]) to String in Java:
1) Creating String object by passing array name to the constructor
2) Using valueOf() method of String class.

Example:
This example demonstrates both the above mentioned ways of converting a
char array to String. Here we have a char array ch and we have created two
strings str and str1 using the char array.

class CharArrayToString
{
public static void main(String args[])
{
// Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
String str = new String(ch);
System.out.println(str);

// Method 2: Using valueOf method


String str2 = String.valueOf(ch);
System.out.println(str2);
}
}
Output:

good morning
good morning

Java Program to Check Armstrong Number


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will write a java program that checks whether the given number is
Armstrong number or not. We will see the two variation of the same program.
In the first program we will assign the number in the program itself and in
second program user would input the number and the program will check
whether the input number is Armstrong or not.

Before we go through the program, lets see what is an Armstrong number. A


number is called Armstrong number if the following equation holds true for that
number:

xy..z = xn + yn+.....+ zn
where n denotes the number of digits in the number

For example this is a 3 digit Armstrong number

370 = 33 + 73 + o3
= 27 + 343 + 0
= 370
Let’s write this in a program:
To understand this Program you should have the knowledge of following Java
Programming topics:

1. Java while loop


2. Java if..else-if

Example 1: Program to check whether the given


number is Armstrong number
public class JavaExample {

public static void main(String[] args) {

int num = 370, number, temp, total = 0;

number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}

if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:

370 is an Armstrong number


In the above program we have used while loop, However you can also use for
loop. To use for loop replace the while loop part of the program with this code:

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


temp = number % 10;
total = total + temp*temp*temp;
}

Example 2: Program to check whether the input


number is Armstrong or not
import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int num, number, temp, total = 0;


System.out.println("Ënter 3 Digit Number");
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
scanner.close();
number = num;

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


{
temp = number % 10;
total = total + temp*temp*temp;
}

if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:

Ënter 3 Digit Number


371
371 is an Armstrong number

Java program to check prime number


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
The number which is only divisible by itself and 1 is known as prime number,
for example 7 is a prime number because it is only divisible by itself and 1.
This program takes the number (entered by user) and then checks whether
the input number is prime or not. The program then displays the result. If you
are looking for a program that displays the prime number between two
intervals then see: Java program to display prime numbers between 1 to n.

Example: Program to check whether input


number is prime or not
To understand this program you should have the knowledge of for loop, if-else
statements and break statement.

import java.util.Scanner;
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter any number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Output:

Enter any number:


19
19 is a Prime Number
Output 2:

Enter any number:


6
6 is not a Prime Number
You can also use while loop to check the prime number:
Just replace this part of the code in above program:

for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
with this:

int i=2;
while(i<= num/2)
{
if(num % i == 0)
{
isPrime = false;
break;
}
i++;
}

Java Program to Find Factorial using For


and While loop
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

We will write three java programs to find factorial of a number. 1) using for
loop 2) using while loop 3) finding factorial of a number entered by user.
Before going through the program, lets understand what is factorial: Factorial
of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n

The same logic we have implemented in our programs using loops. To


understand these programs you should have a basic knowledge of following
topics of java tutorials:

 For loop in Java


 Java – while loop

Example: Finding factorial using for loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 2: Finding Factorial using while loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 3: Finding factorial of a number


entered by user
Program finds the factorial of input number using while loop.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Enter the number:


6
Factorial of 6 is: 720

java program to find factorial of a given


number using recursion
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will write programs to find out the factorial of a number using


recursion.

Program 1:
Program will prompt user for the input number. Once user provide the input,
the program will calculate the factorial for the provided input number.

/**
* @author: BeginnersBook.com
* @description: User would enter the 10 elements
* and the program will store them into an array and
* will display the sum of them.
*/
import java.util.Scanner;
class FactorialDemo{
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
Output:

Enter the number:


5
Factorial of entered number is: 120
Program 2: 
If you do not want user intervention and simply want to specify the number in
program itself then refer this example.

class FactorialDemo2{
public static void main(String args[]){
int factorial = fact(4);
System.out.println("Factorial of 4 is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
Output:

Factorial of 4 is: 24

Java Program to check Even or Odd


number
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

import java.util.Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output 1:

Enter an Integer number:


78
Entered number is even
Output 2:

Enter an Integer number:


77
Entered number is odd

Java Program to Multiply Two Numbers


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

When you start learning java programming, you get these type of problems in
your assignment. Here we will see two Java programs, first program takes two
integer numbers (entered by user) and displays the product of these numbers.
The second program takes any two numbers (can be integer or floating point)
and displays the result.

Example 1: Program to read two integer and


print product of them
This program asks user to enter two integer numbers and displays the
product. To understand how to use scanner to take user input, checkout this
program: Program to read integer from system input.

import java.util.Scanner;

public class Demo {


public static void main(String[] args) {

/* This reads the input provided by user


* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");

// This method reads the number provided using keyboard


int num1 = scan.nextInt();

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


int num2 = scan.nextInt();

// Closing Scanner after the use


scan.close();

// Calculating product of two numbers


int product = num1*num2;

// Displaying the multiplication result


System.out.println("Output: "+product);
}
}
Output:

Enter first number: 15


Enter second number: 6
Output: 90

Example 2: Read two integer or floating point


numbers and display the multiplication
In the above program, we can only integers. What if we want to calculate the
multiplication of two float numbers? This programs allows you to enter float
numbers and calculates the product.

Here we are using data type double for numbers so that you can enter integer
as well as floating point numbers.

import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

/* This reads the input provided by user


* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");

// This method reads the number provided using keyboard


double num1 = scan.nextDouble();
System.out.print("Enter second number: ");
double num2 = scan.nextDouble();

// Closing Scanner after the use


scan.close();

// Calculating product of two numbers


double product = num1*num2;

// Displaying the multiplication result


System.out.println("Output: "+product);
}
}
Output:

Enter first number: 1.5


Enter second number: 2.5
Output: 3.75

Java Program to check Leap Year


BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will write a java program to check whether the input year is a leap
year or not. Before we see the program, lets see how to determine whether a
year is a leap year mathematically:
To determine whether a year is a leap year, follow these steps:
1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days). Source of these steps.

Example: Program to check whether the input


year is leap or not
Here we are using Scanner class to get the input from user and then we are
using if-else statements to write the logic to check leap year. To understand
this program, you should have the knowledge of following concepts of Core
Java Tutorial:
→ If-else statement
→ Read input number in Java program

import java.util.Scanner;
public class Demo {
public static void main(String[] args) {

int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;

if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}

if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
Output:

Enter any Year:


2001
2001 is not a Leap Year.

Java program to convert decimal to


hexadecimal
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

There are two following ways to convert Decimal number to hexadecimal


number:

1) Using toHexString() method of Integer class.


2) Do conversion by writing your own logic without using any predefined
methods.
Method 1: Decimal to hexadecimal Using toHexString()
method
import java.util.Scanner;
class DecimalToHexExample
{
public static void main(String args[])
{
Scanner input = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =input.nextInt();

// calling method toHexString()


String str = Integer.toHexString(num);
System.out.println("Method 1: Decimal to hexadecimal: "+str);
}
}
Output:

Enter a decimal number : 123


Method 1: Decimal to hexadecimal: 7b
Method 2: Decimal to hexadecimal without using
predefined method
import java.util.Scanner;
class DecimalToHexExample
{
public static void main(String args[])
{
Scanner input = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =input.nextInt();

// For storing remainder


int rem;

// For storing result


String str2="";

// Digits in hexadecimal number system


char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

while(num>0)
{
rem=num%16;
str2=hex[rem]+str2;
num=num/16;
}
System.out.println("Method 2: Decimal to hexadecimal: "+str2);
}
}
Output:

Enter a decimal number : 123


Method 2: Decimal to hexadecimal: 7B

Java program for bubble sort in Ascending


& descending order
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this tutorial we are gonna see how to do sorting in ascending & descending
order using Bubble sort algorithm.

Bubble sort program for sorting in ascending


Order
import java.util.Scanner;

class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

for (i = 0; i < num; i++)


array[i] = input.nextInt();

for (i = 0; i < ( num - 1 ); i++) {


for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}

System.out.println("Sorted list of integers:");

for (i = 0; i < num; i++)


System.out.println(array[i]);
}
}
Output:
Enter the number of integers to sort:
6
Enter 6 integers:
12
6
78
9
45
08
Sorted list of integers:
6
8
9
12
45
78

Bubble sort program for sorting in descending


Order
In order to sort in descending order we just need to change the logic array[j] >
array[j+1] to array[j] < array[j+1] in the above program. Complete code as
follows:

import java.util.Scanner;

class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

for (i = 0; i < num; i++)


array[i] = input.nextInt();

for (i = 0; i < ( num - 1 ); i++) {


for (j = 0; j < num - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}

System.out.println("Sorted list of integers:");

for (i = 0; i < num; i++)


System.out.println(array[i]);
}
}
Output:

Enter the number of integers to sort:


6
Enter 6 integers:
89
12
45
9
56
102
Sorted list of integers:
102
89
56
45
12
9

Java Program to find Sum of Natural


Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The positive integers 1, 2, 3, 4 etc. are known as natural numbers. Here we


will see three programs to calculate and display the sum of natural numbers.

 First Program calculates the sum using while loop


 Second Program calculates the sum using for loop
 Third Program takes the value of n(entered by user) and calculates the
sum of n natural numbers

To understand these programs you should be familiar with the following


concepts of Core Java Tutorial:

 Java For loop


 Java While loop

Example 1: Program to find the sum of natural


numbers using while loop
public class Demo {

public static void main(String[] args) {


int num = 10, count = 1, total = 0;

while(count <= num)


{
total = total + count;
count++;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}
}
Output:

Sum of first 10 natural numbers is: 55

Example 2: Program to calculate the sum of


natural numbers using for loop
public class Demo {

public static void main(String[] args) {

int num = 10, count, total = 0;

for(count = 1; count <= num; count++){


total = total + count;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}
}
Output:

Sum of first 10 natural numbers is: 55

Example 3: Program to find sum of first n


(entered by user) natural numbers
import java.util.Scanner;
public class Demo {

public static void main(String[] args) {

int num, count, total = 0;

System.out.println("Enter the value of n:");


//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}

System.out.println("Sum of first "+num+" natural numbers is: "+total);


}
}
Output:

Enter the value of n:


20
Sum of first 20 natural numbers is: 210

Java program to perform binary search –


Example
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Example Program to perform binary search on a list of integer


numbers

This program uses binary search algorithm to search an element in given list


of elements.

/* Program: Binary Search Example


* Written by: Chaitanya from beginnersbook.com
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import java.util.Scanner;
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();

//Creating array to store the all the numbers


array = new int[num];

System.out.println("Enter " + num + " integers");


//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;

while( first <= last )


{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}
}
Output 1:

Enter number of elements:


7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.
Output 2:

Enter number of elements:


5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.
Java Program to find largest of three
numbers using Ternary Operator
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

This program finds the largest of three numbers using ternary operator. Before
going through the program, lets understand what is a ternary Operator:
Ternary operator evaluates a boolean expression and assign the value
based on the result.

variable num = (expression) ? value if true : value if false


If the expression results true then the first value before the colon (:) is
assigned to the variable num else the second value is assigned to the num.

Example: Program to find the largest number


using ternary operator
In this Program, we have used the ternary operator twice to compare the three
numbers, however you can compare all three numbers in one statement
using ternary operator like this:

result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);


However if you are finding it difficult to understand then use it like I have
shown in the example below:

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int num1, num2, num3, result, temp;
/* Scanner is used for getting user input.
* The nextInt() method of scanner reads the
* integer entered by user.
*/
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();

/* In first step we are comparing only num1 and


* num2 and storing the largest number into the
* temp variable and then comparing the temp and
* num3 to get final result.
*/
temp = num1>num2 ? num1:num2;
result = num3>temp ? num3:temp;
System.out.println("Largest Number is:"+result);
}
}
Output:

Enter First Number:


89
Enter Second Number:
109
Enter Third Number:
8
Largest Number is:109

Java Program to read integer value from


the Standard Input
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this program we will see how to read an integer number entered by user.
Scanner class is in java.util package. It is used for capturing the input of the
primitive types like int, double etc. and strings.

Example: Program to read the number entered


by user
We have imported the package java.util.Scanner to use the Scanner. In order to
read the input provided by user, we first create the object of Scanner by
passing System.inas parameter. Then we are using nextInt() method of Scanner
class to read the integer. If you are new to Java and not familiar with the
basics of java program then read the following topics of Core Java:
→ Writing your First Java Program
→ How JVM works

import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

/* This reads the input provided by user


* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");

// This method reads the number provided using keyboard


int num = scan.nextInt();

// Closing Scanner after the use


scan.close();

// Displaying the number


System.out.println("The number entered by user: "+num);
}
}
Output:

Enter any number: 101


The number entered by user: 101

Java Program to Find Factorial using For


and While loop
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

We will write three java programs to find factorial of a number. 1) using for loop 2) using
while loop 3) finding factorial of a number entered by user. Before going through the
program, lets understand what is factorial: Factorial of a number n is denoted as n! and the
value of n! is: 1 * 2 * 3 * … (n-1) * n

The same logic we have implemented in our programs using loops. To understand these
programs you should have a basic knowledge of following topics of java tutorials:

 For loop in Java


 Java – while loop

Example: Finding factorial using for loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 2: Finding Factorial using while loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 3: Finding factorial of a number


entered by user
Program finds the factorial of input number using while loop.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Enter the number:
6
Factorial of 6 is: 720

Java Program to calculate area and


circumference of circle
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

In this tutorial we will see how to calculate area and circumference of


circle in Java. There are two ways to do this:

1) With user interaction: Program will prompt user to enter the radius of the
circle
2) Without user interaction: The radius value would be specified in the
program itself.

Program 1:

/**
* @author: BeginnersBook.com
* @description: Program to calculate area and circumference of circle
* with user interaction. User will be prompt to enter the radius and
* the result will be calculated based on the provided radius value.
*/
import java.util.Scanner;
class CircleDemo
{
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
System.out.print("Enter the radius: ");
/*We are storing the entered radius in double
* because a user can enter radius in decimals
*/
double radius = sc.nextDouble();
//Area = PI*radius*radius
double area = Math.PI * (radius * radius);
System.out.println("The area of circle is: " + area);
//Circumference = 2*PI*radius
double circumference= Math.PI * 2*radius;
System.out.println( "The circumference of the circle is:"+circumference) ;
}
}
Output:

Enter the radius: 1


The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586
Program 2:

/**
* @author: BeginnersBook.com
* @description: Program to calculate area and circumference of circle
* without user interaction. You need to specify the radius value in
* program itself.
*/
class CircleDemo2
{
public static void main(String args[])
{
int radius = 3;
double area = Math.PI * (radius * radius);
System.out.println("The area of circle is: " + area);
double circumference= Math.PI * 2*radius;
System.out.println( "The circumference of the circle is:"+circumference) ;
}
}
Output:

The area of circle is: 28.274333882308138


The circumference of the circle is:18.84955592153876

Java Program to find largest of three


Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

Here we will write two java programs to find the largest among three numbers.
1) Using if-else..if 2) Using nested If

To understand these programs you should have the knowledge of if..else-if


statement in Java. If you are new to java start from Core Java tutorial.

Example 1: Finding largest of three numbers


using if-else..if
public class JavaExample{

public static void main(String[] args) {

int num1 = 10, num2 = 20, num3 = 7;

if( num1 >= num2 && num1 >= num3)


System.out.println(num1+" is the largest Number");

else if (num2 >= num1 && num2 >= num3)


System.out.println(num2+" is the largest Number");

else
System.out.println(num3+" is the largest Number");
}
}
Output:

20 is the largest Number

Example 2: Program to find largest number


among three numbers using nested if
public class JavaExample{

public static void main(String[] args) {

int num1 = 10, num2 = 20, num3 = 7;

if(num1 >= num2) {

if(num1 >= num3)


/* This will only execute if conditions given in both
* the if blocks are true, which means num1 is greater
* than num2 and num3
*/
System.out.println(num1+" is the largest Number");
else
/* This will only execute if the condition in outer if
* is true and condition in inner if is false. which
* means num1 is grater than num2 but less than num3.
* which means num3 is the largest
*/
System.out.println(num3+" is the largest Number");
}
else {

if(num2 >= num3)


/* This will execute if the condition in outer if is false
* and inner if is true which means num3 is greater than num1
* but num2 is greater than num3. That means num2 is largest
*/
System.out.println(num2+" is the largest Number");
else
/* This will execute if the condition in outer if is false
* and inner if is false which means num3 is greater than num1
* and num2. That means num3 is largest
*/
System.out.println(num3+" is the largest Number");
}
}
}
Output:

20 is the largest Number


Java Program to check Vowel or
Consonant using Switch Case
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The alphabets A, E, I, O and U (smallcase and uppercase) are known as


Vowels and rest of the alphabets are known as consonants. Here we will write
a java program that checks whether the input character is vowel or Consonant
using Switch Case in Java.

If you are new to java, refer this Java Tutorial to start learning from basics

Example: Program to check Vowel or Consonant


using Switch Case
In this program we are not using break statement with cases intentionally, so
that if user enters any vowel, the program continues to execute all the
subsequent cases until Case 'U' is reached and thats where we are setting up
the value of a boolean variable to true. This way we can identify that the
alphabet entered by user is vowel or not.

import java.util.Scanner;
class JavaExample
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}
Output 1:

Enter a character :
A
A is a Vowel
Output 2:

Enter a character :
P
P is a Consonant
Output 3:

Enter a character :
9
Input is not an alphabet

Java Program to find Sum of Natural


Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The positive integers 1, 2, 3, 4 etc. are known as natural numbers. Here we


will see three programs to calculate and display the sum of natural numbers.

 First Program calculates the sum using while loop


 Second Program calculates the sum using for loop
 Third Program takes the value of n(entered by user) and calculates the
sum of n natural numbers

To understand these programs you should be familiar with the following


concepts of Core Java Tutorial:

 Java For loop


 Java While loop
Example 1: Program to find the sum of natural
numbers using while loop
public class Demo {

public static void main(String[] args) {

int num = 10, count = 1, total = 0;

while(count <= num)


{
total = total + count;
count++;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}
}
Output:

Sum of first 10 natural numbers is: 55

Example 2: Program to calculate the sum of


natural numbers using for loop
public class Demo {

public static void main(String[] args) {

int num = 10, count, total = 0;

for(count = 1; count <= num; count++){


total = total + count;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}
}
Output:

Sum of first 10 natural numbers is: 55

Example 3: Program to find sum of first n


(entered by user) natural numbers
import java.util.Scanner;
public class Demo {

public static void main(String[] args) {

int num, count, total = 0;


System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}

System.out.println("Sum of first "+num+" natural numbers is: "+total);


}
}
Output:

Enter the value of n:


20
Sum of first 20 natural numbers is: 210

Java Program to Find GCD of Two


Numbers
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The GCD (Greatest Common Divisor) of two numbers is the largest positive


integer number that divides both the numbers without leaving any remainder.
For example. GCD of 30 and 45 is 15. GCD also known as HCF (Highest
Common Factor). In this tutorial we will write couple of different Java
programs to find out the GCD of two numbers.

How to find out the GCD on paper?


To find out the GCD of two numbers we multiply the common factors as
shown in the following diagram:
Example 1: Java Program to find GCD of two
numbers using for loop
In this example, we are finding the GCD of two given numbers using for loop.

We are running a for loop from 1 to the smaller number and inside loop we are
dividing both the numbers with the loop counter “i” which ranges from 1 to the
smaller number value. If the value of i divides both numbers with no remainder
then we are assigning that value to the variable “gcd”. At the end of the loop,
the variable “gcd” will have the largest number that divides both the numbers
without remainder.

public class GCDExample1 {

public static void main(String[] args) {

//Lets take two numbers 55 and 121 and find their GCD
int num1 = 55, num2 = 121, gcd = 1;

/* loop is running from 1 to the smallest of both numbers


* In this example the loop will run from 1 to 55 because 55
* is the smaller number. All the numbers from 1 to 55 will be
* checked. A number that perfectly divides both numbers would
* be stored in variable "gcd". By doing this, at the end, the
* variable gcd will have the largest number that divides both
* numbers without remainder.
*/
for(int i = 1; i <= num1 && i <= num2; i++)
{
if(num1%i==0 && num2%i==0)
gcd = i;
}

System.out.printf("GCD of %d and %d is: %d", num1, num2, gcd);


}

}
Output:

GCD of 55 and 121 is: 11

Example 2: Finding GCD of two numbers using


while loop
Lets write the same program using while loop. Here we are taking a different
approach of finding gcd. In this program we are subtracting the smaller
number from the larger number until they both become same. At the end of
the loop the value of the numbers would be same and that value would be the
GCD of these numbers.
public class GCDExample2 {

public static void main(String[] args) {

int num1 = 55, num2 = 121;

while (num1 != num2) {


if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

System.out.printf("GCD of given numbers is: %d", num2);


}

}
Output:

GCD of given numbers is: 11

Example 3: Finding GCD of two input(Entered by


user) numbers
In this example, we are using Scanner to get the input from user. The user
would enter the value of both the numbers and program would find the GCD of
these entered numbers.

import java.util.Scanner;
public class GCDExample3 {

public static void main(String[] args) {

int num1, num2;

//Reading the input numbers


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = (int)scanner.nextInt();

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


num2 = (int)scanner.nextInt();

//closing the scanner to avoid memory leaks


scanner.close();
while (num1 != num2) {
if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

//displaying the result


System.out.printf("GCD of given numbers is: %d", num2);
}
}
Output:

Enter first number:30


Enter second number:250
GCD of given numbers is: 10

Java Program to Display Fibonacci Series


using loops
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

The Fibonacci sequence is a series of numbers where a number is the sum of


previous two numbers. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3,
5, 8, 13, 21, and so on. Here we will write three programs to print fibonacci
series 1) using for loop 2) using while loop 3) based on the number entered by
user

To understand these programs, you should have the knowledge of for


loop and while loop.

If you are new to java, refer this java programming tutorial to start learning
from basics.

Example 1: Program to print fibonacci series


using for loop
public class JavaExample {

public static void main(String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+" numbers:");

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


{
System.out.print(num1+" ");

/* On each iteration, we are assigning second number


* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}
Output:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

Example 2: Displaying Fibonacci Sequence using


while loop
public class JavaExample {

public static void main(String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+" numbers:");

int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}
}
Output:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

Example 3: Program to display the fibonacci


series based on the user input
This program display the sequence based on the number entered by user. For
example – if user enters 10 then this program displays the series of 10
numbers.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int count, num1 = 0, num2 = 1;


System.out.println("How may numbers you want in the sequence:");
Scanner scanner = new Scanner(System.in);
count = scanner.nextInt();
scanner.close();
System.out.print("Fibonacci Series of "+count+" numbers:");

int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}
}
Output:

How may numbers you want in the sequence:


6
Fibonacci Series of 6 numbers:0 1 1 2 3 5

Java Program to Find Factorial using For


and While loop
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES

We will write three java programs to find factorial of a number. 1) using for
loop 2) using while loop 3) finding factorial of a number entered by user.
Before going through the program, lets understand what is factorial: Factorial
of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n

The same logic we have implemented in our programs using loops. To


understand these programs you should have a basic knowledge of following
topics of java tutorials:

 For loop in Java


 Java – while loop

Example: Finding factorial using for loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 2: Finding Factorial using while loop


public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:

Factorial of 5 is: 120

Example 3: Finding factorial of a number


entered by user
Program finds the factorial of input number using while loop.

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Enter the number:
6
Factorial of 6 is: 720

You might also like