Java Programs - Java Programming Examples with Output
Java Programs - Java Programming Examples with Output
what is java program
The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows applets written in the Java programming language to run inside various browsers. The Java Plug-in software is not a standalone program and cannot be installed separately.
Features of Java
- Simple
- Object-Oriented
- Portable
- Platform independent
- Secured
- Robust
- Architecture neutral
- Interpreted
- High Performance
- Multithreaded
- Distributed
- Dynamic
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
Java Program to check Even or Odd number
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 display first n or first 100 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 the prime numbers from 1 to 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
Example: Program to check whether input number is prime or not
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
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 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
Example 1: Program to check whether the given number is positive or negative
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
Example 1: Program to read two integer and print product of them
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
Program: Check whether String is palindrome using recursion
package beginnersbook.com;
import java.util.Scanner;
class PalindromeCheck
{
//My Method to check
public static boolean isPal(String s)
{ // if length is 0 or 1 then String is palindrome
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails
* Function calling itself: Recursion
*/
return isPal(s.substring(1, s.length()-1));
/* If program control reaches to this statement it means
* the String is not palindrome hence return false.
*/
return false;
}
public static void main(String[]args)
{
//For capturing user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the String for check:");
String string = scanner.nextLine();
/* If function returns true then the string is
* palindrome else not
*/
if(isPal(string))
System.out.println(string + " is a palindrome");
else
System.out.println(string + " is not a palindrome");
}
}
Output:
Enter the String for check:
qqaabb
qqaabb is not a palindrome
Output 2:
Enter the String for check:
cocoococ
cocoococ is a palindrome
Java program to calculate area of Square
Program 1:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate Area of square.Program
* will prompt user for entering the side of the square.
*/
import java.util.Scanner;
class SquareAreaDemo {
public static void main (String[] args)
{
System.out.println("Enter Side of Square:");
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
double side = scanner.nextDouble();
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
Output:
Enter Side of Square:
2.5
Area of Square is: 6.25
Program 2:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate Area of square.
* No user interaction: Side of square is hard-coded in the
* program itself.
*/
class SquareAreaDemo2 {
public static void main (String[] args)
{
//Value specified in the program itself
double side = 4.5;
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
Output:
Area of Square is: 20.25
How To Convert Char To String and a String to char in Java
Program to convert char to String
We have following two ways for char to String conversion.
Method 1: Using toString() method
Method 2: Usng valueOf() method
class CharToStringDemo
{
public static void main(String args[])
{
// Method 1: Using toString() method
char ch = 'a';
String str = Character.toString(ch);
System.out.println("String is: "+str);
// Method 2: Using valueOf() method
String str2 = String.valueOf(ch);
System.out.println("String is: "+str2);
}
}
Output:
String is: a
String is: a
Converting String to Char
We can convert a String to char using charAt() method of String class.
class StringToCharDemo
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch);
}
}
}
Output:
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o
Java Program to Check Armstrong Number
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 reverse the Array
Example: Program to reverse the array
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{
int counter, i=0, j=0, temp;
int number[] = new int[100];
Scanner scanner = new Scanner(System.in);
System.out.print("How many elements you want to enter: ");
counter = scanner.nextInt();
/* This loop stores all the elements that we enter in an
* the array number. First element is at number[0], second at
* number[1] and so on
*/
for(i=0; i<counter; i++)
{
System.out.print("Enter Array Element"+(i+1)+": ");
number[i] = scanner.nextInt();
}
/* Here we are writing the logic to swap first element with
* last element, second last element with second element and
* so on. On the first iteration of while loop i is the index
* of first element and j is the index of last. On the second
* iteration i is the index of second and j is the index of
* second last.
*/
j = i - 1;
i = 0;
scanner.close();
while(i<j)
{
temp = number[i];
number[i] = number[j];
number[j] = temp;
i++;
j--;
}
System.out.print("Reversed array: ");
for(i=0; i<counter; i++)
{
System.out.print(number[i]+ " ");
}
}
}
Output:
How many elements you want to enter: 5
Enter Array Element1: 11
Enter Array Element2: 22
Enter Array Element3: 33
Enter Array Element4: 44
Enter Array Element5: 55
Reversed array: 55 44 33 22 11
Java Program to find area of Geometric figures using method Overloading
Example: Program to find area of Square, Rectangle and Circle using Method Overloading
class JavaExample
{
void calculateArea(float x)
{
System.out.println("Area of the square: "+x*x+" sq units");
}
void calculateArea(float x, float y)
{
System.out.println("Area of the rectangle: "+x*y+" sq units");
}
void calculateArea(double r)
{
double area = 3.14*r*r;
System.out.println("Area of the circle: "+area+" sq units");
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
/* This statement will call the first area() method
* because we are passing only one argument with
* the "f" suffix. f is used to denote the float numbers
*
*/
obj.calculateArea(6.1f);
/* This will call the second method because we are passing
* two arguments and only second method has two arguments
*/
obj.calculateArea(10,22);
/* This will call the second method because we have not suffixed
* the value with "f" when we do not suffix a float value with f
* then it is considered as type double.
*/
obj.calculateArea(6.1);
}
}
Output:
Area of the square: 37.21 sq units
Area of the rectangle: 220.0 sq units
Area of the circle: 116.8394 sq units
Online Video Also Free Watch
More Programming Here
https://beginnersbook.com/2017/09/java-examples/