JAVA SOLUTIONS

 JAVA PROGRAMMING


1. Step-by-step explanation of the "Hello,

World!" program in Java: step-by-step

explanation of the "Hello, World!" program

in Java:


### Step 1: Define the Class

java

public class HelloWorld {

- *public*: This keyword means that the class can be accessed from anywhere.

- *class*: This keyword defines a new class.

- *HelloWorld*: This is the name of the class. By convention, class names in Java start with an

uppercase letter and follow CamelCase.

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: This keyword allows the main method to be accessible from outside the class.

- *static*: This means the method belongs to the class, not to instances of the class. You don’t

need to create an object of the class to call this method.

- *void*: This specifies that the main method does not return any value.

- *main*: This is the name of the method that serves as the entry point for the program. The

Java Virtual Machine (JVM) looks for this method to start execution.

- *String[] args*: This is a parameter named args which is an array of String objects. It can hold

command-line arguments passed to the program.

### Step 3: Print "Hello, World!"

java

System.out.println("Hello, World!");


- *System*: This is a built-in class in Java that provides access to system resources.

- *out*: This is a static field of the System class that represents the standard output stream

(usually the console).

- *println*: This method prints the given string followed by a newline character.

- *"Hello, World!"*: This is a string literal that will be printed to the console.

### Step 4: Close the Method and Class

java

}

}

- The closing curly brace } marks the end of the main method and the HelloWorld class.

### Complete Program

Putting it all together, the complete program looks like this:

java

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

}

}


### How it Works:

1. *Compile*: When you compile the program using javac HelloWorld.java, it creates a file

HelloWorld.class which contains the bytecode.

2. *Run*: When you run the program using java HelloWorld, the JVM executes the main

method, which prints "Hello, World!" to the console.

2. Sum of two numbers:


### Step 1: Define the Class

java

public class SumOfTwoNumbers {

- *public*: This access modifier means the class can be accessed from anywhere.

- *class*: This keyword is used to declare a class.

- *SumOfTwoNumbers*: This is the name of the class. It should match the filename

(SumOfTwoNumbers.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: This allows the main method to be accessed from outside the class.

- *static*: This means the method belongs to the class itself, not to instances of the class. It can

be called without creating an object of the class.

- *void*: This specifies that the method does not return any value.

- *main*: This is the name of the method that serves as the entry point of the program.

- *String[] args*: This parameter is an array of String objects that can hold command-line

arguments.

### Step 3: Declare and Initialize Variables

java

int number1 = 5;

int number2 = 10;

- *int*: This data type is used to store integer values.

- *number1* and *number2*: These are variables that store the values to be summed. They are

initialized with the values 5 and 10, respectively.

### Step 4: Calculate the Sum

java

int sum = number1 + number2;

- *int sum*: This declares a variable named sum to store the result of the addition.

- *number1 + number2*: This expression calculates the sum of number1 and number2.

### Step 5: Print the Result

java

System.out.println("The sum of " + number1 + " and " + number2 + " is " + sum);

- *System.out.println*: This method prints text to the console.

- *"The sum of " + number1 + " and " + number2 + " is " + sum*: This concatenates the string

with the values of number1, number2, and sum to produce a readable message.

### Step 6: Close the Method and Class

java

}

}


- The closing curly brace } ends the main method and the SumOfTwoNumbers class.

### Complete Program

Putting it all together, the complete program is:

java

public class SumOfTwoNumbers {

public static void main(String[] args) {

int number1 = 5;

int number2 = 10;

int sum = number1 + number2;

System.out.println("The sum of " + number1 + " and " + number2 + " is " + sum);

}

}


### How It Works:

1. *Compile*: Save the file as SumOfTwoNumbers.java and compile it with javac

SumOfTwoNumbers.java.

2. *Run*: Execute the program with java SumOfTwoNumbers, which will display the result in the

console.

3. To print "Welcome" 10 times in Java,

you can use a loop.

### Step 1: Define the Class

java

public class PrintWelcome {

- *public*: This access modifier means the class can be accessed from anywhere.

- *class*: This keyword declares a class.

- *PrintWelcome*: This is the name of the class, which should match the filename

(PrintWelcome.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: This allows the main method to be accessed from outside the class.


- *static*: This means the method belongs to the class and can be called without creating an

instance of the class.

- *void*: This specifies that the method does not return any value.

- *main*: This is the entry point of the program.

- *String[] args*: This parameter allows the method to accept command-line arguments.

### Step 3: Use a for Loop to Print "Welcome"

java

for (int i = 0; i < 10; i++) {

System.out.println("Welcome");

}

- *for*: This keyword starts a for loop, which will iterate a specific number of times.

- *int i = 0*: This initializes the loop control variable i to 0.

- *i < 10*: This is the loop condition. The loop will continue as long as i is less than 10.

- *i++*: This increments the loop control variable i by 1 after each iteration.

- *System.out.println("Welcome")*: This prints "Welcome" to the console in each iteration of

the loop.

### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the PrintWelcome class.

### Complete Program

Here is the complete Java program:

java

public class PrintWelcome {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

System.out.println("Welcome");

}

}

}


### How It Works:

1. *Compile*: Save the file as PrintWelcome.java and compile it with javac PrintWelcome.java.


2. *Run*: Execute the program with java PrintWelcome. It will print "Welcome" ten times, each

on a new line.

4. To print "Your Name" 10 times using a

do-while loop in Java:

### Step 1: Define the Class

java

public class PrintName {

- *public*: This access modifier means the class is accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrintName*: This is the name of the class, and it should match the filename (PrintName.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Loop Control Variable

java

int count = 1;

- *int count*: This variable keeps track of the number of times the loop has executed. It is

initialized to 1 because we want to start counting from 1.

### Step 4: Use a do-while Loop to Print the Name

java

do {

System.out.println("Your Name");

count++;

} while (count <= 10);


- *do { ... }*: Starts the do-while loop. The loop body will execute at least once before checking

the condition.

- *System.out.println("Your Name");*: Prints "Your Name" to the console.

- *count++;*: Increments the count variable by 1 after each iteration.

- *while (count <= 10);*: The loop continues as long as count is less than or equal to 10.

### Step 5: Close the Method and Class

java

}

}

- The closing curly braces } end the main method and the PrintName class.

### Complete Program

Here’s the complete Java program:

java

public class PrintName {

public static void main(String[] args) {

int count = 1;

do {

System.out.println("Your Name");

count++;

} while (count <= 10);

}

}


### Output

When you run this program, it will produce the following output:


Your Name

Your Name

Your Name

Your Name

Your Name

Your Name

Your Name

Your Name

Your Name

Your Name


Each line prints "Your Name", and this happens 10 times due to the do-while loop.

5. To print the summation of numbers

from 1 to 10 in Java.


### Step 1: Define the Class

java

public class SumFromOneToTen {

- *public*: This access modifier makes the class accessible from anywhere.

- *class*: This keyword declares a new class.

- *SumFromOneToTen*: The name of the class should match the filename

(SumFromOneToTen.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize Variables

java

int sum = 0;

int i = 1;

- *int sum*: A variable to keep track of the total sum. It is initialized to 0.

- *int i*: A variable to keep track of the current number in the range. It is initialized to 1.

### Step 4: Use a while Loop to Calculate the Sum

java

while (i <= 10) {

sum += i;

i++;


}

- *while (i <= 10) { ... }*: The loop continues as long as i is less than or equal to 10.

- *sum += i;*: Adds the value of i to sum in each iteration.

- *i++;*: Increments the value of i by 1 in each iteration.

### Step 5: Print the Result

java

System.out.println("The sum of numbers from 1 to 10 is: " + sum);

- *System.out.println*: Prints the result to the console.

### Step 6: Close the Method and Class

java

}

}

- The closing curly braces } end the main method and the SumFromOneToTen class.

### Complete Program

Here’s the complete Java program:

java

public class SumFromOneToTen {

public static void main(String[] args) {

int sum = 0;

int i = 1;

while (i <= 10) {

sum += i;

i++;

}

System.out.println("The sum of numbers from 1 to 10 is: " + sum);

}

}


### Output

When you run this program, it will produce the following output:


The sum of numbers from 1 to 10 is: 55


This output indicates that the sum of numbers from 1 to 10 is 55, which is calculated by adding

all integers from 1 through 10.

6. To display numbers from 1 to 5 using a

for loop in Java.

### Step 1: Define the Class

java

