
Java Programming Examples
19 August 2023In 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
- Java Program to check whether a number is prime or not
- JAVA Program To Find ASCII value of a character
- JAVA Program To Find ASCII value of a character
- Java Program To Check Whether a number is Even or Odd
- Java Program To Find Roots of a Quadratic Equation
- Java Program to Check the Leap Year
- Java Program to Find Factorial of a number
- Java Program to Display Fibonacci Series
- Java Program to Find LCM of two number
- Java Program to Check Armstrong Number
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
import java.util.*;
: This line imports thejava.util
package, which contains theScanner
class. TheScanner
class is used to read input from the user.public class Add {
: This line defines a public class namedAdd
. In Java, a program typically consists of classes, and the class containing themain
method is the entry point of the program.public static void main(String[] args) {
: This line declares themain
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.int input_1, input_2, sum;
: These are variable declarations. Three variables are declared:input_1
,input_2
, andsum
. These will be used to store the two input numbers and their sum.Scanner sc = new Scanner(System.in);
: This line creates an instance of theScanner
class namedsc
. It is used to read input from the standard input (keyboard).System.out.println("Enter the first number");
: This line prints a message to the console, prompting the user to enter the first number.input_1 = sc.nextInt();
: This line uses thenextInt()
method of theScanner
class to read an integer input from the user and assigns it to the variableinput_1
.System.out.println("Enter the second number");
: Similar to step 6, this line prompts the user to enter the second number.input_2 = sc.nextInt();
: Again, similar to step 7, this line reads an integer input from the user and assigns it to the variableinput_2
.sum = input_1 + input_2;
: This line calculates the sum of the two input numbers and assigns the result to the variablesum
.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.}
: This closing curly brace marks the end of themain
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
- The code starts by importing the java.util.* package, which includes the Scanner class for user input handling.
- The Prime_Number class is defined. Inside the class, there’s a static method myFunction() that performs the prime number check.
- The method begins by declaring two variables: an integer a and a string value.
- An instance of Scanner is created to read input from the user.
- The program prompts the user to enter a number and reads the input into the variable a.
- Initially, the value is set to “prime”, assuming that the input number is prime.
- 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.
- If the input number is greater than 1, the program enters a loop that iterates from 2 to a – 1.
- 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.
- 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”.
- 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
public class Ascii {
: This line defines a public class namedAscii
.public static void main(String[] args) {
: This line declares themain
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.char characters = 'a';
: This line declares a variable namedcharacters
of typechar
and assigns it the value'a'
. This character is used to demonstrate obtaining the ASCII value.int ascii = characters;
: Here, the ASCII value of the character stored in thecharacters
variable is assigned to an integer variable namedascii
. In Java, characters can be directly assigned to integer variables, and their Unicode values (which include ASCII values) will be used.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
).}
: This closing curly brace marks the end of themain
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
import java.util.*;
: This line imports thejava.util
package, which contains theScanner
class that will be used to read user input.public class Swap {
: This line defines a Java class namedSwap
.public static void main(String[] args) {
: This line defines themain
method, the entry point for the program.String temp;
: This line declares a variable namedtemp
of typeString
. This variable will be used to temporarily hold the value of one of the variables during the swapping process.Scanner sc = new Scanner(System.in);
: This line creates aScanner
object namedsc
to read input from the console.System.out.println("Enter the value of x");
: This line displays a prompt asking the user to enter the value of variable ‘x’.String a = sc.nextLine();
: This line uses theScanner
to read a line of text input from the user and store it in the variablea
.System.out.println("Enter the value of y");
: This line displays a prompt asking the user to enter the value of variable ‘y’.String b = sc.nextLine();
: This line reads another line of text input from the user and stores it in the variableb
.temp = a; a = b; b = temp;
: These lines implement the swapping of values. The value ofa
is temporarily stored intemp
, then the value ofb
is assigned toa
, and finally, the original value ofa
(stored intemp
) is assigned tob
.System.out.println("The value of x is " + a);
: This line prints the value of variablea
after swapping.System.out.println("The value of y is " + b);
: This line prints the value of variableb
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
import java.util.*;
: This line imports thejava.util
package, which includes theScanner
class for reading user input.public class EvenOrOdd {
: This line defines a Java class namedEvenOrOdd
.public static void main(String[] args) {
: This line defines themain
method, the entry point for the program.Scanner sc = new Scanner(System.in);
: This line creates aScanner
object namedsc
to read input from the console.System.out.println("Enter the number");
: This line displays a prompt asking the user to enter a number.int input = sc.nextInt();
: This line reads an integer input from the user using thenextInt
method of theScanner
object and stores it in theinput
variable.sc.close();
: This line closes theScanner
object after reading the input to free up system resources.if (input % 2 == 0) {
: This line starts anif
statement to check whether the input number is even. The conditioninput % 2 == 0
checks if the remainder of dividinginput
by 2 is equal to 0.System.out.println(input + " is even number");
: If the condition in theif
statement is true (meaning the number is even), this line prints a message indicating that the input number is even.} else {
: This line starts theelse
block, which is executed if the condition in theif
statement is false.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
- Coefficients (
a
,b
, andc
) are given for the quadratic equation ax² + bx + c = 0. determinant
is calculated using the formulab² - 4ac
, which is used to determine the nature of the roots.- 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.
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.- 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
- The program starts by importing the
java.util.*
package, which includes theScanner
class for reading user input. - The
main
method is defined as the entry point for the program. - A
Scanner
objectsc
is created to read input from the console. - The program prompts the user to enter a year and reads the input into the
year
variable. - The
Scanner
object is closed to release resources. - A boolean variable
leap
is initialized tofalse
, which will be used to store whether the year is a leap year or not. - 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. - Depending on the conditions met, the value of the
leap
variable is updated. - The program uses the
if-else
construct to print whether the year is a leap year or not based on the value of theleap
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
- The program starts by importing the
java.math.BigInteger
package for handling large integer values and thejava.util.*
package for reading user input. - The
main
method is defined as the entry point for the program. - A
Scanner
objectsc
is created to read input from the console. - The program prompts the user to enter a number and reads the input into the
num
variable. - The
Scanner
object is closed to release resources. - A
BigInteger
variablefactorial
is initialized toBigInteger.ONE
, which is the initial value for calculating the factorial. - A
for
loop is used to iterate from 1 tonum
(inclusive), calculating the factorial of the number. - Inside the loop, the
factorial
variable is updated by multiplying it with the current value ofi
using themultiply
method ofBigInteger
. - 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
- The program defines a class named
Fibonacci
. - The
main
method is defined as the entry point for the program. int n = 10;
specifies that the program should generate the Fibonacci series up to 10 terms.int firstTerm = 0, secondTerm = 1;
initializes the first two terms of the Fibonacci series.System.out.println("Fibonacci Series till " + n + " terms:");
prints a message indicating the number of terms to be generated.- The
for
loop runs fromi = 1
toi <= n
to generate and print the Fibonacci series terms. - Inside the loop,
System.out.print(firstTerm + ", ");
prints the currentfirstTerm
in the sequence. int nextTerm = firstTerm + secondTerm;
calculates the next term in the Fibonacci series.firstTerm = secondTerm;
updatesfirstTerm
to hold the value of the previoussecondTerm
.secondTerm = nextTerm;
updatessecondTerm
to hold the value of the calculatednextTerm
.- 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
- The program defines a class named
Main
. - The
main
method is defined as the entry point for the program. int n1 = 72, n2 = 120, lcm;
initializes the two numbers,n1
andn2
, and the variablelcm
to store the LCM.(n1 > n2) ? n1 : n2;
uses the conditional (ternary) operator to determine the maximum value betweenn1
andn2
and assigns it to the variablelcm
. The variablelcm
is initialized with the maximum value because the LCM cannot be smaller than either of the input numbers.- The program enters a
while (true)
loop, which runs indefinitely until the LCM is found. - Inside the loop, the condition
lcm % n1 == 0 && lcm % n2 == 0
checks if the current value oflcm
is divisible by bothn1
andn2
without leaving a remainder. If this condition is true, it means the current value oflcm
is the LCM of the two numbers. - 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 thebreak
statement. - 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
- The program imports the
java.util.Scanner
package to read user input. - The program defines a class named
Armstrong
. - The
main
method is defined as the entry point for the program. - A
Scanner
objectsc
is created to read input from the console. - The program prompts the user to enter a number and reads the input into the
number
variable. - The
Scanner
object is closed to release resources. - The program calls the
isArmstrong
method to check if the entered number is an Armstrong number. - Depending on the return value of
isArmstrong(number)
, the program prints whether the number is an Armstrong number or not. - The
isArmstrong
method takes an integernum
as an argument and calculates whether it’s an Armstrong number or not. - The method uses a
while
loop to extract each digit of the number and adds the cube of each digit to thesum
variable. - After the loop, it checks if the
sum
of cubes is equal to theoriginalNumber
, and if so, it returnstrue
, indicating that the number is an Armstrong number. - If the sum of cubes is not equal to the original number, the method returns
false
.
Suggested Reads!
Hey there, I’m Anshul Pal, a tech blogger and Computer Science graduate. I’m passionate about exploring tech-related topics and sharing the knowledge I’ve acquired. With two years of industry expertise in blogging and content writing, I’m also the co-founder of HVM Smart Solution. Thanks for reading my blog – Happy Learning!