Java Programming Examples

Java Programming Examples

19 August 2023 0 By Anshul Pal

In this article we are going to see the Java Programming Examples. Before starting it let we have a basic understanding about Java Programming language. Java is a widely used, versatile programming language known for its portability, reliability, and readability. Created by Sun Microsystems (now owned by Oracle), Java enables developers to build platform-independent applications due to its “write once, run anywhere” principle. With a strong emphasis on object-oriented programming, Java supports reusable and modular code, making software development efficient. Its rich standard library provides diverse tools for tasks ranging from user interface creation to networking. Java’s popularity in web, mobile, and enterprise applications, along with its active community and continuous updates, solidifies its position as a cornerstone of modern programming. Now, Let’s start the Java Programming Examples tutorial : –

Table of Contents

Java Program to Add two integers

This Java code defines a simple program that takes two integer inputs from the user, adds them together, and then displays the sum.

import java.util.*;
public class Add {
public static void main(String[] args) {
int input_1, input_2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number");
input_1 = sc.nextInt();
System.out.println("Enter the second number");
input_2 = sc.nextInt();
sum = input_1 + input_2;
System.out.println("The sum of two numbers: " + sum);
}
}

Output

Enter the first number
66665
Enter the second number
6565
The sum of two numbers: 73230

Explanation

  1. import java.util.*;: This line imports the java.util package, which contains the Scanner class. The Scanner class is used to read input from the user.
  2. public class Add {: This line defines a public class named Add. In Java, a program typically consists of classes, and the class containing the main method is the entry point of the program.
  3. public static void main(String[] args) {: This line declares the main method, which serves as the starting point of the program’s execution. It takes an array of strings (args) as its parameter, although in this code, the parameter is not used.
  4. int input_1, input_2, sum;: These are variable declarations. Three variables are declared: input_1, input_2, and sum. These will be used to store the two input numbers and their sum.
  5. Scanner sc = new Scanner(System.in);: This line creates an instance of the Scanner class named sc. It is used to read input from the standard input (keyboard).
  6. System.out.println("Enter the first number");: This line prints a message to the console, prompting the user to enter the first number.
  7. input_1 = sc.nextInt();: This line uses the nextInt() method of the Scanner class to read an integer input from the user and assigns it to the variable input_1.
  8. System.out.println("Enter the second number");: Similar to step 6, this line prompts the user to enter the second number.
  9. input_2 = sc.nextInt();: Again, similar to step 7, this line reads an integer input from the user and assigns it to the variable input_2.
  10. sum = input_1 + input_2;: This line calculates the sum of the two input numbers and assigns the result to the variable sum.
  11. System.out.println("The sum of two numbers: " + sum);: Finally, this line prints the sum of the two numbers to the console along with a descriptive message.
  12. }: This closing curly brace marks the end of the main method.

Java Program to check whether a number is prime or not

This java code helps to check that the given number is prime or not.

import java.util.*;
public class Prime_Number {
static void myFunction() {
int a;
String value;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
a = sc.nextInt();
value = "prime";
if (a <= 1) {
System.out.println("This is not a prime number");
} else {
for (int i = 2; i < a; i++) {
if (a % i == 0) {
value = "notprime";
break;
}
}
if (value.equals("notprime")) {
System.out.println("This is not a prime number");
} else {
System.out.println("This is a prime number");
}
}
}
public static void main(String[] args) {
myFunction();
}
}

Output

Enter a number: 5
This is a prime number

Explanation

  1. The code starts by importing the java.util.* package, which includes the Scanner class for user input handling.
  2. The Prime_Number class is defined. Inside the class, there’s a static method myFunction() that performs the prime number check.
  3. The method begins by declaring two variables: an integer a and a string value.
  4. An instance of Scanner is created to read input from the user.
  5. The program prompts the user to enter a number and reads the input into the variable a.
  6. Initially, the value is set to “prime”, assuming that the input number is prime.
  7. The code checks whether the input number a is less than or equal to 1. If it is, the program immediately prints “This is not a prime number”, as prime numbers are defined to be greater than 1.
  8. If the input number is greater than 1, the program enters a loop that iterates from 2 to a – 1.
  9. Inside the loop, the program checks whether the input number a is divisible by the current value of i. If it is, the value of value is changed to “notprime”, indicating that the number is not prime, and the loop is broken using the break statement.
  10. After the loop finishes, the program checks the value of value. If it’s “notprime”, the program prints “This is not a prime number”. Otherwise, it prints “This is a prime number”.
  11. The main method is defined, and it is simply called the myFunction() method to start the prime number checking process.

JAVA Program To Find ASCII value of a character

public class Ascii {
public static void main(String[] args) {
char characters = 'a';
int ascii = characters;
System.out.println("The ASCII value of " + characters + " is: " + ascii);
} }

Output

The ASCII value of a is: 97

Explanation

  1. public class Ascii {: This line defines a public class named Ascii.
  2. public static void main(String[] args) {: This line declares the main method, which is the entry point of the program’s execution. It takes an array of strings (args) as its parameter, although in this code, the parameter is not utilized.
  3. char characters = 'a';: This line declares a variable named characters of type char and assigns it the value 'a'. This character is used to demonstrate obtaining the ASCII value.
  4. int ascii = characters;: Here, the ASCII value of the character stored in the characters variable is assigned to an integer variable named ascii. In Java, characters can be directly assigned to integer variables, and their Unicode values (which include ASCII values) will be used.
  5. System.out.println("The ASCII value of " + characters + " is: " + ascii);: This line prints a message to the console that displays the original character (characters) and its corresponding ASCII value (ascii).
  6. }: This closing curly brace marks the end of the main method.

Java Program To Swap two numbers

This Java program demonstrates how to swap the values of two variables using a temporary variable. Let’s break down the code step by step:

import java.util.*;
public class Swap{
public static void main(String[] args){
String temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of x");
String a = sc.nextLine();
System.out.println("Enter the value of y");
String b = sc.nextLine();
temp = a;
a = b;
b = temp;
System.out.println("The value of x is " + a);
System.out.println("The value of y is " + b);
}
}

Output

Enter the value of x
Java
Enter the value of y
Programs
The value of x is Programs
The value of y is Java

Explanation

  1. import java.util.*;: This line imports the java.util package, which contains the Scanner class that will be used to read user input.
  2. public class Swap {: This line defines a Java class named Swap.
  3. public static void main(String[] args) {: This line defines the main method, the entry point for the program.
  4. String temp;: This line declares a variable named temp of type String. This variable will be used to temporarily hold the value of one of the variables during the swapping process.
  5. Scanner sc = new Scanner(System.in);: This line creates a Scanner object named sc to read input from the console.
  6. System.out.println("Enter the value of x");: This line displays a prompt asking the user to enter the value of variable ‘x’.
  7. String a = sc.nextLine();: This line uses the Scanner to read a line of text input from the user and store it in the variable a.
  8. System.out.println("Enter the value of y");: This line displays a prompt asking the user to enter the value of variable ‘y’.
  9. String b = sc.nextLine();: This line reads another line of text input from the user and stores it in the variable b.
  10. temp = a; a = b; b = temp;: These lines implement the swapping of values. The value of a is temporarily stored in temp, then the value of b is assigned to a, and finally, the original value of a (stored in temp) is assigned to b.
  11. System.out.println("The value of x is " + a);: This line prints the value of variable a after swapping.
  12. System.out.println("The value of y is " + b);: This line prints the value of variable b after swapping.

Java Program To Check Whether a number is Even or Odd

This Java program determines whether a given number is even or odd. Let’s go through the code step by step:

import java.util.*;
public class EvenOrOdd{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int input = sc.nextInt();
sc.close();
if( input % 2 == 0){
System.out.println(input + " is even number");
}
else{
System.out.println(input + " is odd number");
} }
}

Output

Enter the number
8
8 is even number

Explanation

  1. import java.util.*;: This line imports the java.util package, which includes the Scanner class for reading user input.
  2. public class EvenOrOdd {: This line defines a Java class named EvenOrOdd.
  3. public static void main(String[] args) {: This line defines the main method, the entry point for the program.
  4. Scanner sc = new Scanner(System.in);: This line creates a Scanner object named sc to read input from the console.
  5. System.out.println("Enter the number");: This line displays a prompt asking the user to enter a number.
  6. int input = sc.nextInt();: This line reads an integer input from the user using the nextInt method of the Scanner object and stores it in the input variable.
  7. sc.close();: This line closes the Scanner object after reading the input to free up system resources.
  8. if (input % 2 == 0) {: This line starts an if statement to check whether the input number is even. The condition input % 2 == 0 checks if the remainder of dividing input by 2 is equal to 0.
  9. System.out.println(input + " is even number");: If the condition in the if statement is true (meaning the number is even), this line prints a message indicating that the input number is even.
  10. } else {: This line starts the else block, which is executed if the condition in the if statement is false.
  11. System.out.println(input + " is odd number");: If the number is not even (i.e., the remainder is not 0), this line prints a message indicating that the input number is odd.

Java Program To Find Roots of a Quadratic Equation

This Java program solves a quadratic equation of the form ax² + bx + c = 0 and calculates its roots using the quadratic formula. The quadratic formula is used to find the solutions (roots) of a quadratic equation, and it involves the coefficients a, b, and c. The program distinguishes between different cases based on the determinant of the quadratic equation to determine whether the roots are real or complex.

public class QuadraticEquation {
public static void main(String[] args) {
double a = 2.3, b = 4, c = 5.6; 
double root1, root2; 
double determinant = b * b - 4 * a * c; 
if (determinant > 0) {
// Case: Two distinct real roots
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
} else if (determinant == 0) {
// Case: One real root (repeated)
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
} else {
// Case: Complex roots
double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
} }

Explanation

  1. Coefficients (a, b, and c) are given for the quadratic equation ax² + bx + c = 0.
  2. determinant is calculated using the formula b² - 4ac, which is used to determine the nature of the roots.
  3. The if statement checks the value of the determinant to determine the type of roots:a. If the determinant is greater than 0, it means there are two distinct real roots. The roots are calculated using the quadratic formula and printed.b. If the determinant is equal to 0, it means there’s a single real root that is repeated. The root is calculated and printed.

    c. If the determinant is less than 0, it means there are complex roots. The real and imaginary parts of the roots are calculated and printed.

  4. System.out.format is used to display the roots with formatting. %f is used to format the floating-point numbers (roots), and %i is used for the imaginary part.
  5. The code uses the Math.sqrt() method to calculate the square root and handles both real and imaginary parts of the roots.

Java Program to Check the Leap Year

This Java program determines whether a given year is a leap year or not. A leap year is a year that is evenly divisible by 4. However, to be considered a leap year, a year that is divisible by 100 must also be divisible by 400. The code uses nested if statements to check these conditions. Let’s break down the code step by step.

import java.util.*;
public class Leap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year");
int year = sc.nextInt();
sc.close();
boolean leap = false;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) .
leap = true; 
else
leap = false;
} else
leap = true;
} else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year."); 
} }

Output

Enter the year
2023
2023 is not a leap year.

Explanation

  1. The program starts by importing the java.util.* package, which includes the Scanner class for reading user input.
  2. The main method is defined as the entry point for the program.
  3. A Scanner object sc is created to read input from the console.
  4. The program prompts the user to enter a year and reads the input into the year variable.
  5. The Scanner object is closed to release resources.
  6. A boolean variable leap is initialized to false, which will be used to store whether the year is a leap year or not.
  7. Nested if statements are used to check the conditions for leap years based on the rules described earlier. The program checks if the year is divisible by 4, then further checks if it’s divisible by 100, and finally if it’s divisible by 400.
  8. Depending on the conditions met, the value of the leap variable is updated.
  9. The program uses the if-else construct to print whether the year is a leap year or not based on the value of the leap variable.

Java Program to Find Factorial of a number

This Java program calculates the factorial of a given number using the BigInteger class to handle large integer values that might exceed the range of standard integer types.

import java.math.BigInteger;
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); 
System.out.println("Enter the number");
int num = sc.nextInt(); 
sc.close(); 
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= num; ++i) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf("Factorial of %d = %d", num, factorial);
} }