public class DisplayNumbers {

- *public*: This access modifier allows the class to be accessed from anywhere.

- *class*: This keyword declares a new class.

- *DisplayNumbers*: This is the name of the class. It should match the filename

(DisplayNumbers.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: This allows the main method to be accessed from outside the class.

- *static*: This means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: This is the entry point of the program.

- *String[] args*: This parameter is used to accept command-line arguments.

### Step 3: Use a for Loop to Display Numbers

java

for (int i = 1; i <= 5; i++) {

System.out.println(i);

}

- *for*: Starts the for loop.

- *int i = 1*: Initializes the loop control variable i to 1.

- *i <= 5*: The loop continues as long as i is less than or equal to 5.

- *i++*: Increments the value of i by 1 after each iteration.

- *System.out.println(i);*: Prints the current value of i to the console.


### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the DisplayNumbers class.

### Complete Program

Here’s the complete Java program:

java

public class DisplayNumbers {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

System.out.println(i);

}

}

}


### Output

When you run this program, it will produce the following output:


1

2

3

4

5


Each number from 1 to 5 is printed on a new line due to the System.out.println statement inside

the for loop.

7. To print a 2D matrix using nested loops

in Java.


### Example Program


We’ll use a 3x3 matrix for simplicity, but the approach is applicable to any size.

### Step 1: Define the Class

java

public class PrintMatrix {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrintMatrix*: The name of the class should match the filename (PrintMatrix.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: This allows the main method to be accessed from outside the class.

- *static*: This means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: This is the entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Matrix

java

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

- *int[][] matrix*: Declares a 2D array (matrix) of integers.

- *{ ... }*: Initializes the matrix with values in a 3x3 grid.

### Step 4: Use Nested Loops to Print the Matrix

java

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

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

}

System.out.println();

}

- *Outer for Loop*:


- *for (int i = 0; i < matrix.length; i++)*: Iterates over the rows of the matrix. matrix.length gives

the number of rows.

- *Inner for Loop*:

- *for (int j = 0; j < matrix[i].length; j++)*: Iterates over the columns of the current row.

matrix[i].length gives the number of columns in row i.

- *System.out.print(matrix[i][j] + " ");*: Prints each element followed by a space, keeping

elements in the same row on the same line.

- *After Inner Loop*:

- *System.out.println();*: Prints a newline after each row is printed to move to the next line.

### Step 5: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the PrintMatrix class.

### Complete Program

Here’s the complete Java program:

java

public class PrintMatrix {

public static void main(String[] args) {

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

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

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

}

System.out.println();

}

}

}


### Output

When you run this program, it will produce the following output:


1 2 3

4 5 6

7 8 9


*Explanation of Output:*

- Each row of the matrix is printed on a new line.

- The for loops ensure that each element is accessed and printed in the correct order, row by

row.

8. Using the break statement in a loop

allows you to exit the loop prematurely.

Here's how you can use it to print numbers

from 1 to 5:


### Example Program

We’ll use a for loop and break to print numbers from 1 to 5.

### Step 1: Define the Class

java

public class PrintNumbersWithBreak {

- *public*: This access modifier allows the class to be accessed from anywhere.

- *class*: This keyword declares a new class.

- *PrintNumbersWithBreak*: The name of the class should match the filename

(PrintNumbersWithBreak.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.


### Step 3: Use a for Loop with break

java

for (int i = 1; i <= 10; i++) {

if (i > 5) {

break;

}

System.out.println(i);

}

- *for (int i = 1; i <= 10; i++)*: Starts the for loop, initializing i to 1 and running until i is greater

than 10.

- *int i = 1*: Initializes the loop control variable i to 1.

- *i <= 10*: The loop continues as long as i is less than or equal to 10.

- *i++*: Increments i by 1 in each iteration.

- *if (i > 5)*: Checks if i is greater than 5.

- *break*: Exits the loop if i is greater than 5. This prevents printing numbers greater than 5.

- *System.out.println(i);*: Prints the value of i to the console.

### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the PrintNumbersWithBreak class.

### Complete Program

Here’s the complete Java program:

java

public class PrintNumbersWithBreak {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

if (i > 5) {

break;

}

System.out.println(i);

}

}

}


### Output

When you run this program, it will produce the following output:


1

2

3

4

5


### Explanation:

- *Loop Execution*: The for loop starts with i equal to 1 and increments i until it reaches 10.

- *Condition Check*: Inside the loop, the if statement checks if i is greater than 5. If true, break

exits the loop.

- *Printing*: Numbers from 1 to 5 are printed. When i becomes 6, the if condition i > 5 evaluates

to true, so the break statement is executed, and the loop exits.

This way, the break statement ensures that the loop terminates once i exceeds 5, effectively

limiting the output to numbers from 1 to 5.

9. The continue statement in a loop

allows you to skip the current iteration and

move to the next one. Here's how you can

use it to print numbers from 1 to 10,

skipping a specific number.

### Example Program

We’ll use a for loop and the continue statement to print numbers from 1 to 10, but we will skip

printing the number 5.

### Step 1: Define the Class

java

public class PrintNumbersWithContinue {

- *public*: This access modifier allows the class to be accessible from anywhere.


- *class*: This keyword declares a new class.

- *PrintNumbersWithContinue*: The name of the class should match the filename

(PrintNumbersWithContinue.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Use a for Loop with continue

java

for (int i = 1; i <= 10; i++) {

if (i == 5) {

continue;

}

System.out.println(i);

}

- *for (int i = 1; i <= 10; i++)*: Starts the for loop.

- *int i = 1*: Initializes the loop control variable i to 1.

- *i <= 10*: The loop continues as long as i is less than or equal to 10.

- *i++*: Increments i by 1 in each iteration.

- *if (i == 5)*: Checks if i is equal to 5.

- *continue*: Skips the rest of the loop body and moves to the next iteration if i is 5. This

means the number 5 will not be printed.

- *System.out.println(i);*: Prints the value of i to the console, except when i is 5.

### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the PrintNumbersWithContinue class.

### Complete Program

Here’s the complete Java program:


java

public class PrintNumbersWithContinue {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

if (i == 5) {

continue;

}

System.out.println(i);

}

}

}


### Output

When you run this program, it will produce the following output:


1

2

3

4

6

7

8

9

10


### Explanation:

- *Loop Execution*: The for loop starts with i equal to 1 and increments i until it reaches 10.

- *Condition Check*: Inside the loop, the if statement checks if i is equal to 5. If true, the

continue statement is executed, which skips the current iteration and moves to the next value

of i.

- *Skipping and Printing*: When i is 5, the continue statement prevents the

System.out.println(i); from executing, so 5 is not printed. For all other values of i, the

System.out.println(i); executes and prints the number.

This way, the continue statement effectively allows you to skip specific iterations in the loop,

here skipping the number 5 in the output.


10. To check if a number is even or odd

using an if statement in Java.

### Example Program

We’ll write a Java program to check whether a number is even or odd.

### Step 1: Define the Class

java

