Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Question Paper 1 Java

Uploaded by

mohanraj08052006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Question Paper 1 Java

Uploaded by

mohanraj08052006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

QUESTION PAPER 1

1. What is an array? How are multidimensional arrays implemented in Java?

 Array: An array is a data structure in Java that holds a fixed-size sequence of elements of
the same type.
 Each element in an array can be accessed using an index, and arrays are stored in
contiguous memory locations.
 Example: int[] arr = {1, 2, 3};

 Multidimensional arrays: These are arrays that contain other arrays, often used to
represent tables or matrices.
 In Java, a multidimensional array can be implemented by specifying multiple dimensions
in the array declaration.
 For instance: int[][] matrix = {{1, 2}, {3, 4}};

This creates a 2x2 matrix where each row is an array.

2. Name the access modifiers in Java.

 Public: The field, method, or class is accessible from anywhere in the program.
 Private: The field, method, or class is only accessible within the same class.
 Protected: The field, method, or class is accessible within the same package or by
subclasses (including those in different packages).
 Default (Package-private): If no access modifier is specified, it means the field, method,
or class is only accessible within the same package.

3. Define inheritance.

 Inheritance is an object-oriented programming (OOP) concept where a class (subclass or


child class) inherits properties and behaviors (fields and methods) from another class
(superclass or parent class). This allows for code reuse and hierarchical relationships.
Example:

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

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}
4. How can a subclass call a constructor defined by its superclass?

 A subclass can call a constructor of its superclass using the super() keyword. The
super() call must be the first statement in the subclass constructor. If not explicitly
called, the default constructor of the superclass is invoked automatically. Example:

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls the constructor of the superclass (Animal)
System.out.println("Dog constructor");
}
}

5. Outline the difference between unchecked exceptions and checked exceptions.

 Checked exceptions: These are exceptions that the compiler forces you to handle, either
with a try-catch block or by declaring them with the throws keyword. Examples
include IOException and SQLException. They typically represent conditions that a
program might be able to recover from.
 Unchecked exceptions: These exceptions occur during the program's execution and are
not checked at compile-time. They are subclasses of RuntimeException and often
represent programming errors. Examples include NullPointerException and
ArrayIndexOutOfBoundsException.

6. Name the methods used by Java for interprocess communication to avoid


polling.

 Java provides the following methods for interprocess communication (IPC) to


synchronize threads and avoid polling:
o wait(): Causes the current thread to release the lock and wait until it is awakened
by another thread.
o notify(): Wakes up one thread that is waiting on the object's monitor.
o notifyAll(): Wakes up all threads that are waiting on the object's monitor.

7. What are streams?

 Streams in Java represent sequences of data. Java provides streams for reading and
writing data to files, network connections, and other input/output sources. There are two
main types:
o Byte streams: Handle raw binary data, like FileInputStream and
FileOutputStream.
o Character streams: Handle data as characters and are used for text files, like
FileReader and FileWriter.

8. Why are parameterized types important?

 Parameterized types are a feature of Java generics that enable classes, interfaces, and
methods to operate on objects of various types while providing compile-time type safety.
This eliminates the need for type casting and ensures that only compatible types are used.
Example:

List<String> list = new ArrayList<>();


list.add("Hello");
String str = list.get(0); // No need for type casting

9. What is JavaFX?

 JavaFX is a framework for building graphical user interfaces (GUIs) in Java. It supports
a wide range of features for building rich user interfaces, including controls (buttons,
tables, etc.), 2D and 3D graphics, animations, and more. JavaFX allows developers to
create desktop applications with modern UIs, and it can be used for both client-side
applications and web-based applications (via Java Web Start).

10. Write a note on HBox and VBox.

 HBox and VBox are layout containers in JavaFX:


o HBox: Arranges its child nodes horizontally in a row. It is commonly used for
layouts where elements should appear side-by-side. Example:

HBox hbox = new HBox();


hbox.getChildren().addAll(new Button("Button 1"), new
Button("Button 2"));

o VBox: Arranges its child nodes vertically in a column. It is useful for organizing
elements in a stack or list. Example:

VBox vbox = new VBox();


vbox.getChildren().addAll(new Button("Button 1"), new
Button("Button 2"));

PART B
11.

(a) (i) List the symbols that are used as separators in Java and present an outline of the
same.

Java Separator Symbols:

Java uses several symbols that serve as separators to help organize code and indicate different
structural elements. Below is a list of the most common separator symbols used in Java:

1. Semicolon (;):
o Marks the end of a statement.
o Example: int x = 5;

2. Comma (,):
o Separates items in a list, such as variables or parameters.
o Example: int a, b, c;

3. Period (.):
o Used for accessing members (methods/fields) of a class or an object.
o Example: System.out.println("Hello");

4. Parentheses (()):
o Used in method calls and method declarations, as well as controlling precedence in
expressions.
o Example: methodName(arg1, arg2);

5. Curly Braces ({}):


o Denote the body of methods, classes, and loops.
o Example:

java
Copy code
public class Main {
public static void main(String[] args) {
// method body
}
}

6. Square Brackets ([]):


o Used for array declarations and accessing elements.
o Example: int[] arr = new int[5];

7. Angle Brackets (<>):


o Used in generics for type parameters.
o Example: ArrayList<String> list = new ArrayList<>();
8. Colon (:):
o Used in enhanced for loop to separate the loop variable from the collection.
o Example: for (int i : arr) { System.out.println(i); }

9. Double Colon (::):


o Method reference operator, used to refer to methods in a more concise way.
o Example: list.forEach(System.out::println);

(ii) Outline the primitive types of data in Java.

Primitive Data Types in Java:

Java defines eight primitive data types, each with its own range of values and usage:

1. byte:
o Size: 1 byte (8 bits).
o Range: -128 to 127.
o Example: byte b = 100;

2. short:
o Size: 2 bytes (16 bits).
o Range: -32,768 to 32,767.
o Example: short s = 1000;

3. int:
o Size: 4 bytes (32 bits).
o Range: -2^31 to 2^31 - 1.
o Example: int i = 10000;

4. long:
o Size: 8 bytes (64 bits).
o Range: -2^63 to 2^63 - 1.
o Example: long l = 100000L;

5. float:
o Size: 4 bytes (32 bits).
o Range: Approx. ±3.40282347E+38F (7 significant digits).
o Example: float f = 10.5f;

6. double:
o Size: 8 bytes (64 bits).
o Range: Approx. ±1.7976931348623157E+308 (15 significant digits).
o Example: double d = 20.5;
7. char:
o Size: 2 bytes (16 bits, Unicode character).
o Range: '\u0000' (0) to '\uffff' (65535).
o Example: char c = 'A';

8. boolean:
o Size: 1 bit.
o Values: true or false.
o Example: boolean flag = true;

(b) (i) Outline the bitwise operators in Java that can be applied to the integer type.

Bitwise Operators in Java:

Bitwise operators are used to manipulate individual bits of an integer value. These operators
perform operations on binary representations of numbers. Java provides the following bitwise
operators:

1. AND (&):
o Compares corresponding bits of two integers. If both bits are 1, the result is 1;
otherwise, it's 0.
o Example: int result = a & b;

2. OR (|):
o Compares corresponding bits of two integers. If at least one bit is 1, the result is 1;
otherwise, it's 0.
o Example: int result = a | b;

3. XOR (^):
o Compares corresponding bits of two integers. If the bits are different, the result is 1;
otherwise, it's 0.
o Example: int result = a ^ b;

4. Complement (~):
o Flips all the bits of an integer, changing 1s to 0s and vice versa.
o Example: int result = ~a;

5. Left Shift (<<):


o Shifts bits to the left by the specified number of positions. This operation fills the empty
positions with 0s.
o Example: int result = a << 2; (Shifts bits of a left by 2 positions)

6. Right Shift (>>):


o Shifts bits to the right by the specified number of positions. The sign bit is used to fill the
empty positions.
o Example: int result = a >> 2; (Shifts bits of a right by 2 positions)

7. Unsigned Right Shift (>>>):


o Shifts bits to the right by the specified number of positions, and fills the empty positions
with 0s (ignores the sign bit).
o Example: int result = a >>> 2;

(ii) Outline while and do-while iteration statements in Java with its general form.

while loop:

The while loop executes a block of code repeatedly as long as the given condition is true. If the
condition is false initially, the loop will not execute.

General Form:

while (condition) {
// Block of code
}

Example:

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

Output:

0
1
2
3
4

do-while loop:

The do-while loop executes a block of code at least once, and then continues to execute as long
as the condition remains true. The condition is checked after the block of code executes,
ensuring that the loop runs at least once.

General Form:
do {
// Block of code
} while (condition);

Example:

int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

Output:

0
1
2
3
4

12.

(a) Outline method overloading and method overriding in Java with code fragments.

Method Overloading: Method overloading in Java occurs when a class has multiple methods
with the same name, but with different parameters (different number or type of arguments).

 Key Points:
o Overloaded methods must differ in the type, number, or both types of parameters.
o It is resolved at compile-time (early binding).

Example:

Java

class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // Calls int version
System.out.println(calc.add(10.5, 20.5)); // Calls double version
}
}

Method Overriding: Method overriding in Java occurs when a subclass provides a specific
implementation for a method already defined in its superclass. This is a way of implementing
runtime polymorphism.

 Key Points:
o The method in the subclass must have the same name, return type, and parameters as
in the superclass.
o It is resolved at runtime (late binding).

Example:

java

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

class Dog extends Animal {


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

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Calls Dog's version of sound
}
}

(b) What is an interface? How to define an interface? How one or more classes can
implement an interface? Outline with code fragments.

Interface: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types. Interfaces
cannot contain instance fields or constructors. An interface defines a contract that other classes
can implement.

 Key Points:
o A class implements an interface by providing implementations for all of its methods.
o An interface can be implemented by multiple classes.

Defining an Interface:
interface Animal {
void sound(); // Abstract method
}

Implementing an Interface:

class Dog implements Animal {


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

class Cat implements Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}

Using the Interface:

public class Main {


public static void main(String[] args) {
Animal dog = new Dog();
dog.sound(); // Calls Dog's sound method

Animal cat = new Cat();


cat.sound(); // Calls Cat's sound method
}
}

(b) Present an outline of Java's multithreading system. Also outline the two ways to
create a thread.

Java Multithreading System: Java provides a built-in support for multithreading, which allows
multiple threads to run concurrently. Threads are lightweight processes, and Java’s
multithreading capabilities enable efficient use of system resources.

Ways to create a thread in Java:

1. By Extending the Thread class:


o You can create a new thread by subclassing the Thread class and overriding its run()
method.

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}

Using the Thread:

public class Main {


public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Starts the thread
}
}

2. By Implementing the Runnable interface:


o Another way to create a thread is by implementing the Runnable interface and passing
it to a Thread object.

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running");
}
}

Using the Runnable:

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t = new Thread(myRunnable);
t.start();
}
}

(a) What is a button? Name and outline the types of buttons JavaFX provides with
visual representations.

A button is a UI component that can be clicked by the user to trigger an action or event. JavaFX
provides several types of buttons, which are:

1. Button: A basic button with text or graphics that performs an action when clicked.

Example:

Button button = new Button("Click Me");


button.setOnAction(e -> System.out.println("Button clicked"));
2. RadioButton: A button that represents a choice in a group of mutually exclusive options.
Only one RadioButton can be selected at a time in a group.

Example

RadioButton radio1 = new RadioButton("Option 1");


RadioButton radio2 = new RadioButton("Option 2");
ToggleGroup group = new ToggleGroup();
radio1.setToggleGroup(group);
radio2.setToggleGroup(group);

3. CheckBox: A button that can be checked or unchecked to represent a true/false value.

Example;’

CheckBox checkBox = new CheckBox("Accept Terms");

4. ImageButton: A button with an image instead of text. This is useful for graphical
interfaces.

Example:

ImageView imageView = new ImageView(new Image("buttonImage.png"));


Button imageButton = new Button();
imageButton.setGraphic(imageView);

13.

(a) (i) What is a Java exception? How Java exception handling is managed? Outline.

Java Exception: An exception in Java is an event that disrupts the normal flow of execution.
When an exception occurs, Java creates an object called an exception object, which contains
details about the error.

Exception Handling: Java handles exceptions using a set of keywords: try, catch, throw,
throws, and finally.

 try: Defines a block of code to be tested for exceptions.


 catch: Catches and handles exceptions thrown by the try block.
 throw: Used to explicitly throw an exception.
 throws: Indicates which exceptions a method can throw.
 finally: A block of code that is always executed, regardless of whether an exception occurred.

Example:

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("This will always execute");
}

(ii) Outline Java's checked exceptions defined in the java.lang package.

Checked Exceptions: Checked exceptions are exceptions that are explicitly checked at compile-
time. They must either be caught in a try-catch block or declared using the throws keyword.

Some common checked exceptions from java.lang:

 IOException: Raised when there is an issue with input/output operations.


 ClassNotFoundException: Raised when a class is not found during runtime.
 SQLException: Raised when there is a database-related issue.

Example:

try {
throw new IOException("File not found");
} catch (IOException e) {
System.out.println("Handled IOException");
}

14.

(a) (i) Outline reading console input and writing console output in Java.

In Java, reading input from the console and writing output to the console can be done using
various classes such as Scanner for input and System.out for output.

Reading Console Input: To read input from the console, Java provides the Scanner class from
the java.util package. Here's how it can be used:

1. Import the Scanner class.


2. Create a Scanner object that reads from System.in (keyboard input).
3. Use methods like nextLine(), nextInt(), etc., to read different types of input.

Example:

import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.println("Hello " + name + ", you are " + age + " years
old.");

scanner.close();
}
}

 Explanation:
o scanner.nextLine() is used to read a full line of text (string).
o scanner.nextInt() is used to read an integer value.
o Always close the Scanner object after use to avoid resource leaks.

Writing Console Output:

To print output to the console, Java provides the System.out object, which supports various
methods such as println() and print() for displaying messages.

 println(): Prints the message and then moves the cursor to the next line.
 print(): Prints the message without moving the cursor to the next line.

Example:

public class ConsoleOutput {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
System.out.print("Enter your name: ");
}
}

(ii) Present an outline of FileInputStream and FileOutputStream classes.

The FileInputStream and FileOutputStream classes are part of the java.io package and are
used for reading from and writing to files as byte streams.

FileInputStream:

 Used to read byte data from a file.


 Suitable for reading binary data such as images, audio files, etc.

Common Methods of FileInputStream:

1. read(): Reads the next byte of data from the input stream.
2. read(byte[] b): Reads bytes into an array.
3. close(): Closes the stream and releases any system resources associated with it.

Example (Reading from a file):

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("example.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData); // Converting byte to
character
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

FileOutputStream:

 Used to write byte data to a file.


 Suitable for writing binary data to a file.

Common Methods of FileOutputStream:

1. write(int b): Writes a byte of data.


2. write(byte[] b): Writes an array of bytes to the file.
3. close(): Closes the output stream.

Example (Writing to a file):

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String data = "Hello, this is a test.";
fos.write(data.getBytes()); // Write string as bytes
} catch (IOException e) {
e.printStackTrace();
}
}
}

 Explanation:
o write(int b) writes a single byte.
o write(byte[] b) writes an array of bytes.
o The try-with-resources statement is used to automatically close the streams.

(b) What is StringBuffer? Name and outline the constructors defined by


StringBuffer with code fragments.

StringBuffer:

 A StringBuffer is a mutable sequence of characters. Unlike String, which is immutable


(cannot be modified after creation), StringBuffer allows modifications such as appending,
inserting, or deleting characters without creating new objects.
 It is primarily used for performance optimization when dealing with strings in situations where
frequent modifications are needed (e.g., in loops).

Constructors of StringBuffer:

1. StringBuffer():
o Creates an empty StringBuffer with an initial capacity of 16 characters.
o Example:

StringBuffer sb = new StringBuffer();


System.out.println(sb); // Output: ""

2. StringBuffer(int capacity):
o Creates an empty StringBuffer with the specified initial capacity.
o Example:

StringBuffer sb = new StringBuffer(50);


System.out.println(sb.capacity()); // Output: 50

3. StringBuffer(String str):
o Creates a StringBuffer initialized with the contents of the specified string.
o Example:

StringBuffer sb = new StringBuffer("Hello");


System.out.println(sb); // Output: "Hello"

4. StringBuffer(CharSequence seq):
o Creates a StringBuffer initialized with the contents of the specified CharSequence
(like a String, StringBuilder, etc.).
o Example

StringBuffer sb = new StringBuffer(new StringBuilder("World"));


System.out.println(sb); // Output: "World"

Common Methods in StringBuffer:

 append(String str): Adds the specified string to the end of the StringBuffer.
 insert(int offset, String str): Inserts the specified string at the specified position.
 delete(int start, int end): Removes characters from the StringBuffer between the
specified start and end indexes.
 reverse(): Reverses the contents of the StringBuffer.

Example:

public class StringBufferExample {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

// Append
sb.append(" World");
System.out.println(sb); // Output: "Hello World"

// Insert
sb.insert(5, ",");
System.out.println(sb); // Output: "Hello, World"

// Reverse
sb.reverse();
System.out.println(sb); // Output: "dlroW ,olleH"
}
}

15.

(a) What is a button? Name and outline the types of buttons JavaFX provides with
visual representations.

In JavaFX, a Button is a UI control that triggers actions when clicked by the user. It is a
commonly used element for interaction in graphical user interfaces (GUIs). JavaFX provides
several types of buttons, each serving different use cases.

1. Button:
o A simple button with text or graphics, typically used to trigger an action when clicked.

Example:
Button button = new Button("Click Me");
button.setOnAction(e -> System.out.println("Button clicked"));

2. RadioButton:
o A button used in a group of options where only one option can be selected at a time.
RadioButton elements are often used for mutually exclusive options.

Example:

RadioButton radioButton1 = new RadioButton("Option 1");


RadioButton radioButton2 = new RadioButton("Option 2");
ToggleGroup group = new ToggleGroup();
radioButton1.setToggleGroup(group);
radioButton2.setToggleGroup(group);

3. CheckBox:
o A button that can be either checked or unchecked, typically used to represent binary
choices (true/false).

Example:

CheckBox checkBox = new CheckBox("Accept Terms");


checkBox.setOnAction(e -> System.out.println("Accepted: " +
checkBox.isSelected()));

4. ImageButton:
o A button that displays an image instead of text. This is useful for creating visually rich
applications where images are used instead of text for buttons.

Example:

ImageView imageView = new ImageView(new Image("buttonImage.png"));


Button imageButton = new Button();
imageButton.setGraphic(imageView);

(b) Name and outline the types of panes JavaFX provides for organizing nodes in a
container.

In JavaFX, a Pane is a container for organizing and laying out UI components (nodes). JavaFX
provides several types of panes to help manage the positioning and resizing of nodes.

1. VBox:
o Arranges its children (nodes) in a vertical column.

Example:

VBox vbox = new VBox();


vbox.getChildren().addAll(new Button("Button 1"), new Button("Button
2"));

2. HBox:
o Arranges its children in a horizontal row.

Example:

HBox hbox = new HBox();


hbox.getChildren().addAll(new Button("Button 1"), new Button("Button
2"));

3. GridPane:
o Organizes nodes in a grid, with rows and columns. Each node can be placed at a specific
row and column.

Example:

GridPane grid = new GridPane();


grid.add(new Button("Button 1"), 0, 0);
grid.add(new Button("Button 2"), 1, 0);

4. BorderPane:
o Divides the area into five regions: top, bottom, left, right, and center.

Example:

BorderPane borderPane = new BorderPane();


borderPane.setTop(new Button("Top"));
borderPane.setCenter(new Button("Center"));

5. StackPane:
o Stacks its children on top of each other, with each child taking the same space.

Example:

StackPane stackPane = new StackPane();


stackPane.getChildren().addAll(new Button("Button 1"), new
Button("Button 2"));

6. FlowPane:
o Arranges its children in a flow, wrapping to the next row/column when the space is
filled.

Example:

FlowPane flowPane = new FlowPane();


flowPane.getChildren().addAll(new Button("Button 1"), new Button("Button
2"));

16.

(a) Write a Java program to accept 'n' names, store them in an array, sort the names in
alphabetic order and display the result. Use classes and methods.

import java.util.Arrays;
import java.util.Scanner;

public class NameSorter {

// Method to sort names alphabetically


public static void sortNames(String[] names) {
Arrays.sort(names);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of names: ");


int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character

String[] names = new String[n];

// Accept names
for (int i = 0; i < n; i++) {
System.out.print("Enter name " + (i+1) + ": ");
names[i] = scanner.nextLine();
}

// Sort names alphabetically


sortNames(names);

// Display sorted names


System.out.println("\nNames in Alphabetic Order:");
for (String name : names) {
System.out.println(name);
}

scanner.close();
}
}

Explanation:

 The program first accepts n names from the user.


 It stores them in an array, sorts the array alphabetically using Arrays.sort(), and then
displays the sorted names.
(b) Write a Java program to accept two square matrices, store them in an array, add
the matrices and display the result. Use classes and methods.
import java.util.Scanner;

public class MatrixAddition {

// Method to add two matrices


public static int[][] addMatrices(int[][] matrix1, int[][] matrix2, int
size) {
int[][] result = new int[size][size];

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


for (int j = 0; j < size; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the square matrices: ");


int size = scanner.nextInt();

int[][] matrix1 = new int[size][size];


int[][] matrix2 = new int[size][size];

System.out.println("Enter elements of Matrix 1:");


for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements of Matrix 2:");


for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Add matrices
int[][] result = addMatrices(matrix1, matrix2, size);

// Display result
System.out.println("Result of Matrix Addition:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}

Explanation:

 The program accepts two square matrices from the user.


 It then adds them element-wise and displays the resulting matrix.

You might also like