Output

Enter the number
6
Factorial of 6 = 720

Explanation

  1. The program starts by importing the java.math.BigInteger package for handling large integer values and the java.util.* package for reading user input.
  2. The main method is defined as the entry point for the program.
  3. A Scanner object sc is created to read input from the console.
  4. The program prompts the user to enter a number and reads the input into the num variable.
  5. The Scanner object is closed to release resources.
  6. A BigInteger variable factorial is initialized to BigInteger.ONE, which is the initial value for calculating the factorial.
  7. A for loop is used to iterate from 1 to num (inclusive), calculating the factorial of the number.
  8. Inside the loop, the factorial variable is updated by multiplying it with the current value of i using the multiply method of BigInteger.
  9. The System.out.printf statement is used to print the calculated factorial of the input number.

Java Program to Display Fibonacci Series

This Java program generates and prints the Fibonacci series up to a specified number of terms. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones.

public class Fibonacci {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series till " + n + " terms:");
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + ", ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}   }   }

Output

Fibonacci Series till 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Explanation

  1. The program defines a class named Fibonacci.
  2. The main method is defined as the entry point for the program.
  3. int n = 10; specifies that the program should generate the Fibonacci series up to 10 terms.
  4. int firstTerm = 0, secondTerm = 1; initializes the first two terms of the Fibonacci series.
  5. System.out.println("Fibonacci Series till " + n + " terms:"); prints a message indicating the number of terms to be generated.
  6. The for loop runs from i = 1 to i <= n to generate and print the Fibonacci series terms.
  7. Inside the loop, System.out.print(firstTerm + ", "); prints the current firstTerm in the sequence.
  8. int nextTerm = firstTerm + secondTerm; calculates the next term in the Fibonacci series.
  9. firstTerm = secondTerm; updates firstTerm to hold the value of the previous secondTerm.
  10. secondTerm = nextTerm; updates secondTerm to hold the value of the calculated nextTerm.
  11. The loop continues for the specified number of terms, generating and printing each term in the series.

Java Program to Find LCM of two number

This Java program calculates the Least Common Multiple (LCM) of two numbers, n1 and n2, using a while loop. The LCM of two numbers is the smallest positive integer that is divisible by both of the given numbers.

public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120, lcm;
lcm = (n1 > n2) ? n1 : n2;
while (true) {
if (lcm % n1 == 0 && lcm % n2 == 0) {
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}  }       }

Explanation

  1. The program defines a class named Main.
  2. The main method is defined as the entry point for the program.
  3. int n1 = 72, n2 = 120, lcm; initializes the two numbers, n1 and n2, and the variable lcm to store the LCM.
  4. (n1 > n2) ? n1 : n2; uses the conditional (ternary) operator to determine the maximum value between n1 and n2 and assigns it to the variable lcm. The variable lcm is initialized with the maximum value because the LCM cannot be smaller than either of the input numbers.
  5. The program enters a while (true) loop, which runs indefinitely until the LCM is found.
  6. Inside the loop, the condition lcm % n1 == 0 && lcm % n2 == 0 checks if the current value of lcm is divisible by both n1 and n2 without leaving a remainder. If this condition is true, it means the current value of lcm is the LCM of the two numbers.
  7. If the condition is met, the program prints the LCM and the two input numbers using System.out.printf, and then it exits the loop using the break statement.
  8. If the condition is not met, the program increments lcm by 1 using ++lcm. This is done to check the next potential LCM value in the next iteration of the loop.

Java Program to Check Armstrong Number

This Java program checks whether a given number is an Armstrong number or not. An Armstrong number (also known as a narcissistic number or pluperfect digital invariant) is a number that is equal to the sum of its own digits raised to the power of the number of digits.

import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = sc.nextInt();
sc.close();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}  }
public static boolean isArmstrong(int num) {
int originalNumber = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
return sum == originalNumber;
}  }

Output

Enter a number: 
153
153 is an Armstrong number.

Explanation

  1. The program imports the java.util.Scanner package to read user input.
  2. The program defines a class named Armstrong.
  3. The main method is defined as the entry point for the program.
  4. A Scanner object sc is created to read input from the console.
  5. The program prompts the user to enter a number and reads the input into the number variable.
  6. The Scanner object is closed to release resources.
  7. The program calls the isArmstrong method to check if the entered number is an Armstrong number.
  8. Depending on the return value of isArmstrong(number), the program prints whether the number is an Armstrong number or not.
  9. The isArmstrong method takes an integer num as an argument and calculates whether it’s an Armstrong number or not.
  10. The method uses a while loop to extract each digit of the number and adds the cube of each digit to the sum variable.
  11. After the loop, it checks if the sum of cubes is equal to the originalNumber, and if so, it returns true, indicating that the number is an Armstrong number.
  12. If the sum of cubes is not equal to the original number, the method returns false.

Suggested Reads!

Featured image source