0% found this document useful (0 votes)
6 views53 pages

Java Exercises

The document provides a series of Java programming exercises focused on basic operations such as printing greetings, summing numbers, division, and performing arithmetic operations. Each exercise includes sample code, explanations, and expected outputs, along with suggestions for further practice. It emphasizes user input handling and the use of the Scanner class for interactive programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views53 pages

Java Exercises

The document provides a series of Java programming exercises focused on basic operations such as printing greetings, summing numbers, division, and performing arithmetic operations. Each exercise includes sample code, explanations, and expected outputs, along with suggestions for further practice. It emphasizes user input handling and the use of the Scanner class for interactive programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Java: Print hello and your name on a

separate lines
Last update on May 12 2025 13:20:08 (UTC/GMT +8 hours)

Hello and Name Printer


Write a Java program to print 'Hello' on screen and your name on a separate line.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise1 {
public static void main(String[] args) {
// Print a greeting message to the console
System.out.println("Hello\nAlexandra Abramov!");
}
}

Explanation:
In the exercise above
 The "main()" method is the program entry point.
 It uses System.out.println to print the message.
 The message consists of two lines: "Hello" and "Alexandra Abramov!" separated by a newline character
(\n).
When we run this Java program, we'll see this message displayed in the console or terminal.
Sample Output:
Hello
Alexandra Abramov!
Flowchart:

Sample solution using input from the user:


Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner input = new Scanner(System.in);
// Prompt the user to input their first name
System.out.print("Input your first name: ");
String fname = input.next();
// Prompt the user to input their last name
System.out.print("Input your last name: ");
String lname = input.next();
// Output a greeting message with the user's full name
System.out.println();
System.out.println("Hello \n" + fname + " " + lname);
}
}
Explanation:
In the exercise above -
 import java.util. Scanner;: This code imports the "Scanner" class, which allows the program to read
input from the user.
 public class Main {: This code declares a class named "Main," and it contains the main method, which is
the entry point of the program.
 public static void main(String[] args) {: This line defines the main method. Here's what each part means:
o public: This keyword indicates that the method can be accessed from outside the class.
o static: This keyword means that the method belongs to the class itself, not to a specific instance
of the class.
o void: This specifies that the main method doesn't return any value.
o main: This is the name of the method.
o (String[] args): This is the method's parameter list, which accepts an array of strings. In this case,
it's not used.
 Scanner input = new Scanner(System.in);: This code creates a Scanner object named input to read input
from the console (user's keyboard).
 System.out.print("Input your first name: ");: This code prints a message to the console, asking the user
to input their first name.
 String fname = input.next();: This code reads the user's input for their first name and stores it in the
variable fname.
 System.out.print("Input your last name: ");: This code prints a message to the console, asking the user to
input their last name.
 String lname = input.next();: This code reads the user's input for their last name and stores it in the
variable lname.
 System.out.println();: This code prints a blank line to separate the output.
 System.out.println("Hello \n" + fname + " " + lname);: This code prints a greeting message to the
console. It combines the user's full name with the text "Hello" and a newline character (\n) to create a
formatted greeting message.
Sample Output:
Input your first name: James
Input your last name: Smith

Hello
James Smith
Flowchart:
For more Practice: Solve these Related Problems:
 Modify the program to ask for user input and print "Hello, [Name]" dynamically.
 Print "Hello" in uppercase and your name in lowercase using string manipulation.
 Print "Hello" and your name, but each letter should be on a new line.
 Print "Hello" and your name, but reverse the order of characters.

Sum of Two Numbers


Write a Java program to print the sum of two numbers.
In mathematics, summation (capital Greek sigma symbol: ∑) is the addition of a sequence of numbers;
the result is their sum or total. The numbers to be summed may be integers, rational numbers, real
numbers, or complex numbers.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise2 {
public static void main(String[] args) {
// Calculate the sum of 24 and 26
int sum = 24 + 26;
// Print the result of the addition
System.out.println(sum);
}
}

Explanation:
This Java code defines a class called 'Exercise2' with a 'main' method. When executed, it prints the
result of the arithmetic expression '24 + 26' to the console, which is '50'.
Java programming course
Sample Output:
50
Flowchart:

Sample solution using input from the user:


Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args)
{
// Create a Scanner object to read input from the user
Scanner input = new Scanner(System.in);

// Prompt the user to input the first number


System.out.print("Input the first number: ");

// Read and store the first number


int num1 = input.nextInt();

// Prompt the user to input the second number


System.out.print("Input the second number: ");

// Read and store the second number


int num2 = input.nextInt();

// Calculate the sum of the two numbers


int sum = num1 + num2;

// Display a blank line for separation


System.out.println();

// Display the sum of the two numbers


System.out.println("Sum: " + sum);
}
}
Explanation:
The above Java code takes two numbers as input from the user, calculates their sum, and then displays
the result. It uses the Scanner class to read user input and performs basic arithmetic.
Java programming course
Sample Output:
Input the first number: 256
Input the second number: 326

Sum: 582
Flowchart:

For more Practice: Solve these Related Problems:


 Write a program that reads three numbers and prints their sum.
 Write a program that takes two floating-point numbers as input and prints their sum rounded to 2
decimal places.
 Modify the program to add two numbers but handle integer overflow gracefully.
 Print the sum of two numbers without using the '+' operator.

Division of Two Numbers


Write a Java program to divide two numbers and print them on the screen.
Division is one of the four basic operations of arithmetic, the others being addition, subtraction, and
multiplication. The division of two natural numbers is the process of calculating the number of times
one number is contained within one another.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise3 {
public static void main(String[] args) {
// Calculate the result of the division 50/3
int result = 50 / 3;

// Print the result of the division


System.out.println(result);
}
}

Java programming course


Explanation:
The above Java code defines a class called "Exercise3" with a "main()" method. When executed, it
prints the result of the division operation 50 / 3 to the console, which is approximately 16.6667 (since
it's integer division, it will be truncated to 16).
Sample Output:
16
Flowchart:

Sample solution using input from the user:


Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args)
{
// Create a Scanner object to read input from the user
Scanner input = new Scanner(System.in);

// Prompt the user to input the first number


System.out.print("Input the first number: ");

// Read and store the first number


int a = input.nextInt();

// Prompt the user to input the second number


System.out.print("Input the second number: ");

// Read and store the second number


int b = input.nextInt();

// Calculate the division of a and b


int d = (a / b);

// Display a blank line for separation


System.out.println();

// Display the result of the division


System.out.println("The division of a and b is: " + d);
}
}
Java programming course
Explanation:
The above Java code takes two integer numbers as input from the user, performs division, and displays
the result. It uses the "Scanner" class for input, divides 'a' by 'b', and prints the result as "The division of
a and b is: [result]."
Sample Output:
Input the first number: 7
Input the second number: 2

The division of a and b is:3


Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to take two decimal numbers and perform division.
 Write a program that divides two numbers and prints only the quotient.
 Write a program to divide two numbers and round the result to the nearest integer.
 Perform division, but handle cases where the denominator is zero.

Arithmetic Operations
Write a Java program to print the results of the following operations.
Pictorial Presentation:

Sample Solution-1
Java Code:
public class Exercise4 {
public static void main(String[] args) {
// Calculate and print the result of the expression: -5 + 8 * 6
System.out.println(-5 + 8 * 6);

// Calculate and print the result of the expression: (55 + 9) % 9


System.out.println((55 + 9) % 9);

// Calculate and print the result of the expression: 20 + -3 * 5 /


8
System.out.println(20 + -3 * 5 / 8);
// Calculate and print the result of the expression: 5 + 15 / 3 *
2 - 8 % 3
System.out.println(5 + 15 / 3 * 2 - 8 % 3);
}
}

Explanation:
The above Java code calculates and prints the results of four different arithmetic expressions:
 '-5 + 8 * 6' evaluates to '43'.
 '(55 + 9) % 9' evaluates to '1'.
 '20 + -3 * 5 / 8' evaluates to '19'.
 '5 + 15 / 3 * 2 - 8 % 3' evaluates to '13'.
Each expression is evaluated based on the order of operations (PEMDAS/BODMAS), which
determines the sequence of arithmetic operations.
Note: PEMDAS stands for P- Parentheses, E- Exponents, M- Multiplication, D- Division, A- Addition,
and S- Subtraction.
BODMAS stands for Bracket, Of, Division, Multiplication, Addition, and Subtraction.
Sample Output:
43
1
19
13
Flowchart:

Sample Solution-2
Java Code:
public class Main {
public static void main(String[] args) {
// Calculate and store the result of the expression: -5 + 8 * 6
int w = -5 + 8 * 6;

// Calculate and store the result of the expression: (55 + 9) % 9


int x = (55 + 9) % 9;

// Calculate and store the result of the expression: 20 + (-3 * 5 / 8)


int y = 20 + (-3 * 5 / 8);

// Calculate and store the result of the expression: 5 + 15 / 3 * 2 -


8 % 3
int z = 5 + 15 / 3 * 2 - 8 % 3;

// Print the calculated values, each on a new line


System.out.print(w + "\n" + x + "\n" + y + "\n" + z);
}
}

Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to take operations dynamically as user input.
 Write a program to evaluate a complex mathematical expression: (a^2 + b^2) / (a - b).
 Write a program that calculates a series sum: 1 + 1/2 + 1/3 + 1/4 + … + 1/n.
 Write a program that computes the sum of squares of two numbers.

Product of Two Numbers


Write a Java program that takes two numbers as input and displays the product of two numbers.
Test Data:
Input first number: 25
Input second number: 5
Pictorial Presentation:

Sample Solution-1
Java Code:
import java.util.Scanner;

public class Exercise5 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input the first number


System.out.print("Input first number: ");
// Read and store the first number
int num1 = in.nextInt();
// Prompt the user to input the second number
System.out.print("Input second number: ");
// Read and store the second number

// Calculate the product of the two numbers and display the result
System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
}
}

Explanation:
The above Java code takes two integer numbers as input from the user, multiplies them, and then
displays the result in the format "num1 x num2 = result." It uses the "Scanner" class to read user input
and performs multiplication on the input values.
Sample Output:
Input first number: 25
Input second number: 5
25 x 5 = 125
Flowchart:

Sample Solution-2
Java Code:
public class Main
{
// Declare and initialize static variables x and y
static int x = 25;
static int y = 5;

public static void main(String[] args)


{
// Calculate and print the product of x and y
System.out.println(x * y);
}
}

Sample Output:
125
Flowchart:
For more Practice: Solve these Related Problems:
 Write a program that multiplies three numbers instead of two.
 Multiply two numbers without using the '*' operator.
 Write a program that multiplies a number by itself n times (exponentiation).
 Modify the program to accept floating-point numbers and print the product.

Basic Arithmetic Operations


Write a Java program to print the sum (addition), multiply, subtract, divide and remainder of
two numbers.
Test Data:
Input first number: 125
Input second number: 24
Pictorial Presentation:

Sample Solution-1
Java Code:
public class Exercise6 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input the first number


System.out.print("Input first number: ");
// Read and store the first number
int num1 = in.nextInt();

// Prompt the user to input the second number


System.out.print("Input second number: ");
// Read and store the second number

// Calculate and print the sum of the two numbers


System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));

// Calculate and print the difference of the two numbers


System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));

// Calculate and print the product of the two numbers


System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));

// Calculate and print the division of the two numbers


System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));

// Calculate and print the remainder of the division of the two numbers
System.out.println(num1 + " mod " + num2 + " = " + (num1 % num2);
}
}

Explanation:
In the exercise above -
 It takes two integer numbers as input from the user using the Scanner class.
o Scanner in = new Scanner(System.in);
o System.out.print("Input first number: ");
o int num1 = in.nextInt();
o System.out.print("Input second number: ");
 System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); - It calculates and displays
the sum of the two numbers.
 System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); - It calculates and displays
the difference between the two numbers.
 System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); - It calculates and displays
the product of the two numbers.
 System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); - It calculates and displays
the result of dividing the first number by the second number.
 System.out.println(num1 + " mod " + num2 + " = " + (num1 % num2)); - It calculates and
displays the remainder (modulus) when the first number is divided by the second number.
Sample Output:
Input first number: 125
Input second number: 24
125 + 24 = 149
125 - 24 = 101
125 x 24 = 3000
125 / 24 = 5
125 mod 24 = 5
Flowchart:
Sample Solution-2
Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to input the first number


System.out.println("Input the first number: ");

// Read and store the first number


int n1 = scanner.nextInt();

// Prompt the user to input the second number


System.out.println("Input the second number: ");

// Read and store the second number

// Calculate the sum of the two numbers


int sum = n1 + n2;

// Calculate the difference of the two numbers


int minus = n1 - n2;

// Calculate the product of the two numbers


int multiply = n1 * n2;

// Calculate the addition of the two numbers (Note: This comment may be
a typo; it seems similar to the "sum" calculation)
int subtract = n1 + n2;

// Calculate the division of the two numbers


int divide = n1 / n2;

// Calculate the remainder when dividing the two numbers


int rnums = n1 % n2;
// Display the results of the calculations
System.out.printf("Sum = %d\nMinus = %d\nMultiply = %d\nSubtract = %d\
nDivide = %d\nRemainderOf2Numbers = %d\n ", sum, minus, multiply,
subtract, divide, rnums);
}
}

Sample Output:
Input the first number:
6
Input the second number:
5
Sum = 11
Minus = 1
Multiply = 30
Subtract = 11
Divide = 1
RemainderOf2Numbers = 1
Flowchart:

For more Practice: Solve these Related Problems:


 Write a program that performs arithmetic operations on three numbers instead of two.
 Modify the program to take input from the user and display the results dynamically.
 Perform arithmetic operations, but ensure the division operation rounds to two decimal places.
 Write a program that performs arithmetic operations without using '+', '-', '*', or '/' operators.

Multiplication Table
Write a Java program that takes a number as input and prints its multiplication table up to 10.
Test Data:
Input a number: 8
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise7 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input a number


System.out.print("Input a number: ");

// Read and store the input number


int num1 = in.nextInt();

// Use a loop to calculate and print the multiplication table for the
input number
for (int i = 0; i < 10; i++) {
// Calculate and print the result of num1 multiplied by (i+1)
System.out.println(num1 + " x " + (i + 1) + " = " + (num1 * (i +
1)));
}
}
}

Explanation:
In the exercise above -

 It takes an integer number as input from the user using the Scanner class.
 It then enters a for loop that iterates 10 times (for values of i from 0 to 9).
 Inside the loop, it calculates and prints the result of multiplying the input number by i+1, displaying a
multiplication table for the input number from 1 to 10.
Sample Output:
Input a number: 8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80
Flowchart:

Sample Solution:
Java Code:
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input a number


System.out.println("Input the Number: ");

// Read and store the input number


int n = in.nextInt();

// Use a loop to generate and print the multiplication table for the
input number
for (int i = 1; i <= 10; i++) {
// Calculate and print the result of n multiplied by i
System.out.println(n + "*" + i + " = " + (n * i));
}
}
}

Sample Output:
Input the Number:
6
6*1 = 6
6*2 = 12
6*3 = 18
6*4 = 24
6*5 = 30
6*6 = 36
6*7 = 42
6*8 = 48
6*9 = 54
6*10 = 60
Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to print the multiplication table up to 20 instead of 10.
 Write a program that prints the multiplication table of a given number in reverse order.
 Modify the program to print the multiplication table in a tabular format with proper alignment.
 Write a program that generates the multiplication tables of numbers from 1 to 10.

Pattern Display: JAVA


Write a Java program to display the following pattern.
Sample Pattern :
J a v v a
J a a v v a a
J J aaaaa V V aaaaa
JJ a a V a a
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise8 {

public static void main(String[] args) {


// Display the characters to form the text "Java" in a specific
pattern
System.out.println(" J a v v a ");
System.out.println(" J a a v v a a");
System.out.println("J J aaaaa V V aaaaa");
System.out.println(" JJ a a V a a");
}
}

Sample Output:
J a v v a
J a a v v a a
J J aaaaa V V aaaaa
JJ a a V a a
Flowchart:

For more Practice: Solve these Related Problems:


 Write a program to print the word "JAVA" in an inverted pyramid pattern.
 Modify the program to print the letters using numbers instead of characters.
 Write a program to display the word "JAVA" diagonally across the screen.
 Print the pattern but replace the letter 'A' with user input.

Expression Evaluation
Write a Java program to compute the specified expressions and print the output.
Specified Expression :
(25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise9 {
public static void main(String[] arg) {
// Calculate and print the result of a mathematical expression
System.out.println((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5));
}
}

Explanation:
The above Java code calculates and prints the result of the following mathematical expression:
(25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)
The code performs arithmetic operations, including multiplication, subtraction, and division, and
displays the final result. In this case, the result will be printed to the console.
Sample Output:
2.138888888888889
Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to evaluate an expression entered by the user.
 Write a program that evaluates multiple expressions in a loop until the user exits.
 Compute an expression using variables instead of fixed numbers.
 Write a program that evaluates a complex formula containing square roots and exponents.

Formula Computation
Write a Java program to compute a specified formula.
Specified Expression :
4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11))
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise10 {
public static void main(String[] args) {
// Calculate the result of an alternating series and store it in
'result'
double result = 4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) -
(1.0/11));

// Print the calculated result


System.out.println(result);
}
}

Sample Output:
2.9760461760461765
Flowchart:

For more Practice: Solve these Related Problems:


 Write a program that computes the formula but allows the user to change the numerator and
denominator.
 Modify the program to compute a similar mathematical series with more terms.
 Write a program that evaluates the formula using recursion instead of iteration.
 Compute a different formula and compare results with the given formula.

Circle: Area and Perimeter


Write a Java program to print the area and perimeter of a circle.
In geometry, the area enclosed by a circle of radius r is πr2. Here the Greek letter π represents a
constant, approximately equal to 3.14159, which is equal to the ratio of the circumference of any circle
to its diameter.
Circle-shaped kitchenware
The circumference of a circle is the linear distance around its edge.
Pictorial Presentation:
Circle-shaped art prints

Geometry course
Why is the area of a circle of a circle pi times the square of the radius?
Circle-shaped furniture

Circle-shaped art prints

Sample Solution-1
Java Code:
Circle-shaped furniture
public class Exercise11 {
// Define a constant for the radius of the circle
private static final double radius = 7.5;

public static void main(String[] args) {


// Calculate the perimeter of the circle using the constant radius
double perimeter = 2 * Math.PI * radius;

// Calculate the area of the circle using the constant radius


double area = Math.PI * radius * radius;

// Print the calculated perimeter and area


System.out.println("Perimeter is = " + perimeter);
System.out.println("Area is = " + area);
}
}

Explanation:
In the exercise above -
The above Java code calculates and prints the perimeter and area of a circle with a given radius (in this
case, a radius of 7.5 units). It uses mathematical constants and formulas for circles:
Circle-shaped kitchenware

 It calculates the perimeter (circumference) using the formula: 2 * Math.PI * radius;


 It calculates the area using the formula: π * radius^2.
The perimeter and area values are then printed to the console.
Sample Output:
Perimeter is = 47.12388980384689
Area is = 176.71458676442586
Flowchart:
Circle-shaped art prints

Mathematics course
Pi calculator

Sample Solution-2
Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner io = new Scanner(System.in);

// Prompt the user to input the radius of the circle


System.out.println("Input the radius of the circle: ");

// Read and store the input radius


double radius = io.nextDouble();

// Calculate and print the perimeter of the circle


System.out.println("Perimeter is = " + (2 * radius * Math.PI));

// Calculate and print the area of the circle


System.out.println("Area is = " + (Math.PI * radius * radius));
}
}

Sample Output:
Input the radius of the circle:
5
Perimeter is = 31.41592653589793
Area is = 78.53981633974483
Flowchart:
For more Practice: Solve these Related Problems:
 Write a program to calculate the circumference and area of an ellipse.
 Modify the program to calculate the area and perimeter of a semicircle.
 Write a program to compare the areas of two circles given their radii.
 Calculate the surface area and volume of a sphere.
Pi calculator

Average of Three Numbers


Write a Java program that takes five numbers as input to calculate and print the average of the
numbers.
Test Data:
Input first number: 10
Input second number: 20
Input third number: 30
Input fourth number: 40
Enter fifth number: 50
Pictorial Presentation:

Sample Solution-1
Java Code:
import java.util.Scanner;

public class Exercise12 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);

// Prompt the user to input the first number


System.out.print("Input first number: ");
// Read and store the first number
int num1 = in.nextInt();

// Prompt the user to input the second number


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

// Read and store the second number


int num2 = in.nextInt();

// Prompt the user to input the third number


System.out.print("Input third number: ");

// Read and store the third number


int num3 = in.nextInt();

// Prompt the user to input the fourth number


System.out.print("Input fourth number: ");

// Read and store the fourth number


int num4 = in.nextInt();

// Prompt the user to input the fifth number


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

// Read and store the fifth number


int num5 = in.nextInt();

// Calculate and print the average of the five numbers


System.out.println("Average of five numbers is: " + (num1 + num2 + num3
+ num4 + num5) / 5);
}
}

Explanation:
In the exercise above -
 It prompts the user to input five different numbers, one by one.
 It reads and stores each number in separate variables: num1, num2, num3, num4, and num5.
 It calculates the average of these five numbers by adding them together and dividing the sum by 5.
 It displays the calculated average with the message "Average of five numbers is:" to the console.
Sample Output:
Input first number: 10
Input second number: 20
Input third number: 30
Input fourth number: 40
Enter fifth number: 50
Average of five numbers is: 30
Flowchart:
Sample Solution-2
Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// Initialize variables for sum and counting
double num = 0;
double x = 1;

// Create a Scanner object to read input from the user


Scanner sc = new Scanner(System.in);

// Prompt the user to input the number (n) for which to calculate the
average
System.out.println("Input the number(n) you want to calculate the
average: ");
int n = sc.nextInt();

// Use a loop to collect n numbers and calculate their sum


while (x <= n) {
System.out.println("Input number " + "(" + (int) x + ")" + ":");
num += sc.nextInt();
x += 1;
}

// Calculate the average of the collected numbers


double avgn = (num / n);

// Display the calculated average


System.out.println("Average: " + avgn);
}
}

Sample Output:
Input the number(n) you want to calculate the average:
4
Input number (1):
2
Input number (2):
4
Input number (3):
4
Input number (4):
2
Average:3.0
Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to calculate the average of five numbers instead of three.
 Write a program that calculates the average but ignores the lowest and highest values.
 Modify the program to find the weighted average of three numbers.
 Compute the average of numbers until the user enters a negative number.

Rectangle: Area and Perimeter


Rectangle-themed merchandise
Write a Java program to print the area and perimeter of a rectangle.
Java: Perimeter of a rectangle
A perimeter is a path that surrounds a two-dimensional shape. The word comes from the Greek peri
(around) and meter (measure). The perimeter can be used to calculate the length of fence required to
surround a yard or garden. Following image represents the perimeter of a rectangle.
Java: Area of a rectangle
Rectangle-themed merchandise
In Euclidean plane geometry, a rectangle is a quadrilateral with four right angles. To find the area of a
rectangle, multiply the length by the width.
A rectangle with four sides of equal length is a square.
Following image represents the area of a rectangle.
Pictorial Presentation:

Rectangle-themed merchandise

Sample Solution:
Java Code:
Quadrilateral-based products
public class Exercise13 {
public static void main(String[] strings) {
// Define constants for the width and height of the rectangle
final double width = 5.6;
final double height = 8.5;

// Calculate the perimeter of the rectangle


double perimeter = 2 * (height + width);

// Calculate the area of the rectangle


double area = width * height;

// Print the calculated perimeter using placeholders for values


System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f \n",
height, width, perimeter);

// Print the calculated area using placeholders for values


System.out.printf("Area is %.1f * %.1f = %.2f \n", width, height,
area);
}
}

Square-shaped products
Explanation:
In the exercise above -
 Define constant values for the rectangle's width (5.6) and height (8.5).
 Calculate the rectangle perimeter using the formula: 2 * (height + width).
 Calculate the rectangle area using the formula: width * height.
 Prints the perimeter and area values to the console using printf statements with formatted output to
display the results with specific decimal precision.
Rectangle-themed merchandise
Sample Output:
Perimeter is 2*(8.5 + 5.6) = 28.20
Area is 5.6 * 8.5 = 47.60
Flowchart:

For more Practice: Solve these Related Problems:


 Write a program to calculate the area and perimeter of a parallelogram.
 Modify the program to accept user input for both width and height.
 Write a program that calculates the area and perimeter of a rectangle with decimal values.
 Compute the diagonal length of a rectangle using the Pythagorean theorem.
Rectangle-themed merchandise

American Flag Display


Write a Java program to print an American flag on the screen.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise14 {

public static void main(String[] args) {


// Print a pattern of asterisks and equal signs to create a design
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");

// Print a row of equal signs to complete the design

System.out.println("==============================================");

System.out.println("==============================================");

System.out.println("==============================================");

System.out.println("==============================================");

System.out.println("==============================================");

System.out.println("==============================================");
}
}

Sample Output:
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
==============================================
==============================================
==============================================
==============================================
==============================================
==============================================
Flowchart:
Sample Solution:
Java Code:
public class Main {
public static void main(String[] args) {
// Define pattern strings for the top and middle sections
String p1 = "* * * * * * ==================================\n * *
* * * ==================================";
String p2 = "==============================================";
// Print the top section pattern 4 times
for (int i = 0; i < 4; i++) {
System.out.println(p1);
}
// Print the bottom section pattern once
System.out.println("* * * * * *
==================================");
// Print the middle section pattern 6 times
for (int i = 0; i < 6; i++) {
System.out.println(p2);
}
}
}

Output:
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
==============================================
==============================================
==============================================
==============================================
==============================================
==============================================
Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to display a different country’s flag using characters.
 Write a program that prints the American flag with stars aligned dynamically.
 Modify the program to print the flag using only '*' and '-' characters.
 Create a function that prints a scaled version of the flag based on user input.

Swap Variables
Write a Java program to swap two variables.
Java: Swapping two variables
Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is
done with the data in memory.
The simplest method to swap two variables is to use a third temporary variable :
define swap(a, b)
temp := a
a := b
b := temp
Pictorial Presentation:
Sample Solution-1
Java Code:
public class Exercise15 {

public static void main(String[] args) {


// Declare variables for the values to be swapped
int a, b, temp;

// Assign values to variables a and b


a = 15;
b = 27;

// Print the values before swapping


System.out.println("Before swapping : a, b = " + a + ", " + b);

// Perform the swap using a temporary variable


temp = a;
a = b;
b = temp;

// Print the values after swapping


System.out.println("After swapping : a, b = " + a + ", " + b);
}
}

Explanation:
In the exercise above -

 Initialize two integer variables, 'a' with the value 15 and 'b' with the value 27.
 Prints the original values of 'a' and 'b' before swapping.
 Use a temporary variable temp to temporarily store the value of 'a'.
 Assign the value of 'b' to 'a'.
 Assign the value stored in temp (originally from a) to 'b'.
 Finally, it prints the values of 'a' and 'b' after the swapping operation.
Without using third variable.
Sample Solution-2
Java Code:
public class Exercise15 {
public static void main(String[] args) {
// Declare and initialize integer variables a and b
int a, b;
a = 15;
b = 27;

// Print the values before swapping


System.out.println("Before swapping : a, b = " + a + ", " + b);

// Perform the swap without using a temporary variable


a = a + b; // Add a and b and store the result in a
b = a - b; // Subtract the original b from the new a and store the
result in b
a = a - b; // Subtract the new b from the updated a and store the
result in a

// Print the values after swapping


System.out.println("After swapping : a, b = " + a + ", " + b);
}
}

Explanation:
In the exercise above -

 Initialize two integer variables, 'a' with the value 15 and 'b' with the value 27.
 Prints the original values of 'a' and 'b' before swapping.
 Use arithmetic operations to swap values without using a temporary variable:
o a = a + b adds 'a' and 'b' and stores the sum in 'a'. Now, 'a' contains the sum of the original 'a' and
'b'.
o b = a - b subtracts the original 'b' from the updated 'a' and stores the result in 'b'. Now, 'b' contains
the original value of 'a'.
o a = a - b subtracts the updated 'b' (which now contains the original value of 'a') from the updated
'a' and stores the result in 'a'. Now, 'a' contains the original value of 'b'.
 Finally, it prints the values of 'a' and 'b' after the swapping operation.
Sample Output:
Before swapping : a, b = 15, 27
After swapping : a, b = 27, 15
Flowchart:
Sample Solution (Input from the user):
Java Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// Declare integer variables for storing user input and swapping
int x, y, z;

// Create a Scanner object to read input from the user


Scanner in = new Scanner(System.in);

// Prompt the user to input the first number


System.out.println("Input the first number: ");
x = in.nextInt();

// Prompt the user to input the second number


System.out.println("Input the second number: ");
y = in.nextInt();

// Perform the swap using a temporary variable 'z'


z = x;
x = y;
y = z;

// Display the swapped values


System.out.println("Swapped values are: " + x + " and " + y);
}
}

Sample Output:
Input the first number:
36
Input the second number:
44
Swapped values are:44 and 36
Flowchart:
For more Practice: Solve these Related Problems:
 Swap two variables without using a temporary variable.
 Swap three variables in a circular fashion.
 Write a program that swaps two numbers but does not allow direct arithmetic operations.
 Swap two strings instead of integers.

Face Printer
Write a Java program to print a face.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise16 {
public static void main(String[] args)
{
// Display a pattern to create an ASCII art representation of a
simple face
System.out.println(" +\"\"\"\"\"+ ");
System.out.println("[| o o |]");
System.out.println(" | ^ | ");
System.out.println(" | '-' | ");
System.out.println(" +-----+ ");
}
}

Sample Output:
+"""""+
[| o o |]
| ^ |
| '-' |
+-----+
Flowchart:

Sample Solution (using array):


Java Code:
public class Main {

public static void main(String[] args) {


// Create an array to store lines of an ASCII art representation
String[] arra = new String[5];

// Populate the array with lines to form an ASCII art representation of


a simple face
arra[0] = " +\"\"\"\"\"+ ";
arra[1] = "[| o o |]";
arra[2] = " | ^ |";
arra[3] = " | '-' |";
arra[4] = " +-----+";

// Use a loop to print each line of the ASCII art representation


for (int i = 0; i < 5; i++) {
System.out.println(arra[i]);
}
}
}

Flowchart:
For more Practice: Solve these Related Problems:
 Modify the program to print a different emoji-style face.
 Write a program that prints an ASCII representation of an animal.
 Modify the face printer to display a smiling and frowning face alternately.
 Write a program that prints the face with different eyes based on user input.

Check Java Installation


Write a Java program to check whether Java is installed on your computer.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise31 {
public static void main(String[] args) {
// Display Java version
System.out.println("\nJava Version: " +
System.getProperty("java.version"));

// Display Java runtime version


System.out.println("Java Runtime Version: " +
System.getProperty("java.runtime.version"));

// Display Java home directory


System.out.println("Java Home: " +
System.getProperty("java.home"));

// Display Java vendor name


System.out.println("Java Vendor: " +
System.getProperty("java.vendor"));

// Display Java vendor URL


System.out.println("Java Vendor URL: " +
System.getProperty("java.vendor.url"));

// Display Java class path


System.out.println("Java Class Path: " +
System.getProperty("java.class.path") + "\n");
}
}

Explanation:
In the exercise above:
 It uses System.getProperty() to access and retrieve specific Java system properties.
 Finally, it prints the following information about the Java runtime environment:
o Java Version: The Java version installed on the system.
o Java Runtime Version: The Java Runtime Environment (JRE) used.
o Java Home: The directory path to the Java installation directory.
o Java Vendor: The Java runtime vendor or provider.
o Java Vendor URL: The Java vendor's URL or website.
o Java Class Path: The classpath, which specifies the directories and JAR files that the
Java runtime should use when searching for classes and resources.
Java Runtime Environment software
Sample Output:
Java Version: 1.8.0_71
Java Runtime Version: 1.8.0_71-b15
Java Home: /opt/jdk/jdk1.8.0_71/jre
Java Vendor: Oracle Corporation
Java Vendor URL: http://java.oracle.com/
Java Class Path: .
Flowchart:
For more Practice: Solve these Related Problems:
 Write a Java program to display the Java Runtime Environment version, vendor, and
installation path.
 Write a Java program to determine the current Java Virtual Machine (JVM) architecture (32-bit
or 64-bit).
 Write a Java program to check whether a specific Java system property (e.g., "java.vm.name")
exists and display its value.
 Write a Java program to list all system properties available in the Java environment.
Java Runtime Environment software

Compare Two Numbers


Write a Java program to compare two numbers.
Test Data:
Input first integer: 25
Input second integer: 39
Pictorial Presentation:

Sample Solution:
Java Code:
Java programming book
import java.util.Scanner;
public class Exercise32 {
public static void main(String args[]) {
// Create a Scanner to obtain input from the command window
Scanner input = new Scanner(System.in);
int number1; // First number to compare
int number2; // Second number to compare

// Prompt the user to input the first integer


System.out.print("Input first integer: ");
number1 = input.nextInt(); // Read the first number from the user

// Prompt the user to input the second integer


System.out.print("Input second integer: ");
number2 = input.nextInt(); // Read the second number from the user

// Compare and display the results


if (number1 == number2)
System.out.printf("%d == %d\n", number1, number2);
if (number1 != number2)
System.out.printf("%d != %d\n", number1, number2);
if (number1 < number2)
System.out.printf("%d < %d\n", number1, number2);
if (number1 > number2)
System.out.printf("%d > %d\n", number1, number2);
if (number1 <= number2)
System.out.printf("%d <= %d\n", number1, number2);
if (number1 >= number2)
System.out.printf("%d >= %d\n", number1, number2);
}
}

Explanation:
In the exercise above –

 First, it uses the "Scanner" class to obtain input from the command window (user input).
 It declares two integer variables 'number1' and 'number2' to store the two numbers provided by the user.
 It prompts the user to input the first integer using System.out.print("Input first integer: ") and reads the
input into 'number1'.
 It prompts the user to input the second integer using System.out.print("Input second integer: ") and reads
the input into 'number2'.
 Next it performs a series of comparisons using if statements and prints the results using
System.out.printf():
Java programming course

o if (number1 == number2) checks if 'number1' is equal to 'number2' and prints a message if they
are equal.
o if (number1 != number2) checks if 'number1' is not equal to 'number2' and prints a message if
they are not equal.
o if (number1 < number2) checks if 'number1' is less than 'number2' and prints a message if
'number1' is less than 'number2'.
o if (number1 > number2) checks if 'number1' is greater than 'number2' and prints a message if
'number1' is greater than 'number2'.
o if (number1 <= number2) checks if 'number1' is less than or equal to 'number2' and prints a
message accordingly.
o if (number1 >= number2) checks if 'number1' is greater than or equal to number2 and prints a
message accordingly.
Sample Output:
Input first integer: 25
Input second integer: 39
25 != 39
25 < 39
25 <= 39
Flowchart:
For more Practice: Solve these Related Problems:
 Modify the program to compare three numbers.
 Write a program that compares floating-point numbers.
 Implement a function to compare numbers without using conditional operators.
 Modify the program to check for equality within a specified tolerance.

Go to:

 Java Basic Programming Exercises Home ↩


 Java Exercises Home ↩

PREV : Check Java Installation.


NEXT : Sum of Digits.

Sum of Digits
Write a Java program and compute the sum of an integer's digits.
Computer programming tool
Test Data:
Input an intger: 25
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise33 {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to input an integer


System.out.print("Input an integer: ");

// Read the integer from the user


long n = input.nextLong();

// Calculate and display the sum of the digits


System.out.println("The sum of the digits is: " + sumDigits(n));
}

public static int sumDigits(long n) {


int sum = 0;

// Calculate the sum of the digits


while (n != 0) {
sum += n % 10;
n /= 10;
}

return sum;
}
}

Explanation:
In the exercise above -
 It uses the Scanner class to obtain input from the user.
 First, it prompts the user to input an integer using System.out.print("Input an integer: ") and reads the
input into the variable 'n'.
 It then calls a separate method named "sumDigits()" and passes the input integer n as an argument.
 Inside the "sumDigits()" method:
o It initializes an integer variable 'sum' to store the sum of the digits, starting with 0.
o It enters a while loop that continues as long as 'n' is not equal to 0.
o Inside the loop, it calculates the last digit of 'n' using the modulus operator (n % 10) and adds it
to the 'sum' variable.
o It then removes the last digit from 'n' by dividing it by 10 (n /= 10).
o This process continues until all digits of the original number have been processed.
o Finally, it returns the 'sum' containing the sum of the digits.
 Finally, back in the "main()" method, it prints the result of the "sumDigits()" method, displaying the sum
of the digits of the entered integer.
Sample Output:
Input an intger: 25
The sum of the digits is: 7
Flowchart:
For more Practice: Solve these Related Problems:
 Find the sum of digits using recursion.
 Modify the program to compute the product of digits instead.
 Find the sum of digits for a very large number.
 Write a program to sum the digits of a binary number.

Hexagon Area
Write a Java program to compute hexagon area.
Test Data:
Input the length of a side of the hexagon: 6
Pictorial Presentation: Area of Hexagon

Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise34 {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to input the length of a side of the hexagon


System.out.print("Input the length of a side of the hexagon: ");

// Read the length of a side from the user


double s = input.nextDouble();

// Calculate and display the area of the hexagon


System.out.print("The area of the hexagon is: " + hexagonArea(s) +
"\n");
}

public static double hexagonArea(double s) {


// Calculate the area of a hexagon based on its side length
return (6 * (s * s)) / (4 * Math.tan(Math.PI / 6));
}
}

Explanation:
In the exercise above -

 First it uses the "Scanner" class to obtain input from the user.
 It prompts the user to input the length of a side of the hexagon using System.out.print("Input the length
of a side of the hexagon: ") and reads the input into the variable 's'.
 It then calls a separate method named "hexagonArea()" and passes the input length s as an argument.
 Inside the "hexagonArea()" method:
o It calculates the area of the hexagon using the formula (6 s^2) / (4 tan(π/6)), where s is the length
of a side and tan(π/6) represents the tangent of 30 degrees (π/6 radians), which is a constant
value.
o It returns the calculated area as a double.
 Finally, back in the "main()" method, it prints the result of the "hexagonArea()" method, displaying the
area of the hexagon based on the user-provided side length.
Sample Output:
Input the length of a side of the hexagon: 6
The area of the hexagon is: 93.53074360871938
Flowchart:

For more Practice: Solve these Related Problems:


 Compute the perimeter of a hexagon.
 Write a program to compute the area of an octagon.
 Modify the program to handle floating-point side lengths.
 Calculate the area of a regular pentagon.
Go to:

 Java Basic Programming Exercises Home ↩


 Java Exercises Home ↩

PREV : Sum of Digits.


NEXT : Polygon Area.

Distance Between Two Points


Write a Java program to compute the distance between two points on the earth's surface.
Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2))
Radius of the earth r = 6371.01 Kilometers
Test Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 52.5
Input the longitude of coordinate 2: 35.5
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise36 {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to input the latitude and longitude of


coordinate 1
System.out.print("Input the latitude of coordinate 1: ");
double lat1 = input.nextDouble();
System.out.print("Input the longitude of coordinate 1: ");
double lon1 = input.nextDouble();

// Prompt the user to input the latitude and longitude of


coordinate 2
System.out.print("Input the latitude of coordinate 2: ");
double lat2 = input.nextDouble();
System.out.print("Input the longitude of coordinate 2: ");
double lon2 = input.nextDouble();

// Calculate and display the distance between the two coordinates


System.out.print("The distance between those points is: " +
distance_Between_LatLong(lat1, lon1, lat2, lon2) + " km\n");
}

// Points will be converted to radians before calculation


public static double distance_Between_LatLong(double lat1, double
lon1, double lat2, double lon2) {
// Convert latitude and longitude to radians
lat1 = Math.toRadians(lat1);
lon1 = Math.toRadians(lon1);
lat2 = Math.toRadians(lat2);
lon2 = Math.toRadians(lon2);

// Earth's mean radius in kilometers


double earthRadius = 6371.01;

// Calculate the distance using the haversine formula


return earthRadius * Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
}
}

Explanation:
In the exercise above -

 First, it uses the "Scanner" class to obtain user input.


 The user is prompted to input the latitude and longitude of two coordinates:
o Latitude and longitude of coordinate 1 are read into the variables 'lat1' and 'lon1'.
o Latitude and longitude of coordinate 2 are read into the variables 'lat2' and 'lon2'.
 The code then calls a separate method named "distance_Between_LatLong()" and passes the
latitude and longitude values of both coordinates as arguments.
 Inside the "distance_Between_LatLong()" method:
o It converts latitude and longitude values from degrees to radians using the
"Math.toRadians()" method to perform trigonometric calculations.
o It calculates the distance between the two coordinates using the Haversine formula for
calculating distances on a sphere.
o The calculated distance is returned as a double, representing the distance in kilometers.
 Finally, in the "main() method, the result of the "distance_Between_LatLong()" method is
printed, displaying the distance between the two coordinates in kilometers.
Sample Output:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 52.5
Input the longitude of coordinate 2: 35.5
The distance between those points is: 3058.15512920181 km
Flowchart:

For more Practice: Solve these Related Problems:


 Modify the program to work with miles instead of kilometers.
 Write a program that finds the midpoint between two coordinates.
 Compute the distance between three points instead of two.
 Modify the program to calculate the Manhattan distance.

Reverse a String
Write a Java program to reverse a string.
Test Data:
Input a string: The quick brown fox
Pictorial Presentation: Reverse a string

Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise37 {


public static void main(String[] args) {
// Create a scanner to obtain input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to input a string


System.out.print("Input a string: ");

// Read the input string and convert it to a character array


char[] letters = scanner.nextLine().toCharArray();

// Display a message before printing the reversed string


System.out.print("Reverse string: ");

// Iterate through the character array in reverse order and print


each character
for (int i = letters.length - 1; i >= 0; i--) {
System.out.print(letters[i]);
}

// Print a newline character to end the output line


System.out.print("\n");
}
}

Explanation:
In the exercise above -

 First, it uses the " Scanner" class to obtain user input.


 The user is prompted to input a string using System.out.print("Input a string: ").
 The input string is read using scanner.nextLine() and converted to a character array using
toCharArray(). This character array is stored in the 'letters' variable.
 Next, the code enters a loop that iterates from the last character of the 'letters' array to the first character
(in reverse order). Inside the loop, it prints each character, effectively reversing the string character by
character.
 Finally, a newline character is printed to ensure a clean output format.
Sample Output:
Input a string: The quick brown fox
Reverse string: xof nworb kciuq ehT
Flowchart:

For more Practice: Solve these Related Problems:


 Reverse a string without using built-in functions.
 Modify the program to reverse words instead of characters.
 Reverse only the vowels in a string.
 Implement string reversal using recursion.

PREV : Distance Between Two Points.


NEXT : Count Characters in String.

Count Characters in String


Write a Java program to count letters, spaces, numbers and other characters in an input string.
Test Data:
The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;

public class Exercise38 {


public static void main(String[] args) {
// Define a test string containing letters, numbers, spaces, and
other characters
String test = "Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33";

// Call the count method to analyze the characters in the test


string
count(test);
}

public static void count(String x) {


// Convert the input string to a character array
char[] ch = x.toCharArray();

// Initialize counters for letters, spaces, numbers, and other


characters
int letter = 0;
int space = 0;
int num = 0;
int other = 0;

// Iterate through the character array to categorize characters


for (int i = 0; i < x.length(); i++) {
// Check if the character is a letter
if (Character.isLetter(ch[i])) {
letter++;
}
// Check if the character is a digit (number)
else if (Character.isDigit(ch[i])) {
num++;
}
// Check if the character is a space
else if (Character.isSpaceChar(ch[i])) {
space++;
}
// Character falls into the "other" category if none of the
above conditions are met
else {
other++;
}
}

// Display the original string


System.out.println("The string is : Aa kiu, I swd skieo 236587. GH
kiu: sieo?? 25.33");

// Display the counts of letters, spaces, numbers, and other


characters
System.out.println("letter: " + letter);
System.out.println("space: " + space);
System.out.println("number: " + num);
System.out.println("other: " + other);
}
}

Explanation:
In the exercise above -
 The string to be analyzed is stored in the 'test' variable.
 The "count()" method takes a string 'x' as its parameter.
 Inside the "count()" method, the "toCharArray()" method is used to convert the input string x into an
array of characters 'ch'.
 Four variables (letter, space, num, and other) are initialized to zero. These variables will be used to
count the respective types of characters in the string.
 A for loop iterates through each character in the 'ch' array.
 Inside the loop, it checks the type of each character using various "Character" class methods like
isLetter(), isDigit(), and isSpaceChar(). Depending on the type, it increments the corresponding counter
variable (letter, num, space, or other).
 Finally, it prints the original string and the counts of each character type.
Sample Output:
The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33
letter: 23
space: 9
number: 10
other: 6
Flowchart:
For more Practice: Solve these Related Problems:
 Modify the program to count uppercase and lowercase letters separately.
 Write a program to find the most frequent character in a string.
 Ignore punctuation while counting letters.
 Implement character counting using a hash map.

PREV : Reverse a String.


NEXT : Unique Three-Digit Numbers.

You might also like