public class EvenOddCheck {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *EvenOddCheck*: The name of the class should match the filename (EvenOddCheck.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Number

java

int number = 7; // You can change this number to test different values

- *int number*: Declares and initializes the variable number to 7. You can change this value to

test different numbers.

### Step 4: Check if the Number is Even or Odd

java

if (number % 2 == 0) {

System.out.println(number + " is even.");

} else {

System.out.println(number + " is odd.");

}


- *if (number % 2 == 0)*: The if statement checks if the remainder when number is divided by 2

is 0. If true, the number is even.

- *number % 2*: Calculates the remainder of number divided by 2.

- *== 0*: Checks if the remainder is equal to 0.

- *System.out.println(number + " is even.");*: Executes if the number is even, printing that the

number is even.

- *else*: If the if condition is false, the else block executes.

- *System.out.println(number + " is odd.");*: Executes if the number is odd, printing that the

number is odd.

### Step 5: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the EvenOddCheck class.

### Complete Program

Here’s the complete Java program:

java

public class EvenOddCheck {

public static void main(String[] args) {

int number = 7; // You can change this number to test different values

if (number % 2 == 0) {

System.out.println(number + " is even.");

} else {

System.out.println(number + " is odd.");

}

}

}


### Output

When you run this program with the number 7, it will produce the following output:


7 is odd.


If you change the number to 8, the output will be:


8 is even.


### Explanation:

- *Calculation*: The expression number % 2 calculates the remainder when number is divided by

2.

- *Even Check*: If the remainder is 0, the number is evenly divisible by 2 and hence even.

- *Odd Check*: If the remainder is not 0, the number is odd.

This program helps determine if a given number is even or odd using basic arithmetic and

conditional statements.

11. To check a student's grade using if-else

statements in Java.


### Example Program

Assume that the grading scale is as follows:

- A: 90 to 100

- B: 80 to 89

- C: 70 to 79

- D: 60 to 69

- F: Below 60

### Step 1: Define the Class

java

public class GradeChecker {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *GradeChecker*: The name of the class should match the filename (GradeChecker.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.


- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Score

java

int score = 85; // You can change this score to test different values

- *int score*: Declares and initializes the variable score to 85. You can modify this value to test

different scores.

### Step 4: Check the Grade Using if-else Statements

java

if (score >= 90) {

System.out.println("Grade: A");

} else if (score >= 80) {

System.out.println("Grade: B");

} else if (score >= 70) {

System.out.println("Grade: C");

} else if (score >= 60) {

System.out.println("Grade: D");

} else {

System.out.println("Grade: F");

}

- *if (score >= 90)*: Checks if the score is 90 or above. If true, prints "Grade: A".

- *else if (score >= 80)*: Checks if the score is between 80 and 89. If true, prints "Grade: B".

- *else if (score >= 70)*: Checks if the score is between 70 and 79. If true, prints "Grade: C".

- *else if (score >= 60)*: Checks if the score is between 60 and 69. If true, prints "Grade: D".

- *else*: If none of the above conditions are true, this block executes, printing "Grade: F".

### Step 5: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the GradeChecker class.

### Complete Program

Here’s the complete Java program:

java


public class GradeChecker {

public static void main(String[] args) {

int score = 85; // You can change this score to test different values

if (score >= 90) {

System.out.println("Grade: A");

} else if (score >= 80) {

System.out.println("Grade: B");

} else if (score >= 70) {

System.out.println("Grade: C");

} else if (score >= 60) {

System.out.println("Grade: D");

} else {

System.out.println("Grade: F");

}

}

}


### Output

When you run this program with the score 85, it will produce the following output:


Grade: B


If you change the score to 72, the output will be:


Grade: C


### Explanation:

- *Condition Checking*: The if-else statements check the value of score against the defined

ranges.

- *Grade Assignment*: Depending on which condition is met, the appropriate grade is printed.

This program evaluates the student's score and determines the corresponding grade using a

series of if-else statements.


12. Printing the Fibonacci series involves

generating a sequence of numbers where

each number is the sum of the two

preceding ones, starting from 0 and 1

### Example Program

We’ll print the first n Fibonacci numbers. For simplicity, let's print the first 10 numbers in the

series.

### Step 1: Define the Class

java

public class FibonacciSeries {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *FibonacciSeries*: The name of the class should match the filename (FibonacciSeries.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize Variables

java

int n = 10; // Number of Fibonacci numbers to print

int first = 0, second = 1;

- *int n*: Declares and initializes n to 10, which represents the number of Fibonacci numbers to

print.

- *int first*: Declares and initializes the first Fibonacci number (0).

- *int second*: Declares and initializes the second Fibonacci number (1).


### Step 4: Print the First Two Numbers

java

System.out.print(first + " ");

System.out.print(second + " ");

- *System.out.print(first + " ");*: Prints the first Fibonacci number followed by a space.

- *System.out.print(second + " ");*: Prints the second Fibonacci number followed by a space.

### Step 5: Use a for Loop to Generate and Print Remaining Numbers

java

for (int i = 3; i <= n; i++) {

int next = first + second;

System.out.print(next + " ");

first = second;

second = next;

}

- *for (int i = 3; i <= n; i++)*: Starts the loop from 3 and continues until n.

- *int next = first + second;*: Calculates the next Fibonacci number by summing the previous

two numbers.

- *System.out.print(next + " ");*: Prints the next Fibonacci number followed by a space.

- *first = second;*: Updates first to be the old second.

- *second = next;*: Updates second to be the newly calculated next.

### Step 6: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the FibonacciSeries class.

### Complete Program

Here’s the complete Java program:

java

public class FibonacciSeries {

public static void main(String[] args) {

int n = 10; // Number of Fibonacci numbers to print

int first = 0, second = 1;

System.out.print(first + " ");

System.out.print(second + " ");


for (int i = 3; i <= n; i++) {

int next = first + second;

System.out.print(next + " ");

first = second;

second = next;

}

}

}


### Output

When you run this program, it will produce the following output:


0 1 1 2 3 5 8 13 21 34


### Explanation:

- *Initialization*: first and second are initialized to the first two numbers of the Fibonacci

sequence.

- *Printing Initial Numbers*: The first two Fibonacci numbers (0 and 1) are printed separately.

- *Loop Execution*: The for loop calculates each subsequent Fibonacci number by adding the

previous two numbers, prints the result, and updates the previous values.

- *Result*: The loop continues until the required number of Fibonacci numbers are printed.

This program efficiently prints the Fibonacci sequence up to the n-th number using basic

iteration and arithmetic operations.

13. To input values into an array and then

display them in Java

### Example Program

We'll create a program that inputs values into an array of integers and then prints these values.

For simplicity, let's assume the array size is 5.

### Step 1: Define the Class

java

public class ArrayInputOutput {


- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *ArrayInputOutput*: The name of the class should match the filename

(ArrayInputOutput.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Import the Scanner Class

java

import java.util.Scanner;

- *import java.util.Scanner;*: Imports the Scanner class, which is used for reading input from the

user.

### Step 4: Initialize the Scanner and Array

java

Scanner scanner = new Scanner(System.in);

int size = 5; // Define the size of the array

int[] numbers = new int[size];

- *Scanner scanner = new Scanner(System.in);*: Creates a Scanner object to read input from the

console.

- *int size = 5;*: Defines the size of the array (5 in this case).

- *int[] numbers = new int[size];*: Declares and initializes an array of integers with the specified

size.

### Step 5: Input Values into the Array

java

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

for (int i = 0; i < size; i++) {

numbers[i] = scanner.nextInt();

}


- *System.out.println("Enter " + size + " integers:");*: Prompts the user to enter the values.

- *for (int i = 0; i < size; i++)*: Loops through the array indices.

- *numbers[i] = scanner.nextInt();*: Reads an integer from the user and stores it in the array.

### Step 6: Display the Array Elements

java

System.out.println("You entered:");

for (int i = 0; i < size; i++) {

System.out.println(numbers[i]);

}

- *System.out.println("You entered:");*: Prints a message indicating that the array elements will

be displayed.

- *for (int i = 0; i < size; i++)*: Loops through the array indices.

- *System.out.println(numbers[i]);*: Prints each element of the array.

### Step 7: Close the Scanner

java

scanner.close();

- *scanner.close();*: Closes the Scanner object to free up system resources.

### Step 8: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the ArrayInputOutput class.

### Complete Program

Here’s the complete Java program:

java

import java.util.Scanner;

public class ArrayInputOutput {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int size = 5; // Define the size of the array

int[] numbers = new int[size];

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


for (int i = 0; i < size; i++) {

numbers[i] = scanner.nextInt();

}

System.out.println("You entered:");

for (int i = 0; i < size; i++) {

System.out.println(numbers[i]);

}

scanner.close();

}

}


### Output

Suppose the user inputs the numbers 10, 20, 30, 40, and 50. The output will be:


Enter 5 integers:

10

20

30

40

50

You entered:

10

20

30

40

50


### Explanation:

- *Input*: The program prompts the user to enter a series of integers. Each integer is read from

the console and stored in the array.

- *Display*: After all integers are entered, the program prints each integer from the array,

displaying the values that the user entered.

This program demonstrates basic array handling and user input in Java, showing how to store

and display values efficiently.


14. To read an array of 10 integers and find

the sum of all numbers in Java.


### Example Program

We’ll create a program that reads 10 integers from the user, stores them in an array, and then

calculates and prints the sum of these integers.

### Step 1: Define the Class

java

public class SumArray {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *SumArray*: The name of the class should match the filename (SumArray.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Import the Scanner Class

java

import java.util.Scanner;

- *import java.util.Scanner;*: Imports the Scanner class, which is used for reading input from the

user.

### Step 4: Initialize the Scanner and Array

java

Scanner scanner = new Scanner(System.in);

int size = 10; // Define the size of the array

int[] numbers = new int[size];


- *Scanner scanner = new Scanner(System.in);*: Creates a Scanner object to read input from the

console.

- *int size = 10;*: Defines the size of the array as 10.

- *int[] numbers = new int[size];*: Declares and initializes an array of integers with the specified

size.

### Step 5: Input Values into the Array

java

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

for (int i = 0; i < size; i++) {

numbers[i] = scanner.nextInt();

}

- *System.out.println("Enter " + size + " integers:");*: Prompts the user to enter 10 integers.

- *for (int i = 0; i < size; i++)*: Loops through the array indices.

- *numbers[i] = scanner.nextInt();*: Reads an integer from the user and stores it in the array.

### Step 6: Calculate the Sum of the Array Elements

java

int sum = 0;

for (int i = 0; i < size; i++) {

sum += numbers[i];

}

- *int sum = 0;*: Initializes a variable sum to 0 to hold the total sum.

- *for (int i = 0; i < size; i++)*: Loops through the array indices.

- *sum += numbers[i];*: Adds each element of the array to sum.

### Step 7: Display the Sum

java

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

- *System.out.println("Sum of all numbers: " + sum);*: Prints the total sum of the array

elements.

### Step 8: Close the Scanner

java

scanner.close();

- *scanner.close();*: Closes the Scanner object to free up system resources.

### Step 9: Close the Method and Class


java

}

}

- These closing curly braces } end the main method and the SumArray class.

### Complete Program

Here’s the complete Java program:

java

import java.util.Scanner;

public class SumArray {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int size = 10; // Define the size of the array

int[] numbers = new int[size];

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

for (int i = 0; i < size; i++) {

numbers[i] = scanner.nextInt();

}

int sum = 0;

for (int i = 0; i < size; i++) {

sum += numbers[i];

}

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

scanner.close();

}

}


### Output

When you run this program and enter the integers 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, the output will

be:


Enter 10 integers:

1


2

3

4

5

6

7

8

9

10

Sum of all numbers: 55


### Explanation:

- *Input*: The user is prompted to enter 10 integers, which are stored in the numbers array.

- *Summation*: The program calculates the sum of all elements in the array using a for loop.

- *Output*: The total sum is printed to the console.

This program demonstrates how to handle user input, process array elements, and compute a

sum in Java.

15. Writing a two-dimensional array

program in Java involves creating a matrix

and performing operations like printing it.

Let’s go through a step-by-step example

where we initialize a 2D array, populate it

with values, and then print the matrix.

### Example Program

We’ll create a program to handle a 2D array (matrix) of size 3x3, populate it with some values,

and then print the matrix.

### Step 1: Define the Class

java

public class MatrixExample {


- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *MatrixExample*: The name of the class should match the filename (MatrixExample.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the 2D Array

java

int rows = 3; // Number of rows

int cols = 3; // Number of columns

int[][] matrix = new int[rows][cols];

- *int rows = 3;*: Defines the number of rows in the matrix.

- *int cols = 3;*: Defines the number of columns in the matrix.

- *int[][] matrix = new int[rows][cols];*: Declares and initializes a 2D array with 3 rows and 3

columns.

### Step 4: Populate the 2D Array

java

int value = 1; // Starting value to populate the matrix

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

matrix[i][j] = value++;

}

}

- *int value = 1;*: Initializes a starting value for populating the matrix.

- *for (int i = 0; i < rows; i++)*: Loops through each row.

- *for (int j = 0; j < cols; j++)*: Loops through each column within the current row.

- *matrix[i][j] = value++;*: Assigns the current value to the matrix element and increments the

value.

### Step 5: Print the 2D Array

java


System.out.println("Matrix:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

System.out.print(matrix[i][j] + " ");

}

System.out.println(); // Move to the next line after printing all columns of a row

}

- *System.out.println("Matrix:");*: Prints a header for the matrix.

- *for (int i = 0; i < rows; i++)*: Loops through each row.

- *for (int j = 0; j < cols; j++)*: Loops through each column within the current row.

- *System.out.print(matrix[i][j] + " ");*: Prints each element of the matrix followed by a space.

- *System.out.println();*: Moves to the next line after printing all columns of a row.

### Step 6: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the MatrixExample class.

### Complete Program

Here’s the complete Java program:

java

public class MatrixExample {

public static void main(String[] args) {

int rows = 3; // Number of rows

int cols = 3; // Number of columns

int[][] matrix = new int[rows][cols];

int value = 1; // Starting value to populate the matrix

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

matrix[i][j] = value++;

}

}

System.out.println("Matrix:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

System.out.print(matrix[i][j] + " ");


}

System.out.println(); // Move to the next line after printing all columns of a row

}

}

}


### Output

When you run this program, the output will be:


Matrix:

1 2 3

4 5 6

7 8 9


### Explanation:

- *Initialization*: The matrix is declared with 3 rows and 3 columns, and initially filled with

default values (0s).

- *Populating*: The nested for loops populate the matrix with values from 1 to 9.

- *Printing*: Another set of nested for loops prints each element in a formatted way to display

the matrix.

This program demonstrates basic operations with a 2D array, including initialization, population,

and display.

16. To find the length of a string in Java, you

can use the length() method of the String

class.


### Example Program

We will create a program that finds and displays the length of a given string.

### Step 1: Define the Class

java

public class StringLengthExample {


- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *StringLengthExample*: The name of the class should match the filename

(StringLengthExample.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the String

java

String str = "Hello, world!";

- *String str = "Hello, world!";*: Declares and initializes a string variable with the value "Hello,

world!".

### Step 4: Find the Length of the String

java

int length = str.length();

- *int length*: Declares a variable to hold the length of the string.

- *str.length()*: Calls the length() method of the String class, which returns the number of

characters in the string.

### Step 5: Display the Length

java

System.out.println("The length of the string is: " + length);

- *System.out.println("The length of the string is: " + length);*: Prints the length of the string to

the console.

### Step 6: Close the Method and Class

java

}

}


- These closing curly braces } end the main method and the StringLengthExample class.

