Question Paper 1 Java
Question Paper 1 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}};
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.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
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");
}
}
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.
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.
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:
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).
o VBox: Arranges its child nodes vertically in a column. It is useful for organizing
elements in a stack or list. Example:
PART B
11.
(a) (i) List the symbols that are used as separators in Java and present an outline of the
same.
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);
java
Copy code
public class Main {
public static void main(String[] args) {
// method body
}
}
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 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;
(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;
}
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");
}
}
(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:
(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.
(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:
Example
Example;’
4. ImageButton: A button with an image instead of text. This is useful for graphical
interfaces.
Example:
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.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("This will always execute");
}
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.
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:
Example:
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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.
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:
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:
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.
import java.io.FileInputStream;
import java.io.IOException;
FileOutputStream:
import java.io.FileOutputStream;
import java.io.IOException;
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.
StringBuffer:
Constructors of StringBuffer:
1. StringBuffer():
o Creates an empty StringBuffer with an initial capacity of 16 characters.
o Example:
2. StringBuffer(int capacity):
o Creates an empty StringBuffer with the specified initial capacity.
o Example:
3. StringBuffer(String str):
o Creates a StringBuffer initialized with the contents of the specified string.
o Example:
4. StringBuffer(CharSequence seq):
o Creates a StringBuffer initialized with the contents of the specified CharSequence
(like a String, StringBuilder, etc.).
o Example
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:
// 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:
3. CheckBox:
o A button that can be either checked or unchecked, typically used to represent binary
choices (true/false).
Example:
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:
(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:
2. HBox:
o Arranges its children in a horizontal row.
Example:
3. GridPane:
o Organizes nodes in a grid, with rows and columns. Each node can be placed at a specific
row and column.
Example:
4. BorderPane:
o Divides the area into five regions: top, bottom, left, right, and center.
Example:
5. StackPane:
o Stacks its children on top of each other, with each child taking the same space.
Example:
6. FlowPane:
o Arranges its children in a flow, wrapping to the next row/column when the space is
filled.
Example:
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;
// Accept names
for (int i = 0; i < n; i++) {
System.out.print("Enter name " + (i+1) + ": ");
names[i] = scanner.nextLine();
}
scanner.close();
}
}
Explanation:
return result;
}
// 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: