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

OOP Practical Answer

Oops notes

Uploaded by

SUNITA MONDAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

OOP Practical Answer

Oops notes

Uploaded by

SUNITA MONDAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Title: Answering user with output

July 10, 2024

This conversation may reflect the link creator’s personalized data, which isn’t shared and can
meaningfully change how the model responds.

Give me answer of following questions with output:

Sure, please provide the questions, and I'll help you with the answers and their corresponding output.

1. a) Write a program in Java to swap the values of two variables without using a third variable.
b) Write a menu-driven calculator program in Java using switch-case construct.

1. a) Java Program to Swap Values of Two Variables Without Using a Third Variable

Here is a simple Java program to swap the values of two variables without using a third variable:

java

public class SwapValues {


public static void main(String[] args) {
int a = 5;
int b = 10;

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

// Swap values
a = a + b;
b = a - b;
a = a - b;

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

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/21
less

Before swap:
a = 5
b = 10
After swap:
a = 10
b = 5

1. b) Menu-Driven Calculator Program in Java Using Switch-Case Construct

Here's a Java program that implements a simple menu-driven calculator using the switch-case
construct:

java

import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2;
int choice;
boolean exit = false;

while (!exit) {
System.out.println("Menu:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 * num2));
break;
case 4:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error! Division by zero.");
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/21
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice! Please choose a valid option.");
}
System.out.println();
}
scanner.close();
}
}

Example Output:

markdown

Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter first number: 10
Enter second number: 5
Result: 15.0

Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 5

This calculator will keep displaying the menu until the user chooses to exit by selecting option 5.

2. a) Write a program in Java to illustrate the concept of method overloading.


b) Write a program in Java to showcase the concept of dynamic method dispatch.

2. a) Java Program to Illustrate Method Overloading

Method overloading allows a class to have more than one method with the same name, as long as
their parameter lists are different. Here is a simple Java program to illustrate this concept:

java

public class MethodOverloading {


// Method with one integer parameter
public void display(int a) {
System.out.println("Method with one integer parameter: " + a);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/21
// Method with two integer parameters
public void display(int a, int b) {
System.out.println("Method with two integer parameters: " + a + ", " + b);
}

// Method with one double parameter


public void display(double a) {
System.out.println("Method with one double parameter: " + a);
}

public static void main(String[] args) {


MethodOverloading obj = new MethodOverloading();
obj.display(5); // Calls the method with one integer parameter
obj.display(5, 10); // Calls the method with two integer parameters
obj.display(5.5); // Calls the method with one double parameter
}
}

Output:

sql

Method with one integer parameter: 5


Method with two integer parameters: 5, 10
Method with one double parameter: 5.5

2. b) Java Program to Showcase Dynamic Method Dispatch

Dynamic method dispatch (also known as runtime polymorphism) is a mechanism by which a call to
an overridden method is resolved at runtime rather than compile-time. Here’s a Java program to
demonstrate this concept:

java

class A {
// Method to be overridden
void display() {
System.out.println("Display method of class A");
}
}

class B extends A {
// Overriding the display method
void display() {
System.out.println("Display method of class B");
}
}

class C extends A {
// Overriding the display method
void display() {
System.out.println("Display method of class C");
}
}

public class DynamicMethodDispatch {


public static void main(String[] args) {
A a; // Reference variable of type A

// Pointing to an object of class B


a = new B();
a.display(); // Calls the display method of class B

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/21
// Pointing to an object of class C
a = new C();
a.display(); // Calls the display method of class C
}
}

Output:

kotlin

Display method of class B


Display method of class C

In this program, the `display` method of the appropriate subclass (either `B` or `C`) is called based on
the actual object the reference variable `a` points to, demonstrating dynamic method dispatch.

3. a) Write a program in Java to show the concept of multi-level inheritance.


b) Write a program in Java to illustrate the use of super keyword in the constructor of a sub-class.

3. a) Java Program to Show the Concept of Multi-Level Inheritance

In multi-level inheritance, a class is derived from another derived class. Here's an example to illustrate
this concept:

java

// Base class
class Animal {
void eat() {
System.out.println("Eating...");
}
}

// Derived class
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}

// Further derived class


class BabyDog extends Dog {
void weep() {
System.out.println("Weeping...");
}
}

public class MultiLevelInheritance {


public static void main(String[] args) {
BabyDog babyDog = new BabyDog();
babyDog.weep(); // Calls method of BabyDog
babyDog.bark(); // Calls method of Dog
babyDog.eat(); // Calls method of Animal

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/21
}
}

Output:

Weeping...
Barking...
Eating...

3. b) Java Program to Illustrate the Use of `super` Keyword in the Constructor of a


Sub-Class