### Complete Program

Here’s the complete Java program:

java

public class StringLengthExample {

public static void main(String[] args) {

String str = "Hello, world!";

int length = str.length();

System.out.println("The length of the string is: " + length);

}

}


### Output

When you run this program, the output will be:


The length of the string is: 13


### Explanation:

- *Initialization*: The string str is initialized with "Hello, world!".

- *Finding Length*: The length() method calculates the number of characters in the string, which

is 13 in this case.

- *Display*: The program prints the length of the string.

This program effectively demonstrates how to find and display the length of a string using Java’s

built-in methods.

17. To compare two strings in Java, you can

use several methods provided by the String

class. The most common methods for


comparison are equals(),

equalsIgnoreCase(), and compareTo().

### Example Program

We’ll write a program to compare two strings using equals(), equalsIgnoreCase(), and

compareTo() methods.

### Step 1: Define the Class

java

public class StringComparisonExample {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *StringComparisonExample*: The name of the class should match the filename

(StringComparisonExample.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Strings

java

String str1 = "Hello";

String str2 = "hello";

- *String str1 = "Hello";*: Declares and initializes the first string.

- *String str2 = "hello";*: Declares and initializes the second string.

### Step 4: Compare Strings Using equals()

java

boolean isEqual = str1.equals(str2);

System.out.println("Using equals(): " + isEqual);


- *boolean isEqual = str1.equals(str2);*: Compares str1 and str2 for equality, considering case

sensitivity.

- *System.out.println("Using equals(): " + isEqual);*: Prints the result of the comparison.

### Step 5: Compare Strings Using equalsIgnoreCase()

java

boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase);

- *boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);*: Compares str1 and str2 for

equality, ignoring case.

- *System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase);*: Prints the result of

the comparison.

### Step 6: Compare Strings Using compareTo()

java

int comparisonResult = str1.compareTo(str2);

System.out.println("Using compareTo(): " + comparisonResult);

- *int comparisonResult = str1.compareTo(str2);*: Compares str1 and str2 lexicographically. It

returns:

- 0 if the strings are equal,

- A negative number if str1 is lexicographically less than str2,

- A positive number if str1 is lexicographically greater than str2.

- *System.out.println("Using compareTo(): " + comparisonResult);*: Prints the result of the

comparison.

### Step 7: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the StringComparisonExample class.

### Complete Program

Here’s the complete Java program:

java

public class StringComparisonExample {

public static void main(String[] args) {

String str1 = "Hello";

String str2 = "hello";


// Compare using equals()

boolean isEqual = str1.equals(str2);

System.out.println("Using equals(): " + isEqual);

// Compare using equalsIgnoreCase()

boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase);

// Compare using compareTo()

int comparisonResult = str1.compareTo(str2);

System.out.println("Using compareTo(): " + comparisonResult);

}

}


### Output

When you run this program, the output will be:


Using equals(): false

Using equalsIgnoreCase(): true

Using compareTo(): -32


### Explanation:

- *equals()*: Compares str1 and str2 for equality, considering case sensitivity. Since "Hello" and

"hello" differ in case, the result is false.

- *equalsIgnoreCase()*: Compares str1 and str2 for equality, ignoring case. Since "Hello" and

