1. Define JVM and explain its role in Java execution.
Definition:
The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to
run a Java program. It serves as the runtime engine of the Java Platform, acting as an
intermediary between the compiled Java bytecode and the underlying hardware/operating
system11. This architecture is what makes Java "Platform Independent."
Role and Internal Architecture:
The JVM performs four critical operations during execution:
1. Class Loading (The Subsystem):
○ It reads the .class files (bytecode) generated by the javac compiler.
○ Loading: Finds the binary representation of a class.
○ Linking: Verifies the bytecode (security check) and resolves references.
○ Initialization: Assigns static variables to their default values.
2. Bytecode Verification:
○ Before execution, the JVM inspects the code to ensure it doesn't violate access
rights or forge pointers. This prevents malicious code from crashing the host
machine.
3. Execution Engine:
○ Interpreter: Reads bytecode line-by-line and executes it.
○ JIT (Just-In-Time) Compiler: A performance booster that compiles frequently
executed bytecode ("hotspots") into native machine code, so the processor
doesn't have to interpret it repeatedly.
4. Memory Management:
○ The JVM partitions memory into the Heap (for Objects), Stack (for methods/local
variables), and the Method Area (for class structures)4. It uses Garbage
Collection to automatically reclaim memory from objects that are no longer in
use.
2. Explain visibility modifiers and list their types.
Explanation:
Visibility modifiers (also called access specifiers) control the scope and accessibility of
classes, variables, methods, and constructors5. They are the primary tool for implementing
Encapsulation (Data Hiding) in Object-Oriented Programming.
The 4 Types of Modifiers:
1. private (Most Restrictive):
○ Scope: Accessible only within the same class.
○ Usage: Used for sensitive data (e.g., passwords, internal logic) that shouldn't be
touched by outside classes.
2. Default (Package-Private):
○ Scope: Accessible only within the same package.
○ Condition: Applied automatically if no keyword is written. It allows classes in the
same folder (package) to collaborate but hides them from the rest of the world.
3. protected:
○ Scope: Accessible within the same package AND by subclasses (child classes)
in different packages.
○ Usage: Essential for inheritance, allowing children to access parent properties.
4. public (Least Restrictive):
○ Scope: Accessible from anywhere (any class, any package).
○ Usage: Used for methods intended to be the "public interface" (API) of an object
(e.g., main method).
3. Distinguish between primitive data type and wrapper class.
This distinction is vital for understanding Java memory and performance6.
Feature Primitive Data Type Wrapper Class
Definition Basic data types built into the Java classes that "wrap"
language; they hold pure primitives into Objects.
values.
Memory Stored in Stack Memory (very Stored in Heap Memory (has
fast access). object overhead).
Null Support Cannot be null. They have Can be null. Essential for
defaults (e.g., int is 0). databases where data might
be missing.
Generics Cannot be used in Collections Required for Collections
(List<int> is invalid). (List<Integer> is valid).
Performance High performance; less Slower due to boxing/unboxing
memory. overhead.
4. What is a wrapper class? Give any two examples.
Definition:
A wrapper class is a class in the [Link] package that encapsulates a primitive data type into
an object7. This converts a value type (primitive) into a reference type (object).
Why do we need them?
Java is an Object-Oriented language, but primitives are not objects. Wrapper classes bridge
this gap. They are mandatory when working with the Collection Framework (ArrayList,
HashMap) and multithreading synchronization, which only support Objects.
Mechanism:
● Autoboxing: Automatic conversion of primitive $\rightarrow$ Wrapper (e.g., int to
Integer).
● Unboxing: Automatic conversion of Wrapper $\rightarrow$ primitive.
Examples:
1. Integer: Wraps the primitive int.
2. Character: Wraps the primitive char.
(Others include: Boolean, Double, Byte, Float)
5. Explain the purpose of the this keyword in Java.
Definition:
this is a reference variable that refers to the current object instance executing the code8. It
effectively says "me" or "my variables."
Three Key Purposes:
1. Resolving Variable Shadowing:
When a method parameter has the same name as an instance variable, the local
parameter hides (shadows) the instance variable. this forces the compiler to use the
instance variable.
class Student {
int id; // Instance variable
Student(int id) {
[Link] = id; // "[Link]" is the instance var; "id" is the parameter
}
}
2. Constructor Chaining:
It is used to call another constructor within the same class using this(). This reduces
code duplication.
3. Passing the Current Object:
It can be passed as an argument to other methods or returned from a method (e.g.,
return this;), which is common in "Builder" design patterns.
6. Write the syntax of a Java method declaration.
Explanation:
A method declaration defines the method's attributes (visibility, return type) and its behavior9.
Detailed Syntax:
[Access Modifier] [Non-Access Modifier] [Return Type] methodName(Parameter List) [throws
ExceptionList] {
// Method Body (Business Logic)
// return statement (if return type is not void)
}
Component Breakdown:
● Access Modifier: Defines visibility (e.g., public, private).
● Non-Access Modifier (Optional): Defines special properties (e.g., static, final,
abstract).
● Return Type: The data type the method sends back (e.g., int, String, void).
● Method Name: Follows camelCase convention (e.g., calculateSum).
● Parameter List: Input variables enclosed in parentheses (e.g., (int a, int b)).
● Exception List (Optional): Errors the method might cause (e.g., throws IOException).
7. What is the difference between throw and throws?
Both keywords are used in Exception Handling, but they serve completely different stages of
the process10.
Feature throw throws
Purpose Used to explicitly throw an Used to declare that a method
exception (error) from the might cause an exception.
code.
Location Inside the method body. In the method signature
(header).
Followed By An instance (object) of an The class name of the
exception class. exception.
throw new IOException(); throws IOException
Multiplicity Can throw only one exception Can declare multiple
at a time. exceptions
(comma-separated).
8. What is a nested loop? Mention one use case.
Definition:
A nested loop is a loop structure where one loop (the Inner Loop) is placed entirely inside the
body of another loop (the Outer Loop).
How it Works:
For every single iteration of the Outer Loop, the Inner Loop restarts and executes its full cycle.
● If the outer loop runs $N$ times and the inner loop runs $M$ times, the total operations
are $N \times M$.
● Time Complexity: usually $O(N^2)$.
Use Case: Matrix (2D Array) Processing
To print or calculate data in a grid format (rows and columns), you need a nested loop:
● Outer Loop: Traverses the Rows ($i$).
● Inner Loop: Traverses the Columns ($j$).
// Example: Printing a 3x3 grid of stars
for(int i=0; i<3; i++) { // Rows
for(int j=0; j<3; j++) { // Cols
[Link]("* ");
}
[Link]();
}
9. Mention two advantages of using arrays over individual variables.
1. Efficient Data Management (Code Clarity):
If you need to store the grades of 100 students, declaring 100 separate variables (grade1,
grade2... grade100) makes the code unreadable and unmanageable. An array allows you to
store all these values under a single variable name (int[] grades) referenced by an index12.
2. Random Access (Performance):
Arrays store elements in contiguous memory locations. This allows the computer to calculate
the exact memory address of any element immediately using the formula: Address =
Base_Address + (Index * Size_of_Element).
● This gives O(1) access time—fetching the 1,000th element is just as fast as fetching
the 1st. Individual variables do not offer this capability.
10. What is a multi-dimensional array? Give an example of
declaration.
Definition:
A multi-dimensional array is an array that contains other arrays as its elements13. The most
common form is the Two-Dimensional (2D) Array, which visually represents a table or matrix
with rows and columns.
Memory Layout (The "Professor" Detail):
In Java, a 2D array is not a single block of memory. It is an "Array of References."
● The main array holds pointers (references).
● Each pointer points to a separate 1D array object stored elsewhere in the Heap.
● This allows for "Jagged Arrays" where rows can have different lengths.
Declaration Example:
// Syntax: dataType[][] arrayName = new dataType[rows][cols];
// A 3x3 integer matrix
int[][] matrix = new int[3][3];
// Initialization with values
int[][] numbers = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};
11. Explain the concept of constructors. Types of constructors with
example.
Concept:
A Constructor is a special block of code used to initialize a newly created object1. It sets the
initial state (values of instance variables) of the object immediately after memory is allocated
in the Heap.
Critical Rules (The "Professor" Checklist):
1. Name: Must match the class name exactly.
2. Return Type: It has no return type, not even void. (If you add void, it becomes a
regular method).
3. Invocation: It is called implicitly by the new operator.
Types of Constructors:
1. Default (No-Arg) Constructor:
○ Has no parameters.
○ If you do not write any constructor, the Java Compiler inserts a "default
constructor" automatically to set numeric variables to 0, booleans to false, and
references to null.
2. Parameterized Constructor:
○ Accepts arguments to initialize the object with specific, unique values at the
time of creation.
Code Example:
class Student {
int id;
String name;
// 1. No-Arg Constructor
Student() {
id = 0;
name = "Unknown"; // Setting default state
}
// 2. Parameterized Constructor
Student(int i, String n) {
id = i;
name = n; // Setting specific state
}
}
12. Describe scope of variables: local, instance, and static with examples.
To impress a professor, explain this in terms of Memory Life Cycle.
1. Local Variables (Stack Memory):
2
● Declaration: Inside a method, constructor, or block .
● Scope: Visible only within that specific block { }.
● Life Cycle: Created when the method is called (pushed to Stack) and destroyed
immediately when the method exits (popped from Stack).
● Default Value: No default value. You must initialize them before use, or the compiler
throws an error.
2. Instance Variables (Heap Memory):
● Declaration: Inside the class but outside any method.
● Scope: Accessible by all methods/constructors of the class.
● Life Cycle: Created when an object is created (new). Destroyed when the object is
Garbage Collected.
● Default Value: Have default values (0, null, etc.).
3. Static Variables (Method/Class Area):
● Declaration: Inside the class with the static keyword.
● Scope: Shared across all instances of the class.
● Life Cycle: Loaded once when the Class Loader loads the class. They remain in
memory for the entire runtime of the program.
13. Write a Java program to print the largest of three numbers using
nested if or ternary operator.
Logic:
This program demonstrates decision-making logic. The Nested-If approach is often preferred
in exams because it clearly shows the branching path of logic5.
Code (Nested If Approach):
public class LargestNumber {
public static void main(String[] args) {
int n1 = 40, n2 = 70, n3 = 30;
// Outer check: Compare n1 and n2
if (n1 >= n2) {
// Inner check: Winner vs n3
if (n1 >= n3) {
[Link](n1 + " is the largest.");
} else {
[Link](n3 + " is the largest.");
}
} else {
// Inner check: Winner (n2) vs n3
if (n2 >= n3) {
[Link](n2 + " is the largest.");
} else {
[Link](n3 + " is the largest.");
}
}
}
}
14. What is a static method? How is it different from an instance method?
Explain with an example.
Definition:
A static method belongs to the class rather than any specific object instance6. It is designed
to perform operations that are not dependent on instance variables (e.g., Math calculations
like [Link]()).
Comparison Table:
Feature Static Method Instance Method
Binding Bound to the Class. Bound to the Object.
Calling [Link]() [Link]()
Data Access Can only access static Can access both static and instance
variables. variables.
Memory Loaded once at startup. Loaded per object creation.
Keywords Cannot use this or super. Can use this and super.
Code Example:
class Calculator {
int count = 0; // Instance variable
// Instance Method: Needs an object
void increment() {
count++;
}
// Static Method: Needs no object
static int add(int a, int b) {
// count++; // ERROR: Cannot access instance variable inside static
return a + b;
}
}
15. Describe different types of operators in Java with examples.
Java provides a rich set of operators to manipulate variables.
1. Arithmetic Operators: Perform mathematical calculations.
○ +, -, *, / (Division), % (Modulus/Remainder).
2. Relational (Comparison) Operators: Compare two values and return a boolean
(true/false).
○ == (Equal to), != (Not equal), >, <, >=, <=.
3. Logical Operators: Combine multiple boolean conditions.
○ && (AND): True only if both are true.
○ || (OR): True if at least one is true.
○ ! (NOT): Reverses the boolean state.
4. Assignment Operators: Assign values to variables.
○ =, +=, -=, *=, /=. (e.g., a += 5 is a = a + 5).
5. Unary Operators: Operate on a single operand.
○ ++ (Increment), -- (Decrement).
6. Bitwise Operators: Manipulate individual bits of a number.
○ & (AND), | (OR), ^ (XOR).
16. Explain operator precedence in Java with an example.
Explanation:
Operator precedence defines the order of evaluation in an expression containing multiple
operators. When two operators share an operand, the one with higher precedence is applied
first.
Hierarchy (Highest to Lowest):
1. Postfix: expr++, expr--
2. Unary: ++expr, --expr, !, ~
3. Multiplicative: *, /, %
4. Additive: +, -
5. Shift: <<, >>
6. Relational: <, >, <=
7. Equality: ==, !=
8. Logical AND/OR: &&, ||
9. Assignment: =, +=
Example:
int x = 5, y = 10, z = 2;
int result = x + y * z;
// 1. Multiplication (*) has higher precedence than Addition (+).
// 2. y * z = 10 * 2 = 20
// 3. x + 20 = 5 + 20 = 25
// Result is 25.
17. Write a Java program to demonstrate exception handling using
try-catch (division by zero).
Logic:
Program robustness depends on handling Runtime Exceptions. Here, we attempt a risky
mathematical operation. The JVM identifies the error (ArithmeticException), creates an
exception object, and passes it to the catch block
Code:
public class ExceptionDemo {
public static void main(String[] args) {
[Link]("Program Start...");
int numerator = 50;
int denominator = 0; // This will cause the error
try {
// Risky Code Area
int result = numerator / denominator;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
// Handling Area
[Link]("Critical Error: Division by zero is not allowed.");
// Good practice: Print the system message
// [Link]([Link]());
}
// Code here runs even if an error occurred above
[Link]("Program End.");
}
}
18. Write short notes on BigInteger and BigDecimal classes.
These classes are part of the [Link] package and are used when primitive types (long,
double) are insufficient.
1. BigInteger:
● Problem: The primitive long is 64-bit signed. It has a maximum value of approx $9
\times 10^{18}$.
● Solution: BigInteger can store integers of arbitrary magnitude. Its size is limited only
by the computer's RAM.
● Usage: RSA Cryptography (generating massive prime numbers), Scientific computing.
● Immutability: Operations like .add() return a new object; they do not modify the
original.
2. BigDecimal:
● Problem: Floating-point types (double, float) use binary approximations, leading to
precision errors (e.g., $0.1 + 0.2$ might equal $0.300000000004$).
● Solution: BigDecimal provides exact decimal arithmetic. It allows you to control the
scale (number of digits after decimal) and rounding behavior.
● Usage: Financial Applications, Banking Systems, Currency calculations.
19. Write a Java program to search an element in an array using linear
search.
Theory:
Linear search is the simplest searching algorithm. It works by iterating through the array
sequentially from index 0 to n-1, comparing each element with the target11.
● Time Complexity: O(N) (Worst case: element is at the end or not present).
Code:
import [Link];
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {10, 50, 30, 70, 80, 20};
int target = 30;
boolean found = false;
// Iterate through the array
for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) {
[Link]("Element found at index: " + i);
found = true;
break; // Optimization: Terminate loop immediately
}
}
if (!found) {
[Link]("Element not found in the list.");
}
}
}
20. Explain switch statement vs nested if with one valid use case for each.
Comparison:
Feature Switch Statement Nested If-Else
Condition Type Tests for Equality only (variable Tests Equality, Ranges, Logic (>,
== constant). <, &&).
Supported Data int, char, String, enum. All data types (including boolean).
Performance Faster (often optimized into a Slower (checks every condition
"Jump Table"). sequentially).
Readability Clean and structured for discrete Can become "Spaghetti code" if
choices. too deep.
Use Cases:
1. Switch Case:
○ Scenario: A Menu System.
○ Example: "Press 1 for Coke, 2 for Pepsi, 3 for Water."
○ Reason: You are checking a single variable against fixed constants.
2. Nested If:
○ Scenario: Grading System.
○ Example: "If score > 90 then A, else if score > 80 then B..."
○ Reason: You are checking ranges, which switch cannot do directly.
21. Explain checked and unchecked exceptions. Write a nested try-catch
program with a finally block.
Theory:
Java distinguishes exceptions based on when they are detected.
Feature Checked Exceptions Unchecked Exceptions
Detection Checked at Compile-Time. Checked at Runtime.
Handling Mandatory. You must use try-catch or Optional. The compiler does not
throws. force you to handle them.
Nature Represents external factors outside Represents logic errors or
the program's control. programming bugs.
Examples IOException, SQLException, NullPointerException,
ClassNotFoundException. ArithmeticException,
IndexOutOfBounds.
Program (Nested Try-Catch + Finally):
public class ExceptionMaster {
public static void main(String[] args) {
try {
// Outer Try Block
[Link]("Outer try started...");
try {
// Inner Try Block
int a = 10 / 0; // ArithmeticException (Unchecked)
} catch (ArithmeticException e) {
[Link]("Inner Catch: Cannot divide by zero.");
// Code continues in outer block
String str = null;
[Link]([Link]()); // NullPointerException (Unchecked)
} catch (NullPointerException e) {
// Outer Catch handles what inner didn't catch
[Link]("Outer Catch: Null Pointer detected.");
} finally {
// Finally block ALWAYS runs, error or no error
[Link]("Finally: Resources cleaned up (File closed/DB disconnected).");
}
22. Explain encapsulation, inheritance, and polymorphism with real-life
examples. Write a program demonstrating inheritance.
1. Encapsulation (Data Hiding):
● Concept: Wrapping variables (data) and methods (code) into a single unit (Class) and
protecting the data from outside interference.
● Implementation: Set variables to private and provide public getter/setter methods.
● Real-Life Example: A Capsule. The medicine is hidden inside; you can only consume
it, not touch the chemicals directly.
2. Inheritance (Reusability):
● Concept: A mechanism where a new class (Child/Subclass) acquires the properties
and behaviors of an existing class (Parent/Superclass).
● Real-Life Example: Genetics. A child inherits features (eye color, height) from their
parents but adds their own unique traits.
3. Polymorphism (Flexibility):
● Concept: "Many Forms." The ability of a single action/method to behave differently
based on the object performing it.
● Real-Life Example: A Man. To his wife, he is a "Husband"; to his boss, he is an
"Employee"; to his kids, he is a "Father." One person, different behaviors.
Program (Inheritance):
// Parent Class
class Vehicle {
String brand = "Ford";
public void honk() {
[Link]("Tuut, tuut!");
// Child Class (inherits from Vehicle)
class Car extends Vehicle {
String modelName = "Mustang"; // Car's own property
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
// Accessing inherited method and variable
[Link]();
[Link]([Link] + " " + [Link]);
}
23. Explain the roles of JDK, JVM, and JRE. Discuss Java memory
management.
The Hierarchy:
● JDK (Java Development Kit): The full toolbox. It contains JRE + Development Tools
(Compiler javac, Debugger, JavaDoc).
● JRE (Java Runtime Environment): The implementation. It contains JVM + Class
Libraries (Standard files to run code). It cannot compile code.
● JVM (Java Virtual Machine): The engine. It executes the bytecode.
Java Memory Management (The "Under the Hood" View):
1. Heap Memory:
○ What it stores: Objects (e.g., new Student()) and instance variables.
○ Characteristics: Large, expandable, and shared by all threads.
2. Stack Memory:
○ What it stores: Method calls (stack frames), local variables, and reference
variables.
○ Characteristics: Follows LIFO (Last-In-First-Out). Fast access. Thread-safe
(each thread has its own stack).
3. Class Loader:
○ Subsystem responsible for loading .class files from the hard drive into RAM.
4. Garbage Collection (GC):
○ An automatic daemon thread that monitors Heap memory. It identifies objects
that are "unreachable" (no references point to them) and deletes them to free
up memory, preventing memory leaks.
24. Describe multithreading in Java. Explain thread life cycle and creation
using Runnable and Executor.
Definition:
Multithreading is the concurrent execution of two or more parts of a program to maximize
CPU utilization.
Thread Life Cycle States:
1. New: Object created, start() not yet called.
2. Runnable: Ready to run, waiting for CPU scheduler.
3. Running: CPU is executing the thread's instructions.
4. Blocked/Waiting: Paused for I/O or waiting for a lock.
5. Terminated: The run() method has finished.
Program (Runnable & Executor Framework - The Professional Way):
import [Link];
import [Link];
// 1. Define the task
class MyTask implements Runnable {
public void run() {
[Link]("Task executing by " + [Link]().getName());
public class ThreadDemo {
public static void main(String[] args) {
// 2. Create a Thread Pool (Executor) instead of manual threads
// This recycles threads efficiently
ExecutorService executor = [Link](2);
// 3. Submit tasks
[Link](new MyTask());
[Link](new MyTask());
// 4. Shutdown
[Link]();
}
25. Discuss single-dimensional and two-dimensional arrays in Java (Decl,
Copy, Sort, etc.).
1. Declaration & Initialization:
● 1D: int[] arr = {10, 20, 30};
● 2D: int[][] matrix = { {1, 2}, {3, 4} };
2. Copying:
● [Link](): Fastest method.
● [Link](): Creates a copy. (Warning: Shallow copy for 2D arrays).
3. Sorting:
● [Link](arr): Uses Dual-Pivot Quicksort. Works instantly for 1D arrays.
4. Passing to Methods:
● Passed by Reference. If the method modifies the array content, the original array in
main is changed.
Code Example:
import [Link];
public class ArrayOps {
public static void main(String[] args) {
int[] data = {5, 1, 9, 3};
// Sorting
[Link](data);
[Link]("Sorted: " + [Link](data)); // [1, 3, 5, 9]
// Binary Search (must be sorted first)
int index = [Link](data, 9);
[Link]("Found 9 at index: " + index);
}
}
26. Differences between 1D, 2D, and Multidimensional arrays with memory
layout.
1. One-Dimensional (1D):
● Layout: Linear sequence.
● Memory: A single contiguous object in Heap memory containing primitive values.
● App: Simple lists, buffers.
2. Two-Dimensional (2D):
● Layout: Grid (Rows/Cols).
● Memory (Crucial Distinction): Java does not allocate a single block for a matrix. It is
an Array of Arrays.
○ The "Main Array" holds references (pointers).
○ Each reference points to a completely separate Row Array in memory.
○ Result: Rows can be scattered in the Heap.
● App: Image pixels, Spreadsheets, Games (Chess board).
3. Multidimensional (nD):
● Layout: Array of Arrays of Arrays...
● App: 3D Rendering, Scientific Simulations, Weather Modeling.
27. Difference between Byte Streams and Character Streams.
Java separates I/O to handle text and binary data correctly.
Feature Byte Stream Character Stream
Basic Unit 8-bit (Byte). 16-bit (Unicode Character).
Top InputStream, OutputStream. Reader, Writer.
Classes
Handling Reads raw binary data. Automatically handles Character Encoding
(translating binary to letters).
Use Case Images (.jpg), Video, Audio, Text Files (.txt), XML, HTML, JSON.
PDFs.
Classes FileInputStream, FileReader, FileWriter.
FileOutputStream.
28. Explain event-driven programming in JavaFX.
Concept:
Unlike procedural programming (where code executes line-by-line), in Event-Driven
Programming, the flow is determined by Events (User actions like clicks, key presses). The
program waits for an event, triggers a handler, and then waits again.
Core Components:
1. Event Source: The GUI component that generates the event (e.g., Button, TextField).
2. Event Object: Carries details about the event (e.g., "Mouse clicked at x=50, y=100").
3. Event Handler: The code that runs in response.
Event Handler Types:
● Anonymous Inner Class: (Old style)
● Lambda Expression: (Modern style - Java 8+) [Link](e ->
[Link]("Clicked!"));
Property Binding:
A powerful JavaFX feature where a property of one object is "bound" to another. If the source
changes, the target updates automatically without writing extra code.
● Example: Binding a "Progress Bar" to a "File Download Task".
29. Write a Java program to multiply two 3×3 matrices.
Logic:
To multiply Matrix A and B into C, you need 3 Nested Loops:
1. Loop i: Iterate Rows of A.
2. Loop j: Iterate Columns of B.
3. Loop k: Calculate the dot product (Sum of $A_{ik} \times B_{kj}$).
Code:
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] a = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
int[][] b = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
int[][] c = new int[3][3]; // Result storage
// 1. Iterate Rows of Matrix A
for (int i = 0; i < 3; i++) {
// 2. Iterate Columns of Matrix B
for (int j = 0; j < 3; j++) {
c[i][j] = 0;
// 3. Compute Dot Product
for (int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
[Link](c[i][j] + " ");
[Link](); // New line for next row
}
}
30. Sum of digits without using String or library methods.
Logic:
We use standard math operations to peel off digits one by one.
● number % 10 gives the last digit.
● number / 10 removes the last digit.
Code:
import [Link];
public class DigitSum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int num = [Link]();
int sum = 0;
// Handle negative input
if (num < 0) num = -num;
while (num > 0) {
int lastDigit = num % 10; // Extract
sum += lastDigit; // Accumulate
num /= 10; // Remove
}
[Link]("Sum of digits: " + sum);