The `super` keyword in Java is used to call the constructor of the parent class. Here’s an example
demonstrating its use:

java

// Base class
class Person {
String name;

// Base class constructor


Person(String name) {
this.name = name;
System.out.println("Person constructor called");
}

void display() {
System.out.println("Name: " + name);
}
}

// Derived class
class Employee extends Person {
double salary;

// Derived class constructor


Employee(String name, double salary) {
super(name); // Calling the constructor of the base class
this.salary = salary;
System.out.println("Employee constructor called");
}

void display() {
super.display(); // Calling the display method of the base class
System.out.println("Salary: " + salary);
}
}

public class SuperConstructor {


public static void main(String[] args) {
Employee emp = new Employee("John", 50000);
emp.display();
}
}

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/21
kotlin

Person constructor called


Employee constructor called
Name: John
Salary: 50000.0

In this example, the `super(name)` call in the `Employee` constructor invokes the constructor of the
`Person` class, demonstrating how the `super` keyword can be used to initialize the base class part of
an object.

4. a) Write a program in Java to find whether a number is prime or not.


b) Write a program in Java to illustrate the usage of abstract class.

4. a) Java Program to Find Whether a Number is Prime or Not

A prime number is a number that is only divisible by 1 and itself. Here's a Java program to check if a
number is prime:

java

import java.util.Scanner;

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}

scanner.close();
}
}

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/21
less

Enter a number: 17
17 is a prime number.

4. b) Java Program to Illustrate the Usage of Abstract Class

An abstract class in Java is a class that cannot be instantiated and can have abstract methods
(methods without a body) that must be implemented by subclasses. Here's an example:

java

// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();

// Regular method
void sleep() {
System.out.println("Sleeping...");
}
}

// Subclass (inherited from Animal)


class Dog extends Animal {
// Providing implementation of abstract method
void sound() {
System.out.println("Barking...");
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calls the sound method of Dog
dog.sleep(); // Calls the sleep method of Animal
}
}

Output:

Barking...
Sleeping...

In this example, the `Animal` class is abstract and contains an abstract method `sound()`. The `Dog`
class extends `Animal` and provides an implementation for the `sound()` method.

5. a) Write a program in Java to find the minimum among three numbers using nested-if
statements. Take the numbers from user.
b) Write a program in Java to illustrate the concept of method over-riding.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/21
5. a) Java Program to Find the Minimum Among Three Numbers Using Nested-if
Statements

This program will take three numbers from the user and determine the smallest using nested-if
statements:

java

import java.util.Scanner;

public class MinimumOfThree {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();

int min;

if (num1 <= num2) {


if (num1 <= num3) {
min = num1;
} else {
min = num3;
}
} else {
if (num2 <= num3) {
min = num2;
} else {
min = num3;
}
}

System.out.println("The minimum number is: " + min);


scanner.close();
}
}

Output:

yaml

Enter first number: 10


Enter second number: 20
Enter third number: 5
The minimum number is: 5

5. b) Java Program to Illustrate the Concept of Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method that is
already defined in its superclass. Here is an example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/21
java

// Base class
class Animal {
// Method to be overridden
void sound() {
System.out.println("Animal makes a sound");
}
}

// Derived class
class Dog extends Animal {
// Overriding the sound method
@Override
void sound() {
System.out.println("Dog barks");
}
}

public class MethodOverriding {


public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal reference and object
Animal myDog = new Dog(); // Animal reference but Dog object

myAnimal.sound(); // Calls the method in Animal class


myDog.sound(); // Calls the method in Dog class
}
}

Output:

css

Animal makes a sound


Dog barks

In this example, the `sound` method is defined in both the `Animal` class and the `Dog` class. The `Dog`
class provides its own implementation of the `sound` method, demonstrating method overriding.
When `sound` is called on an `Animal` reference that points to a `Dog` object, the `Dog`'s
implementation of `sound` is executed.

6. a) Write a Java program to illustrate the concept "A superclass reference may point to a subclass
object"।
b) Write a program in Java to show the concept of constructor overloading.

6. a) Java Program to Illustrate "A Superclass Reference May Point to a Subclass


Object"

In Java, a superclass reference can refer to an object of its subclass. This is useful in polymorphism.
Here’s an example:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/21
java

// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}

void fetch() {
System.out.println("Dog fetches");
}
}

public class SuperclassReference {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Superclass reference pointing to a subclass object

myAnimal.sound(); // Calls the overridden method in Dog class

// myAnimal.fetch(); // This line would cause a compile-time error


}
}

Output:

Dog barks

In this example, the `myAnimal` reference of type `Animal` points to an object of type `Dog`. When
is called on `myAnimal`, the overridden method in the `Dog` class is executed, demonstrating
`sound`
polymorphism. The line `myAnimal.fetch()` is commented out because the `fetch` method is not
defined in the `Animal` class and would cause a compile-time error.