"hello" are considered equal if case is ignored, the result is true.

- *compareTo()*: Compares str1 with str2 lexicographically. The result is -32 because in

Unicode, the uppercase letters have lower values than lowercase letters, and "Hello" is

considered less than "hello".

This program effectively demonstrates how to compare strings in Java using different methods

provided by the String class.

18. Step-by-step Java program to illustrate

call by value with primitive data types.


In Java, "call by value" means that a method receives a copy of the argument's value. Changes

made to the parameter inside the method do not affect the original argument. Java always uses

call by value, even for objects. For objects, the value passed is the reference to the object, but

the reference itself is passed by value, so modifications to the object’s properties within the

method will reflect in the original object, but reassigning the reference does not affect the

original reference.

Let’s write a step-by-step Java program to illustrate call by value with primitive data types.

### Example Program

We will create a program that demonstrates call by value using an int (a primitive type) and a

method that tries to modify the value.

### Step 1: Define the Class

java

public class CallByValueExample {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *CallByValueExample*: The name of the class should match the filename

(CallByValueExample.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Variable and Call the Method

java

int number = 10; // Original value

System.out.println("Before calling the method: " + number);

modifyValue(number); // Call the method

System.out.println("After calling the method: " + number);

- *int number = 10;*: Declares and initializes a variable number.


- *System.out.println("Before calling the method: " + number);*: Prints the value of number

before calling the method.

- *modifyValue(number);*: Calls the method modifyValue with number as an argument.

- *System.out.println("After calling the method: " + number);*: Prints the value of number after

calling the method.

### Step 4: Define the Method to Modify the Value

java

public static void modifyValue(int num) {

num = 20; // Modify the copy of the variable

System.out.println("Inside modifyValue method: " + num);

}

- *public static void modifyValue(int num)*: Declares a method named modifyValue that takes

an int parameter.

- *num = 20;*: Modifies the local copy of the variable.

- *System.out.println("Inside modifyValue method: " + num);*: Prints the modified value inside

the method.

### Step 5: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the CallByValueExample class.

### Complete Program

Here’s the complete Java program:

java

public class CallByValueExample {

public static void main(String[] args) {

int number = 10; // Original value

System.out.println("Before calling the method: " + number);

modifyValue(number); // Call the method

System.out.println("After calling the method: " + number);

}

public static void modifyValue(int num) {

num = 20; // Modify the copy of the variable

System.out.println("Inside modifyValue method: " + num);


}

}


### Output

When you run this program, the output will be:


Before calling the method: 10

Inside modifyValue method: 20

After calling the method: 10


### Explanation:

- *Before Method Call*: The value of number is 10.

- *Inside the Method*: The modifyValue method is called, where the local copy of the variable

num is modified to 20. This change is local to the method and does not affect the original

variable.

- *After Method Call*: The value of number remains 10 because the original variable is not

affected by changes made to the local copy inside the method.

This program demonstrates that in Java, when you pass a primitive data type to a method, you

are passing a copy of the value, not the actual variable. Changes to the copy do not impact the

original value.

19. A step-by-step Java program to

illustrate how to modify an object's fields

using "call by reference":

In Java, all method arguments are passed by value. For objects, this means that the value passed

is the reference to the object, but the reference itself is passed by value. Therefore, you can

modify the object's fields through the reference, but you cannot reassign the reference to point

to a different object in the calling method. This behavior is sometimes referred to as "call by

reference" in the context of object references.

Here’s a step-by-step Java program to illustrate how to modify an object's fields using "call by

reference":


### Example Program

We will create a program to demonstrate modifying an object's field using methods. We will

define a class Person with a field name, and show how to modify this field using a method.

### Step 1: Define the Person Class

java

public class Person {

String name;

public Person(String name) {

this.name = name;

}

}

- *public class Person*: Declares the Person class.

- *String name;*: Defines a field to hold the name of the person.

- *public Person(String name)*: A constructor to initialize the name field.

### Step 2: Define the Main Class

java

public class CallByReferenceExample {

public static void main(String[] args) {

Person person = new Person("Alice"); // Create a new Person object

System.out.println("Before calling the method: " + person.name);

modifyPerson(person); // Call the method with the Person object

System.out.println("After calling the method: " + person.name);

}

- *public class CallByReferenceExample*: Declares the main class.

- *public static void main(String[] args)*: The entry point of the program.

- *Person person = new Person("Alice");*: Creates a new Person object with the name "Alice".

- *System.out.println("Before calling the method: " + person.name);*: Prints the name before

calling the method.

- *modifyPerson(person);*: Calls the modifyPerson method with the person object.

- *System.out.println("After calling the method: " + person.name);*: Prints the name after

calling the method.

### Step 3: Define the Method to Modify the Object

java

public static void modifyPerson(Person p) {

p.name = "Bob"; // Modify the object's name field


System.out.println("Inside modifyPerson method: " + p.name);

}

- *public static void modifyPerson(Person p)*: Declares a method to modify a Person object.

- *p.name = "Bob";*: Changes the name field of the Person object.

- *System.out.println("Inside modifyPerson method: " + p.name);*: Prints the modified name

inside the method.

### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the CallByReferenceExample class.

### Complete Program

Here’s the complete Java program:

java

public class Person {

String name;

public Person(String name) {

this.name = name;

}

}

public class CallByReferenceExample {

public static void main(String[] args) {

Person person = new Person("Alice"); // Create a new Person object

System.out.println("Before calling the method: " + person.name);

modifyPerson(person); // Call the method with the Person object

System.out.println("After calling the method: " + person.name);

}

public static void modifyPerson(Person p) {

p.name = "Bob"; // Modify the object's name field

System.out.println("Inside modifyPerson method: " + p.name);

}

}


### Output

When you run this program, the output will be:


Before calling the method: Alice

Inside modifyPerson method: Bob

After calling the method: Bob


### Explanation:

- *Before Method Call*: The person object’s name field is "Alice".

- *Inside the Method*: The modifyPerson method is called, where the name field of the person

object is changed to "Bob". This modification affects the original object.

- *After Method Call*: The person object’s name field is now "Bob", reflecting the change made

inside the modifyPerson method.

This example illustrates how changes to the object's fields inside a method are reflected outside

the method because the reference to the object was passed, though the reference itself is

passed by value.

20. A program that computes the factorial

of a number using a recursive method.

To compute the factorial of a number using recursion in Java, we define a method that calls

itself with a decremented value until it reaches a base case. Here’s a step-by-step explanation of

a Java program that calculates the factorial of a number using recursion:

### Example Program

We will create a program that computes the factorial of a number using a recursive method.

### Step 1: Define the Class

java

public class FactorialExample {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *FactorialExample*: The name of the class should match the filename (FactorialExample.java).


### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Get Input and Call Recursive Method

java

int number = 5; // Example number to compute factorial

int result = factorial(number); // Call the recursive method

System.out.println("Factorial of " + number + " is: " + result);

- *int number = 5;*: Defines the number for which the factorial will be computed.

- *int result = factorial(number);*: Calls the factorial method and stores the result.

- *System.out.println("Factorial of " + number + " is: " + result);*: Prints the computed factorial.

### Step 4: Define the Recursive Method

java

public static int factorial(int n) {

if (n == 0) { // Base case: factorial of 0 is 1

return 1;

} else { // Recursive case

return n * factorial(n - 1);

}

}

- *public static int factorial(int n)*: Declares a method to compute factorial, which takes an

integer n and returns an integer.

- *if (n == 0)*: Checks the base case where factorial of 0 is 1.

- *return 1;*: Returns 1 if the base case is met.

- *return n * factorial(n - 1);*: Recursively calls factorial with n - 1 and multiplies the result by n.

### Step 5: Close the Method and Class

java

}

}


- These closing curly braces } end the main method and the FactorialExample class.

### Complete Program

Here’s the complete Java program:

java

public class FactorialExample {

public static void main(String[] args) {

int number = 5; // Example number to compute factorial

int result = factorial(number); // Call the recursive method

System.out.println("Factorial of " + number + " is: " + result);

}

public static int factorial(int n) {

if (n == 0) { // Base case: factorial of 0 is 1

return 1;

} else { // Recursive case

return n * factorial(n - 1);

}

}

}


### Output

When you run this program, the output will be:


Factorial of 5 is: 120


### Explanation:

- *Base Case*: When n is 0, the method returns 1 as the factorial of 0 is defined as 1.

- *Recursive Case*: For any n > 0, the method calls itself with n - 1 and multiplies the result by n.

This process continues until n becomes 0.

- *Calculation*: For number = 5, the calculations are as follows:

- factorial(5) returns 5 * factorial(4)

- factorial(4) returns 4 * factorial(3)

- factorial(3) returns 3 * factorial(2)

- factorial(2) returns 2 * factorial(1)

- factorial(1) returns 1 * factorial(0)

- factorial(0) returns 1

- Combining these results: 5 * 4 * 3 * 2 * 1 = 120


This program effectively demonstrates how recursion can be used to solve problems like

calculating the factorial of a number.

21. To print numbers in ascending order in

Java, you can use a simple for loop. The

following is a step-by-step explanation of

how to write a Java program to print

numbers from 1 to n in ascending order:

### Example Program

This program will print numbers from 1 to a given number n.

### Step 1: Define the Class

java

public class PrintAscendingOrder {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrintAscendingOrder*: The name of the class should match the filename

(PrintAscendingOrder.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Variable and Print Numbers

java

int n = 10; // Example number to print numbers up to


for (int i = 1; i <= n; i++) {

System.out.print(i + " ");

}

}

}

- *int n = 10;*: Defines the maximum number to print. You can change this value to print up to a

different number.

- *for (int i = 1; i <= n; i++)*: A for loop that starts with i at 1 and increments it until it is greater

than n.

- *int i = 1*: Initialization, sets i to 1.

- *i <= n*: Loop continuation condition, the loop runs as long as i is less than or equal to n.

- *i++*: Increment, increases i by 1 after each iteration.

- *System.out.print(i + " ");*: Prints the current value of i followed by a space. This keeps the

numbers on the same line.

### Complete Program

Here’s the complete Java program:

java

public class PrintAscendingOrder {

public static void main(String[] args) {

int n = 10; // Example number to print numbers up to

for (int i = 1; i <= n; i++) {

System.out.print(i + " ");

}

}

}


### Output

When you run this program, the output will be:


1 2 3 4 5 6 7 8 9 10


### Explanation:

- *Initialization*: The loop starts with i equal to 1.


- *Condition Check*: The loop continues as long as i is less than or equal to n (which is 10 in this

example).

- *Increment*: After each iteration, i is incremented by 1.

- *Print Statement*: Each value of i is printed on the same line with a space in between.

This program demonstrates a basic loop in Java to print a sequence of numbers in ascending

order. You can modify the value of n to print numbers up to any desired limit.

22. To print numbers in an array in

descending order in Java.

1. Define an array with some values.*

2. *Sort the array in descending order.*

3. *Print the sorted array.*

Here’s a step-by-step explanation of a Java program that performs these tasks:

### Example Program

We will create a program that initializes an array with some values, sorts it in descending order,

and then prints the sorted array.

### Step 1: Define the Class

java

public class PrintDescendingOrder {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrintDescendingOrder*: The name of the class should match the filename

(PrintDescendingOrder.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.


- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Array

java

int[] numbers = {5, 2, 8, 1, 4}; // Example array

- *int[] numbers = {5, 2, 8, 1, 4};*: Declares and initializes an array of integers with some values.

### Step 4: Sort the Array in Descending Order

java

java.util.Arrays.sort(numbers); // Sort in ascending order

System.out.println("Array in descending order:");

for (int i = numbers.length - 1; i >= 0; i--) {

System.out.print(numbers[i] + " ");

}

- *java.util.Arrays.sort(numbers);*: Sorts the array numbers in ascending order using the built-in

sort method.

- *System.out.println("Array in descending order:");*: Prints a header for clarity.

- *for (int i = numbers.length - 1; i >= 0; i--)*: A for loop that starts from the last element of the

sorted array and iterates backwards.

- *int i = numbers.length - 1*: Initializes i to the last index of the array.

- *i >= 0*: Loop continues as long as i is non-negative.

- *i--*: Decrements i by 1 after each iteration.

- *System.out.print(numbers[i] + " ");*: Prints each element in the array from last to first.

### Step 5: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the PrintDescendingOrder class.

### Complete Program

Here’s the complete Java program:

java

public class PrintDescendingOrder {

public static void main(String[] args) {

int[] numbers = {5, 2, 8, 1, 4}; // Example array


java.util.Arrays.sort(numbers); // Sort in ascending order

System.out.println("Array in descending order:");

for (int i = numbers.length - 1; i >= 0; i--) {

System.out.print(numbers[i] + " ");

}

}

}


### Output

When you run this program, the output will be:


Array in descending order:

8 5 4 2 1


### Explanation:

- *Initialization*: The array numbers is initialized with values {5, 2, 8, 1, 4}.

- *Sorting*: The array is sorted in ascending order using Arrays.sort().

- *Descending Order Print*: The for loop iterates from the last element to the first element of

the sorted array, printing the elements in descending order.

This program effectively demonstrates how to sort an array in ascending order and then print it

in descending order. The sorting is done using Java's built-in Arrays.sort() method, and the

descending order is achieved by iterating the sorted array in reverse.

23. To convert temperature from

Fahrenheit to Celsius in Java.


1. *Define the class.*

2. *Define the main method.*

3. *Initialize the Fahrenheit temperature value.*

4. *Perform the conversion using the formula.*

5. *Print the result.*

### Example Program


This program will take a temperature value in Fahrenheit, convert it to Celsius, and print the

result.

### Step 1: Define the Class

java

public class FahrenheitToCelsius {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *FahrenheitToCelsius*: The name of the class should match the filename

(FahrenheitToCelsius.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Fahrenheit Temperature Value

java

double fahrenheit = 98.6; // Example Fahrenheit temperature

- *double fahrenheit = 98.6;*: Initializes the temperature in Fahrenheit. You can change this

value to convert different temperatures.

### Step 4: Perform the Conversion

java

double celsius = (fahrenheit - 32) * 5 / 9; // Convert to Celsius

- *double celsius = (fahrenheit - 32) * 5 / 9;*: Uses the formula for conversion from Fahrenheit

to Celsius:

- *Formula*: \( \text{Celsius} = (\text{Fahrenheit} - 32) \times \frac{5}{9} \)

### Step 5: Print the Result

java

System.out.println(fahrenheit + " Fahrenheit is equal to " + celsius + " Celsius.");

}

}


- *System.out.println(fahrenheit + " Fahrenheit is equal to " + celsius + " Celsius.");*: Prints the

result, showing both the original Fahrenheit value and the converted Celsius value.

### Complete Program

Here’s the complete Java program:

java

public class FahrenheitToCelsius {

public static void main(String[] args) {

double fahrenheit = 98.6; // Example Fahrenheit temperature

// Convert to Celsius

double celsius = (fahrenheit - 32) * 5 / 9;

// Print the result

System.out.println(fahrenheit + " Fahrenheit is equal to " + celsius + " Celsius.");

}

}


### Output

When you run this program, the output will be:


98.6 Fahrenheit is equal to 37.0 Celsius.


### Explanation:

- *Initialization*: The fahrenheit variable is set to 98.6.

- *Conversion*: The formula \((\text{Fahrenheit} - 32) \times \frac{5}{9}\) is used to convert

Fahrenheit to Celsius. For 98.6 Fahrenheit, this calculation results in 37.0 Celsius.

- *Printing*: The result is displayed, showing the conversion from Fahrenheit to Celsius.

This program effectively demonstrates how to perform a basic temperature conversion using

Java.

24. To show the factors of a negative

number in Java, you need to handle the


negative sign and find factors as if the

number were positive. Factors are defined

for positive numbers, so you will work with

the absolute value of the negative number.

Here’s a step-by-step explanation of a Java program that finds and prints the factors of a

negative number:

### Example Program

This program will take a negative number, compute its factors by treating it as positive, and then

print the results.

### Step 1: Define the Class

java

public class NegativeNumberFactors {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *NegativeNumberFactors*: The name of the class should match the filename

(NegativeNumberFactors.java).

### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

### Step 3: Initialize the Negative Number and Compute Factors

java

int number = -12; // Example negative number

int absNumber = Math.abs(number); // Get the absolute value


System.out.println("Factors of " + number + " are:");

for (int i = 1; i <= absNumber; i++) {

if (absNumber % i == 0) {

System.out.print(i + " ");

}

}

}

}

- *int number = -12;*: Initializes the negative number.

- *int absNumber = Math.abs(number);*: Computes the absolute value of the negative number

using Math.abs(). This is necessary because factors are defined for positive integers.

- *System.out.println("Factors of " + number + " are:");*: Prints a header indicating that factors

of the number will follow.

- *for (int i = 1; i <= absNumber; i++)*: A for loop that iterates from 1 to absNumber (the positive

equivalent).

- *int i = 1*: Initializes the loop variable i to 1.

- *i <= absNumber*: The loop runs as long as i is less than or equal to absNumber.

- *i++*: Increments i by 1 after each iteration.

- *if (absNumber % i == 0)*: Checks if i is a factor of absNumber by verifying if the remainder of

the division is 0.

- *System.out.print(i + " ");*: Prints each factor followed by a space.

### Step 4: Close the Method and Class

java

}

}