6. b) Java Program to Show the Concept of Constructor Overloading

Constructor overloading is when a class has more than one constructor with different parameter lists.
Here’s an example:

java

public class ConstructorOverloading {


int id;
String name;
int age;

// Constructor with two parameters


ConstructorOverloading(int id, String name) {
this.id = id;
this.name = name;
}

// Constructor with three parameters

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/21
ConstructorOverloading(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
if (age != 0) {
System.out.println("Age: " + age);
}
}

public static void main(String[] args) {


ConstructorOverloading student1 = new ConstructorOverloading(1, "Alice");
ConstructorOverloading student2 = new ConstructorOverloading(2, "Bob", 20);

student1.display();
System.out.println();
student2.display();
}
}

Output:

makefile

ID: 1
Name: Alice

ID: 2
Name: Bob
Age: 20

In this example, the class `ConstructorOverloading` has two constructors with different parameter
lists. The first constructor initializes `id` and `name`, while the second constructor initializes `id`,
`name`, and `age`. This allows creating objects with different initial states.

7. a) Write a program in Java to show usages of multiple catch clauses in a program.


b) Write a program in Java to illustrate the use of 'throws' keyword.

7. a) Java Program to Show Usages of Multiple Catch Clauses

In Java, multiple catch clauses can be used to handle different types of exceptions. Here’s an example:

java

public class MultipleCatchDemo {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println("Accessing element at index 3: " + numbers[3]); //

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/21
ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: Array index out of
bounds.");
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}

Output:

sql

ArrayIndexOutOfBoundsException caught: Array index out of bounds.


Finally block executed.

In this example, the program demonstrates the use of multiple catch clauses to handle different types
of exceptions. The first catch block catches `ArithmeticException`, the second catches
`ArrayIndexOutOfBoundsException`, and the last one is a generic catch block for any other exceptions.

7. b) Java Program to Illustrate the Use of `throws` Keyword

The `throws` keyword in Java is used to declare that a method can throw one or more exceptions.
Here’s an example:

java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ThrowsDemo {


// Method that throws IOException
public static void readFile(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}

public static void main(String[] args) {


try {
readFile("example.txt"); // Make sure this file exists in the same directory
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
}

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/21
yaml

IOException caught: example.txt (No such file or directory)

In this example, the `readFile` method declares that it throws an `IOException`. When calling this
method, the `main` method handles the exception using a try-catch block. This demonstrates how the
`throws` keyword is used to propagate exceptions up the call stack.

8. a) Write a program in Java illustrating the concept of inheritance of interfaces.


b) Write a Java program illustrating the concept of inner classes.

8. a) Java Program Illustrating the Concept of Inheritance of Interfaces

In Java, interfaces can inherit from other interfaces using the `extends` keyword. Here’s an example
demonstrating interface inheritance:

java

// Base interface
interface Animal {
void sound();
}

// Derived interface inheriting from Animal


interface Dog extends Animal {
void fetch();
}

// Dog class implementing the Dog interface


class Labrador implements Dog {
@Override
public void sound() {
System.out.println("Labrador barks");
}

@Override
public void fetch() {
System.out.println("Labrador fetches");
}
}

public class InterfaceInheritanceDemo {


public static void main(String[] args) {
Labrador labrador = new Labrador();
labrador.sound(); // Calls the method from Dog interface
labrador.fetch(); // Calls the method from Dog interface
}
}

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/21
Labrador barks
Labrador fetches

In this example, the `Dog` interface inherits the `Animal` interface, and the `Labrador` class
implements the `Dog` interface. The `Labrador` class must provide implementations for all methods
defined in both `Animal` and `Dog` interfaces.

8. b) Java Program Illustrating the Concept of Inner Classes

Inner classes are classes defined within another class in Java. There are several types of inner classes:
non-static nested classes (inner classes), static nested classes, local classes, and anonymous classes.
Here’s an example of each type:

Non-Static Nested Class (Inner Class)

java

// Outer class
class Outer {
private int outerData = 10;

// Inner class
class Inner {
void display() {
System.out.println("Outer data: " + outerData);
}
}
}

public class InnerClassDemo {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

Output:

kotlin

Outer data: 10

Static Nested Class

java

// Outer class
class Outer {
static class Nested {
void display() {
System.out.println("Static nested class method");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/21
}
}
}

public class StaticNestedClassDemo {


public static void main(String[] args) {
Outer.Nested nested = new Outer.Nested();
nested.display();
}
}

Output:

kotlin

Static nested class method

Local Class (Class Inside a Method)

java

// Outer class
class Outer {
void outerMethod() {
// Local class inside a method
class Local {
void display() {
System.out.println("Local class method");
}
}

Local local = new Local();


local.display();
}
}

public class LocalClassDemo {


public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
}
}

Output:

kotlin

Local class method

Anonymous Class

java

// Interface
interface Greeting {
void greet();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/21
}

public class AnonymousClassDemo {


public static void main(String[] args) {
// Anonymous class implementing the interface
Greeting greeting = new Greeting() {
@Override
public void greet() {
System.out.println("Hello, Anonymous Class!");
}
};

greeting.greet();
}
}

Output:

mathematica

Hello, Anonymous Class!

Inner classes provide encapsulation and logical grouping of classes within other classes, enhancing
code readability and maintainability.

9. a) Write a Java program to find whether a number is Armstrong number or not.


b) Write a Java program to illustrate the use of continue keyword.

9. a) Java Program to Find Whether a Number is Armstrong Number or Not

An Armstrong number (also known as narcissistic number) for a given number of digits is a number
that is equal to the sum of its own digits each raised to the power of the number of digits. Here's a
Java program to check if a number is an Armstrong number:

java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int originalNumber, remainder, result = 0, n = 0;

originalNumber = number;

// Count number of digits


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/21
originalNumber = number;

// Calculate result
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
originalNumber /= 10;
}

if (result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");

scanner.close();
}
}

Output:

csharp

Enter a number: 153


153 is an Armstrong number.

In this program:

We first calculate the number of digits (`n`) in the given number.


Then, we calculate the sum of each digit raised to the power of `n`.
Finally, we compare the calculated sum (`result`) with the original number to determine if it's an
Armstrong number.

9. b) Java Program to Illustrate the Use of `continue` Keyword

The `continue` keyword in Java is used to skip the current iteration of a loop and proceed to the next
iteration. Here’s an example demonstrating its use:

java

public class ContinueKeywordDemo {


public static void main(String[] args) {
// Print even numbers between 1 to 10, skipping odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
System.out.println(i);
}
}
}

Output:

2
4
6

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/21
8
10

In this example:

The `for` loop iterates through numbers from 1 to 10.


The `if` statement checks if the current number `i` is odd (`i % 2 != 0`).
If `i` is odd, the `continue` statement skips the rest of the loop body for that iteration.
Therefore, only even numbers are printed (2, 4, 6, 8, 10).

The `continue` keyword is useful for skipping certain iterations based on a condition without exiting
the loop entirely.

10. a) Write a program in Java to show the usage of break statement.


b) Write a program in Java to print all possible combinations of 1,2 and 3 without any repetition of
individual digits.

10. a) Java Program to Show the Usage of `break` Statement

The `break` statement in Java is used to terminate the loop or switch statement it is used in. Here’s an
example demonstrating its use:

java

public class BreakStatementDemo {


public static void main(String[] args) {
// Example 1: Using break to terminate a loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
System.out.println("Breaking the loop at i = " + i);
break; // Breaks out of the loop when i is 5
}
System.out.println("Current i value: " + i);
}

System.out.println(); // Just for separating outputs

// Example 2: Using break in a nested loop


outerloop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
System.out.println("Breaking the nested loop at i = " + i + ", j = " +
j);
break outerloop; // Breaks out of both loops when j is 2
}
System.out.println("i = " + i + ", j = " + j);
}
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/21
Output:

less

Current i value: 1
Current i value: 2
Current i value: 3
Current i value: 4
Breaking the loop at i = 5

i = 1, j = 1
Breaking the nested loop at i = 1, j = 2

In this program:

Example 1 demonstrates using `break` to terminate a `for` loop when `i` equals 5.
Example 2 shows using `break` to break out of a nested loop labeled as `outerloop` when `j`
equals 2.

10. b) Java Program to Print All Possible Combinations of 1, 2, and 3 Without


Repetition

To print all possible combinations of the digits 1, 2, and 3 without repeating any individual digit, we
can use nested loops. Here’s a Java program to achieve this:

java

public class DigitCombinations {


public static void main(String[] args) {
int count = 0;

// Nested loops to generate combinations


for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++) {
// Ensure digits are not repeated
if (i != j && j != k && i != k) {
System.out.println(i + " " + j + " " + k);
count++;
}
}
}
}

System.out.println("Total combinations: " + count);


}
}

Output:

mathematica

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/21
3 2 1
Total combinations: 6

In this program:

We use three nested `for` loops to generate combinations of digits 1, 2, and 3.


Each combination is checked to ensure that no digit is repeated (`i != j && j != k && i != k`
condition).
Valid combinations are printed, and a count of total combinations is displayed at the end.

This approach ensures that all possible combinations of the digits 1, 2, and 3 are printed without any
repetition of individual digits within each combination.

|Terms of use|Privacy policy|

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/21

You might also like