- These closing curly braces } end the main method and the NegativeNumberFactors class.

### Complete Program

Here’s the complete Java program:

java

public class NegativeNumberFactors {

public static void main(String[] args) {

int number = -12; // Example negative number

int absNumber = Math.abs(number); // Get the absolute value

System.out.println("Factors of " + number + " are:");

for (int i = 1; i <= absNumber; i++) {

if (absNumber % i == 0) {


System.out.print(i + " ");

}

}

}

}


### Output

When you run this program, the output will be:


Factors of -12 are:

1 2 3 4 6 12


### Explanation:

- *Initialization*: The number variable is set to -12.

- *Absolute Value*: The absolute value of -12 is 12.

- *Factor Computation*: The loop checks all integers from 1 to 12 to see if they are factors of 12

(the absolute value). The factors are 1, 2, 3, 4, 6, 12.

- *Printing*: Each factor is printed in ascending order.

This program demonstrates how to compute and display the factors of a negative number by

working with its absolute value.

25. To swap two numbers in Java, you can

use either a temporary variable or

arithmetic operations. I'll explain both

methods step-by-step.

### Method 1: Swapping Using a Temporary Variable

#### Step 1: Define the Class

java

public class SwapNumbers {

- *public*: This access modifier allows the class to be accessible from anywhere.


- *class*: This keyword declares a new class.

- *SwapNumbers*: The name of the class should match the filename (SwapNumbers.java).

#### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

#### Step 3: Initialize the Numbers

java

int a = 5; // First number

int b = 10; // Second number

int temp; // Temporary variable for swapping

- *int a = 5;*: Initializes the first number.

- *int b = 10;*: Initializes the second number.

- *int temp;*: Declares a temporary variable to assist with the swap.

#### Step 4: Swap the Numbers Using the Temporary Variable

java

// Print original values

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

// Swapping logic

temp = a; // Store value of 'a' in 'temp'

a = b; // Assign value of 'b' to 'a'

b = temp; // Assign value of 'temp' (original 'a') to 'b'

// Print swapped values

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

}

}

- *System.out.println("Before swapping: a = " + a + ", b = " + b);*: Prints the values before

swapping.

- *temp = a;*: Stores the value of a in temp.

- *a = b;*: Assigns the value of b to a.


- *b = temp;*: Assigns the value of temp (which is the original value of a) to b.

- *System.out.println("After swapping: a = " + a + ", b = " + b);*: Prints the values after swapping.

#### Complete Program

Here’s the complete Java program using a temporary variable:

java

public class SwapNumbers {

public static void main(String[] args) {

int a = 5; // First number

int b = 10; // Second number

int temp; // Temporary variable for swapping

// Print original values

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

// Swapping logic

temp = a; // Store value of 'a' in 'temp'

a = b; // Assign value of 'b' to 'a'

b = temp; // Assign value of 'temp' (original 'a') to 'b'

// Print swapped values

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

}

}


#### Output

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5


### Method 2: Swapping Without Using a Temporary Variable (Using Arithmetic Operations)

#### Step 1: Define the Class

java

public class SwapNumbersArithmetic {


#### Step 2: Define the Main Method

java


public static void main(String[] args) {


#### Step 3: Initialize the Numbers

java

int a = 5; // First number

int b = 10; // Second number


#### Step 4: Swap the Numbers Using Arithmetic Operations

java

// Print original values

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

// Swapping logic using arithmetic operations

a = a + b; // Add 'a' and 'b' and store in 'a'

b = a - b; // Subtract new 'b' from 'a' to get original 'a'

a = a - b; // Subtract new 'b' from new 'a' to get original 'b'

// Print swapped values

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

}

}


#### Complete Program

Here’s the complete Java program using arithmetic operations:

java

public class SwapNumbersArithmetic {

public static void main(String[] args) {

int a = 5; // First number

int b = 10; // Second number

// Print original values

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

// Swapping logic using arithmetic operations

a = a + b; // Add 'a' and 'b' and store in 'a'

b = a - b; // Subtract new 'b' from 'a' to get original 'a'

a = a - b; // Subtract new 'b' from new 'a' to get original 'b'


// Print swapped values

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

}

}


#### Output

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5


### Explanation:

- *Initialization*: The variables a and b are initialized with values 5 and 10, respectively.

- *Swapping*:

- *Using Temporary Variable*: Stores the value of a in temp, assigns the value of b to a, and

then assigns the value of temp to b.

- *Using Arithmetic Operations*: Adds a and b, then computes the original values by

subtraction.

- *Printing*: Displays the values before and after the swap.

These methods effectively demonstrate how to swap two numbers in Java, with the first

method using a temporary variable and the second method using arithmetic operations.

26. To calculate compound interest in Java,

you can follow these steps:

[10:21 am, 24/8/2024] Mohit Sir: 1. Define the class.*

2. *Define the main method.*

3. *Initialize the principal amount, rate of interest, number of times interest is compounded per

year, and time (in years).*

4. *Calculate the compound interest using the formula.*

5. *Print the result.*

### Example Program

This program will calculate compound interest based on user input for the principal amount,

annual interest rate, number of times interest is compounded per year, and the time in years.


### Formula for Compound Interest

The compound interest formula is:

\[ A = P \left(1 + \frac{r}{n}\right)^{nt} \]

Where:

- \( A \) = Amount of money accumulated after n years, including interest.

- \( P \) = Principal amount (the initial sum of money).

- \( r \) = Annual interest rate (decimal).

- \( n \) = Number of times that interest is compounded per year.

- \( t \) = Time the money is invested for in years.

The compound interest (CI) can be found using:

\[ CI = A - P \]

### Step-by-Step Code Explanation

#### Step 1: Define the Class

java

public class CompoundInterestCalculator {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *CompoundInterestCalculator*: The name of the class should match the filename

(CompoundInterestCalculator.java).

#### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

#### Step 3: Initialize Variables

java

double principal = 1000; // Principal amount

double rate = 0.05; // Annual interest rate (5%)

int timesCompounded = 4; // Number of times interest is compounded per year

int time = 10; // Time in years

- *double principal = 1000;*: The initial sum of money.


- *double rate = 0.05;*: The annual interest rate (5% expressed as 0.05).

- *int timesCompounded = 4;*: The number of times the interest is compounded per year

(quarterly).

- *int time = 10;*: The number of years the money is invested.

#### Step 4: Calculate Compound Interest

java

double amount = principal * Math.pow(1 + rate / timesCompounded, timesCompounded *

time);

double compoundInterest = amount - principal;

- *double amount = principal * Math.pow(1 + rate / timesCompounded, timesCompounded *

time);*: Calculates the total amount after interest.

- *Math.pow(base, exponent)*: Raises the base to the power of the exponent.

- *double compoundInterest = amount - principal;*: Calculates the compound interest by

subtracting the principal from the total amount.

#### Step 5: Print the Results

java

System.out.println("Principal Amount: " + principal);

System.out.println("Annual Interest Rate: " + (rate * 100) + "%");

System.out.println("Number of Times Compounded per Year: " + timesCompounded);

System.out.println("Time (Years): " + time);

System.out.println("Compound Interest: " + compoundInterest);

System.out.println("Total Amount: " + amount);

}

}

- *System.out.println()*: Prints out the principal, annual interest rate, number of times

compounded, time in years, compound interest, and the total amount.

### Complete Program

Here’s the complete Java program to calculate compound interest:

java

public class CompoundInterestCalculator {

public static void main(String[] args) {

double principal = 1000; // Principal amount

double rate = 0.05; // Annual interest rate (5%)

int timesCompounded = 4; // Number of times interest is compounded per year

int time = 10; // Time in years


// Calculate compound interest

double amount = principal * Math.pow(1 + rate / timesCompounded, timesCompounded *

time);

double compoundInterest = amount - principal;

// Print the results

System.out.println("Principal Amount: " + principal);

System.out.println("Annual Interest Rate: " + (rate * 100) + "%");

System.out.println("Number of Times Compounded per Year: " + timesCompounded);

System.out.println("Time (Years): " + time);

System.out.println("Compound Interest: " + compoundInterest);

System.out.println("Total Amount: " + amount);

}

}


### Output

Principal Amount: 1000.0

Annual Interest Rate: 5.0%

Number of Times Compounded per Year: 4

Time (Years): 10

Compound Interest: 628.894926135

Total Amount: 1628.894926135


### Explanation:

- *Initialization*: Sets principal, rate, number of times compounded, and time.

- *Calculation*: Computes the total amount and compound interest.

- *Printing*: Displays the principal amount, annual interest rate, number of times interest is

compounded per year, time in years, compound interest, and the total amount after interest.

This program demonstrates how to calculate and display compound interest in Java using

standard financial formulas.

27. To determine if a number is prime in

Java, you need to follow these steps:

1. Define the class.*


2. *Define the main method.*

3. *Initialize the number to be checked.*

4. *Check if the number is prime.*

5. *Print the result.*

### Example Program

This program will take an integer as input, check if it is a prime number, and print whether it is

prime or not.

### Step-by-Step Explanation

#### Step 1: Define the Class

java

public class PrimeNumberChecker {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrimeNumberChecker*: The name of the class should match the filename

(PrimeNumberChecker.java).

#### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

#### Step 3: Initialize the Number

java

int number = 29; // Example number to check

boolean isPrime = true; // Assume the number is prime

- *int number = 29;*: Initializes the number to check (e.g., 29).

- *boolean isPrime = true;*: Assumes the number is prime initially.

#### Step 4: Check if the Number is Prime

java

if (number <= 1) {


isPrime = false; // Numbers less than or equal to 1 are not prime

} else {

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

isPrime = false; // Number is divisible by i, so it is not prime

break;

}

}

}

- *if (number <= 1)*: Checks if the number is less than or equal to 1. Numbers less than or equal

to 1 are not prime.

- *for (int i = 2; i <= Math.sqrt(number); i++)*: Loop from 2 to the square root of the number.

- *Math.sqrt(number)*: Calculates the square root of the number. We only need to check up to

the square root.

- *if (number % i == 0)*: Checks if number is divisible by i (i.e., if number modulo i is 0).

- *isPrime = false;*: Sets isPrime to false if the number is divisible by i (not a prime).

- *break;*: Exits the loop early since we found a divisor.

#### Step 5: Print the Result

java

if (isPrime) {

System.out.println(number + " is a prime number.");

} else {

System.out.println(number + " is not a prime number.");

}

}

}

- *if (isPrime)*: Checks the boolean variable isPrime.

- *System.out.println(number + " is a prime number.");*: Prints if the number is prime.

- *System.out.println(number + " is not a prime number.");*: Prints if the number is not prime.

### Complete Program

Here’s the complete Java program to check if a number is prime:

java

public class PrimeNumberChecker {

public static void main(String[] args) {

int number = 29; // Example number to check

boolean isPrime = true; // Assume the number is prime


// Check if the number is prime

if (number <= 1) {

isPrime = false; // Numbers less than or equal to 1 are not prime

} else {

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

isPrime = false; // Number is divisible by i, so it is not prime

break;

}

}

}

// Print the result

if (isPrime) {

System.out.println(number + " is a prime number.");

} else {

System.out.println(number + " is not a prime number.");

}

}

}


### Output

29 is a prime number.


### Explanation:

- *Initialization*: Sets the number to check and assumes it is prime.

- *Prime Check*: Uses a loop to check divisibility from 2 to the square root of the number.

- *Numbers Less Than 2*: Directly marked as not prime.

- *Loop Check*: If the number is divisible by any value within the range, it is marked as not

prime.

- *Printing*: Displays whether the number is prime or not.

This program effectively demonstrates how to check if a number is prime by using mathematical

properties and loops in Java.


28. To find the largest number in an array

in Java, you can follow these steps:

1. Define the class.*

2. *Define the main method.*

3. *Initialize the array with values.*

4. *Find the largest number in the array.*

5. *Print the result.*

### Example Program

This program will find the largest number in an array and print it.

### Step-by-Step Explanation

#### Step 1: Define the Class

java

public class LargestNumberInArray {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *LargestNumberInArray*: The name of the class should match the filename

(LargestNumberInArray.java).

#### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

#### Step 3: Initialize the Array

java

int[] numbers = {34, 78, 12, 56, 89, 23}; // Example array

- *int[] numbers = {34, 78, 12, 56, 89, 23};*: Initializes an array with example values.


#### Step 4: Find the Largest Number in the Array

java

int largest = numbers[0]; // Assume the first element is the largest

for (int i = 1; i < numbers.length; i++) {

if (numbers[i] > largest) {

largest = numbers[i]; // Update largest if current element is greater

}

}

- *int largest = numbers[0];*: Initializes largest with the first element of the array. This assumes

the first element is the largest initially.

- *for (int i = 1; i < numbers.length; i++)*: A loop that iterates through the array starting from the

second element.

- *if (numbers[i] > largest)*: Checks if the current element is greater than the current largest.

- *largest = numbers[i];*: Updates largest if the current element is greater.

#### Step 5: Print the Result

java

System.out.println("The largest number in the array is: " + largest);

}

}

- *System.out.println("The largest number in the array is: " + largest);*: Prints the largest

number found in the array.

### Complete Program

Here’s the complete Java program to find the largest number in an array:

java

public class LargestNumberInArray {

public static void main(String[] args) {

int[] numbers = {34, 78, 12, 56, 89, 23}; // Example array

// Initialize the largest number

int largest = numbers[0]; // Assume the first element is the largest

// Find the largest number in the array

for (int i = 1; i < numbers.length; i++) {

if (numbers[i] > largest) {

largest = numbers[i]; // Update largest if current element is greater


}

}

// Print the largest number

System.out.println("The largest number in the array is: " + largest);

}

}


### Output

The largest number in the array is: 89


### Explanation:

- *Initialization*: Sets up the array with predefined values.

- *Finding the Largest*: Uses a loop to compare each element in the array with the current

largest value and updates the largest value accordingly.

- *Printing*: Displays the largest number found in the array.

This program efficiently finds the largest number in an array by iterating through each element

and comparing values, providing a straightforward approach to solving this problem.

29. To print a sequence of numbers from 1

to 16 in a formatted way using Java, follow

these steps:


1. *Define the class.*

2. *Define the main method.*

3. *Initialize the sequence range.*

4. *Print the numbers in the desired format.*

### Example Program

This program will print numbers from 1 to 16 in a grid-like format:


1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16


### Step-by-Step Explanation

#### Step 1: Define the Class

java

public class PrintSequence {

- *public*: This access modifier allows the class to be accessible from anywhere.

- *class*: This keyword declares a new class.

- *PrintSequence*: The name of the class should match the filename (PrintSequence.java).

#### Step 2: Define the Main Method

java

public static void main(String[] args) {

- *public*: Allows the main method to be accessed from outside the class.

- *static*: Means the method can be called without creating an instance of the class.

- *void*: Specifies that the method does not return any value.

- *main*: The entry point of the program.

- *String[] args*: This parameter can hold command-line arguments.

#### Step 3: Initialize and Print the Numbers

java

int count = 1; // Counter for numbers

// Loop to print numbers from 1 to 16

for (int i = 1; i <= 16; i++) {

// Print the number with formatting

System.out.print(count + " ");

// Print a new line after every 4 numbers

if (i % 4 == 0) {

System.out.println();

}

// Increment the counter

count++;


}

- *int count = 1;*: Initializes a counter to keep track of the numbers being printed.

- *for (int i = 1; i <= 16; i++)*: Loops from 1 to 16.

- *System.out.print(count + " ");*: Prints the current number with a space.

- *if (i % 4 == 0)*: Checks if 4 numbers have been printed on the current line.

- *System.out.println();*: Prints a newline character to start a new row.

- *count++;*: Increments the counter.

### Complete Program

Here’s the complete Java program to print numbers from 1 to 16 in a grid format:

java

public class PrintSequence {

public static void main(String[] args) {

int count = 1; // Counter for numbers

// Loop to print numbers from 1 to 16

for (int i = 1; i <= 16; i++) {

// Print the number with formatting

System.out.print(count + " ");

// Print a new line after every 4 numbers

if (i % 4 == 0) {

System.out.println();

}

// Increment the counter

count++;

}

}

}


### Output

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16


### Explanation:

- *Initialization*: Sets up a counter to start from 1.

- *Looping*: Iterates from 1 to 16, printing each number.

- *Formatting*: Numbers are printed in a grid format with 4 numbers per row.

- *Printing*: Adds a newline after every 4 numbers to create the grid effect.

This approach provides a clear and well-organized way to display

Comments

Popular posts from this blog

PlayerNinja

HOPE DIVINE UNIVERSITY

AKSHATCHOUMALBLOGGER