Java Ans
Java Ans
1. Simple – Java is easy to learn, write, and understand with clear syntax similar to C/C++.
3. Platform Independent – Java programs are compiled into bytecode which can run on any
machine having JVM (Write Once, Run Anywhere – WORA).
4. Secure – Java provides built-in security features like bytecode verification, exception
handling, and no direct memory access.
5. Robust – Java provides strong memory management and exception handling, making it
reliable.
6. Portable – Java code can be easily moved and run on different platforms without changes.
8. Distributed – Java can create distributed applications using technologies like RMI and EJB.
✅ Perfect for MSBTE answers – if you need it in Marathi, or as short notes or a table, let me
know!
Sure! Here's the same explanation about the finalize() method in English, perfectly formatted for
a 4-mark Java theory question (MSBTE or any board):
The finalize() method is used in Java to perform cleanup operations before an object is
removed from memory by the Garbage Collector.
It is called automatically by the JVM when it determines that there are no more references
to the object.
Used to release resources like files, network connections, or database connections before
the object is destroyed.
🧾 Syntax:
// cleanup code
✅ Example:
class Demo {
d = null;
Explanation:
Before the object is destroyed, the finalize() method is called, and the message is printed.
🎯 Short Summary:
finalize() = Used to free up resources before an object is destroyed by the Garbage Collector.
JVM calls it automatically.
Would you like a diagram on Java memory management or Garbage Collection process as well?
String str=”5”;
✅ Method: Integer.parseInt(String s)
int value=5;
String str=Integer.toString(value);z
✅ Method: Integer.toString(int i)
✅ Summary:
Conversion Wrapper Class Method
(2 Marks)
1. Single Inheritance
o ✅ Supported in Java.
2. Multilevel Inheritance
o A class inherits from a class which in turn inherits from another class.
o ✅ Supported in Java.
3. Hierarchical Inheritance
o ✅ Supported in Java.
4. Hybrid Inheritance
o ✅ Not directly supported due to ambiguity, but can be achieved using interfaces.
✅ Syntax:
try {
} catch (ExceptionType e) {
} finally {
try block:
Contains code that might throw an exception.
catch block:
Catches and handles specific type of exception.
finally block:
Always executes after try (and catch if present), whether an exception occurred or not.
Useful for cleanup (like closing files, releasing resources).
✅ Example:
try {
} catch (ArithmeticException e) {
} finally {
Would you like the difference between try-catch and throws explained too?
e) Write the syntax of try-catch-finally blocks.
Here’s the exam-ready answer for the syntax of try-catch-finally blocks in Java:
✅ Syntax:
try {
} catch (ExceptionType e) {
} finally {
try block:
Contains code that might throw an exception.
catch block:
Catches and handles specific type of exception.
finally block:
Always executes after try (and catch if present), whether an exception occurred or not.
Useful for cleanup (like closing files, releasing resources).
✅ Example:
try {
} catch (ArithmeticException e) {
} finally {
}
Would you like the difference between try-catch and throws explained too?
f) Give the syntax of < param > tag to pass parameters to an applet.
Here’s the exam-oriented answer for the syntax of the <param> tag used in Java Applets:
✅ Syntax:
</applet>
✅ Explanation:
✅ Example:
</applet>
🎯 Short Note:
Tag Purpose
Would you like a full applet code example that uses <param>?
In Java, a Stream is a sequence of data used for input and output (I/O) operations.
Stream classes are used to read data from a source (like a file, keyboard) or write data to a
destination (like a file, console).
Java provides different stream classes in the java.io package to handle both byte streams
and character streams.
🔹 1. Byte Streams
Superclasses:
➤ InputStream (for reading)
➤ OutputStream (for writing)
Examples:
FileInputStream
FileOutputStream
BufferedInputStream
DataOutputStream
🔹 2. Character Streams
Superclasses:
➤ Reader (for reading)
➤ Writer (for writing)
Examples:
FileReader
FileWriter
BufferedReader
PrintWriter
🎯 Quick Summary Table:
Let me know if you want a diagram showing Java I/O stream hierarchy – I can provide that too!
✅ Definition of Constructor:
A constructor in Java is a special method that is automatically called when an object of a
class is created.
It is used to initialize objects.
It has the same name as the class and does not have a return type (not even void).
✅ Example:
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "Unknown";
}
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
}
Would you like a short comparison table between constructor and method?
Here’s a clear and concise answer suitable for exams (2–4 marks):
✅ Definition of Class:
It defines the properties (variables) and behaviors (methods) that the objects created from it
will have.
🧾 Example:
class Car {
String color;
void drive() {
System.out.println("Car is moving");
✅ Definition of Object:
It represents a real-world entity and has state (data) and behavior (methods).
🧾 Example:
🎯 Short Summary:
Term Meaning
The FileInputStream class is used to read data (in bytes) from a file.
int read(byte[] b, int off, int len) Reads data into a portion of a byte array
fis.close();
✅ Definition of Error:
In Java, errors are serious problems that typically occur during program execution and
cannot be handled easily.
1. 🔹 Syntax Errors
2. 🔹 Runtime Errors
3. 🔹 Logical Errors
4. 🔹 Compilation Errors
Broad category including all errors found during compilation, mostly syntax errors.
🎯 Short Summary Table:
Let me know if you'd like examples with try-catch handling for runtime errors!
1. 🔹 java.lang
➤ Provides core classes (String, Math, Object, Exception, etc.)
➤ Automatically imported by default.
2. 🔹 java.util
➤ Contains utility classes like collections, Date, Scanner, etc.
3. 🔹 java.io
➤ Supports input and output operations (File, InputStream, OutputStream).
4. 🔹 java.awt
➤ Used for building Graphical User Interface (GUI) components like Button, Frame, etc.
🧾 Bonus Examples:
Let me know if you'd like a list of commonly used classes from each package!
e) Define array. List its types.
✅ Definition of Array:
An array in Java is a collection of elements that are stored in contiguous memory locations.
It is used to store multiple values of the same data type in a single variable.
🧾 Example:
System.out.println(numbers[2]); // Output: 30
1. 🔹 Single-Dimensional Array
– A linear array with one row of elements.
🧾 Example: int[] arr = new int[5];
2. 🔹 Multi-Dimensional Array
– An array of arrays, such as a 2D or 3D array.
🧾 Example: int[][] matrix = new int[3][3];
3. 🔹 Jagged Array
– A multi-dimensional array where rows can have different lengths.
🧾 Example:
Would you like a diagram showing how arrays are stored in memory?
Access specifiers (also called access modifiers) define the scope or visibility of classes,
methods, and variables.
🧾 Example:
}
Let me know if you'd like a diagram showing access levels across packages and subclasses!
Sure! Here's your revised and enriched answer with the additional explanation included in a
clean, exam-ready format:
Q. Explain the Concept of Platform Independence and Portability with Respect to Java
Language
Java is a platform-independent language, which means a Java program can run on any
operating system (Windows, Linux, macOS, etc.) without modification.
When a Java program is compiled, it does not produce machine code. Instead, it produces an
intermediate code called Bytecode.
Bytecode is a highly optimized set of instructions designed to be executed by the Java Virtual
Machine (JVM).
Bytecode is not machine-specific — it is a universal code that can run on any device with a
JVM installed.
🧾 Key Concept:8762
"Write Once, Run Anywhere" — this is possible because of Java’s Bytecode and JVM.
✅ 2. Portability in Java:
🧾 Meaning: You can develop a program on Windows and run the same .class file on Linux or
macOS without changes.
Since Bytecode is universal and not tied to any specific machine, it can be carried across
platforms.
This makes Java a portable language — a program written on one system can run on another
without rewriting.
The only requirement is that the target machine must have a compatible JVM.
✅ Additional Explanation:
JVM is a virtual machine that resides in the computer's memory. It simulates a complete
computer environment to run Java programs.
Although the internal implementation of the JVM differs for each platform, all JVMs interpret
the same Bytecode in the same way.
Therefore, onlyVFUOL/ the JVM needs to be platform-specific, not the Java program itself.
🎯 Summary Table:
Concept Description
Platform
Java Bytecode runs on any OS via JVM
Independence
✅ Diagram:
b) Explain the types of constructors in Java with suitable example.
✅ What is a Constructor?
It has the same name as the class and does not have any return type.
🔹 1. Default Constructor:
🧾 Example:
class Student {
Student() {
Usage:
🧾 Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
Usage:
Java does not provide a built-in copy constructor, but it can be created manually.
🧾 Example:
class Student {
String name;
Student(Student s) {
name = s.name;
Usage:
🎯 Summary Table:
Constructor Type Description
Let me know if you'd like a diagram or a sample program combining all three types!
Sure! Here's the complete answer including all the detailed points you’ve provided, neatly formatted
for a 4-mark question as per MSBTE exam style:
✅ What is a Constructor?
Every time an object is created using the new keyword, a constructor is automatically
invoked.
🔹 Types of Constructors:
1. ✅ Default Constructor:
Numeric → 0
Boolean → false
🧾 Example:
class Test1 {
int i;
boolean b;
byte bt;
float ft;
String s;
System.out.println(t.i); // 0
System.out.println(t.s); // null
System.out.println(t.b); // false
System.out.println(t.bt); // 0
System.out.println(t.ft); // 0.0
o This constructor is written by the programmer and contains logic to initialize default
values.
🧾 Example:
class Student {
int roll_no;
String name;
Student() {
roll_no = 50;
name = "ABC";
void display() {
s.display();
3. ✅ Parameterized Constructor:
o Accepts parameters to initialize object variables with different values for each object.
🧾 Example:
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;
name = n;
void display() {
s.display();
}
4. ✅ Copy Constructor:
🧾 Example:
class Rectangle {
int length;
int breadth;
Rectangle(int l, int b) {
length = l;
breadth = b;
// Copy constructor
Rectangle(Rectangle obj) {
length = obj.length;
breadth = obj.breadth;
🎯 Summary Table:
Constructor Type Description
✅ Let me know if you'd like this converted into PDF or formatted in a chart!
✅ What is a Thread?
🧾 Example:
System.out.println(i);
}
🧾 Example:
System.out.println(i);
}
🎯 Summary Table:
Method Steps
Extending Thread class Extend Thread → Override run() → Create object → Call start()
Let me know if you want a diagram of the thread lifecycle or difference between Thread vs Runnable.
Data flows from external source to Data flows from program to external
3. Direction of Flow
program target
6. Data Handling Handles input as a stream of bytes Handles output as a stream of bytes
✅ Example:
InputStream is used to read data (input), whereas OutputStream is used to write data
(output).
Both are part of the java.io package and handle byte-level I/O.
Would you like a comparison chart for Reader vs Writer classes too (used for character data)?
1aHere is your answer rewritten in a clean, exam-ready tabular format, suitable for MSBTE or similar
4-mark Java theory questions:
Java I/O (Input and Output) is used to process input data and produce output.
It uses the concept of a stream — a continuous flow of data, typically in bytes.
The java.io package provides InputStream and OutputStream classes to handle byte-oriented data.
📊 Comparison Table:
Sr.
InputStream Class OutputStream Class
No.
Used by Java applications to read data from a Used by Java applications to write data to a
1
source destination
Can read data from sources like files, arrays, Can write data to destinations like files, arrays,
2
devices, or sockets devices, or sockets
3 Reads data in the form of bytes Writes data in the form of bytes
Common Methods:‣ int read()‣ int Common Methods:‣ void write(int b)‣ void
5
available()‣ void close() write(byte[] b)‣ flush()
✅ Summary:
Both are abstract classes from java.io and form the base for byte stream handling.
Would you like the same format for Reader vs Writer classes (used for character streams)?
Sr.
String StringBuffer
No.
Contents of the object cannot be Contents of the object can be modified using
3
modified after creation. methods like append(), insert().
Object is created by assigning a string Object is created using the constructor and the new
4
constant in double quotes. keyword.
✅ Summary:
Would you also like the differences between StringBuffer and StringBuilder (non-synchronized
version)?
b) Define a class circle having data members Pi and radius. Initialize and display values of data
members also calculate area of circle and display it
Here's the corrected and complete version of your Java program in the proper MSBTE exam format
(with explanation and correct syntax):
✅ Q. Define a class Circle having data members Pi and radius. Initialize and display values of data
members. Also calculate area of circle and display it.
// Data Members
// Constructor
abc(float p, float r) {
pi = p;
radius = r;
void area() {
void display() {
area();
// Main Method
✅ Output:
Area = 78.5
🔍 Key Concepts Covered:
Would you like the same example with user input using Scanner?
✅ Definition of Exception:
An exception is a problem or abnormal condition that arises during the execution of a program.
It disrupts the normal flow of the program.
Java provides an in-built mechanism called exception handling to manage runtime errors
systematically and allow the program to continue running or terminate gracefully.
Sr.
Exception Name Description
No.
9 OutOfMemoryError When the JVM runs out of memory while allocating new
Sr.
Exception Name Description
No.
objects.
✅ This format is perfect for 4M theory questions and easy to revise during exam time.
Would you like a table with error class hierarchy or example code for any of these exceptions?
(i) drawRect( )
(ii) drawOval( )
(4 Marks)
🔹 1) drawRect( )
✅ Description:
✅ Syntax:
✅ Example:
📝 This draws a rectangle starting at (10,10) with width 60 and height 50.
🔹 2) drawOval( )
✅ Description:
✅ Syntax:
void drawOval(int top, int left, int width, int height);
✅ Example:
a) Write a program using sqrt() and pow() to calculate the square root and power of given number.
Here is a properly formatted Java program that uses sqrt() and pow() to calculate the square root and
power of a given number — suitable for MSBTE 4-mark answers:
✅ Q. Write a Java program using sqrt() and pow() to calculate the square root and power of a given
number. (4M)
✅ Program:
import java.util.Scanner;
class MathExample {
System.out.println(base + " raised to power " + exponent + " is: " + power);
✅ Output (Example):
Enter exponent: 4
📌 Note:
Would you like the same program in Marathi explanation format as well?
b) Write a program to accept four numbers from user using command line arguments and print the
smallest number
Here is a complete Java program that accepts four numbers using command-line arguments and
prints the smallest number — formatted as per MSBTE-style answer:
✅ Q. Write a Java program to accept four numbers from user using command-line arguments and
print the smallest number. (4 Marks)
✅ Program:
class SmallestNumber {
if (args.length != 4) {
return;
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int n3 = Integer.parseInt(args[2]);
int n4 = Integer.parseInt(args[3]);
smallest = n2;
smallest = n3;
smallest = n4;
✅ How to Run:
1. Compile:
javac SmallestNumber.java
java SmallestNumber 45 10 60 25
3. Output:
The smallest number is: 10
📌 Notes:
Would you like the same program using Scanner class instead of command-line arguments?
d) Give the usage of following : i) set Color () ii) get Color () iii) set Foreground () iv) set Background
Here’s the proper explanation of the usage of the following methods — formatted in an MSBTE-
friendly way for a 4-mark question:
🔹 i) setColor(Color c)
✅ Use:
The setColor() method is used in Graphics class to set the current drawing color.
🧾 Syntax:
g.setColor(Color.red);
Example:
g.setColor(Color.blue);
🔹 ii) getColor()
✅ Use:
This method returns the current color being used in the Graphics context.
🧾 Syntax:
Color c = g.getColor();
Example:
🔹 iii) setForeground(Color c)
✅ Use:
This method sets the foreground color of a component (like Label, Button, etc.)
🧾 Syntax:
label.setForeground(Color.red);
Example:
l.setForeground(Color.green);
🔹 iv) setBackground(Color c)
✅ Use:
This method sets the background color of a component (like Frame, Panel, etc.)
🧾 Syntax:
setBackground(Color.cyan);
Example:
f.setBackground(Color.yellow);
📌 Summary Table:
Method Use
Would you like a similar explanation with diagrams or code for drawing colored shapes?
Your code works and logically performs the required task: it reads and displays data for five students
using BufferedReader. However, here is a revised and clean version with formatting corrections and
best practices applied for clarity and better readability:
import java.io.*;
class Student {
int id;
String name;
try {
id = Integer.parseInt(br.readLine());
name = br.readLine();
void display() {
arr[i].setData(br);
arr[i].display();
🟡 Improvements made:
BufferedReader moved to main and passed to setData() — prevents each object from
creating its own.
Would you like a version using the Scanner class instead? It's more beginner-friendly.
c) Describe the use of following methods: (i) Drawoval ( ) (ii) getFont ( ) (iii) drawRect ( ) (iv) getFamily
()
(i) drawOval()
Explanation:
Draws an oval bounded by the specified rectangle (x, y, width, height). If width = height, it
draws a circle.
Example:
g.drawOval(50, 50, 100, 100);
→ Draws a circle with top-left corner at (50, 50) and radius 50.
(ii) getFont()
Belongs to: Component class (inherited by UI elements like Applet, Frame, etc.)
Syntax:
Font getFont()
Explanation:
Returns the Font object being used to draw text in the component.
Example:
Font currentFont = getFont();
→ Gets the font currently set for the component.
(iii) drawRect()
Syntax:
void drawRect(int x, int y, int width, int height)
Explanation:
Draws a rectangle starting from the top-left corner (x, y) with given width and height.
Example:
g.drawRect(10, 20, 100, 50);
→ Draws a rectangle at (10,20) of width 100 and height 50.
(iv) getFamily()
Syntax:
String getFamily()
Explanation:
Retrieves the name of the font family (like "Serif", "SansSerif", etc.) from a Font object.
Example:
System.out.println(f.getFamily());
→ Output: Arial
Let me know if you want this structured in a notes format or added to a document.
d) Write a program to count number of words from a text file using stream classes.
Your provided program to count the number of words in a file using stream classes is mostly correct
and functional. It reads characters one by one and counts spaces to determine the number of words.
Below is a slightly improved and cleaned-up version of your code, with a couple of enhancements
and explanations:
import java.io.*;
if (!file.exists()) {
return;
int wordCount = 0;
int c;
try {
while ((c = fr.read()) != -1) {
if (Character.isLetterOrDigit(c)) {
isWord = true;
} else if (isWord) {
wordCount++;
isWord = false;
if (isWord) {
wordCount++;
} finally {
fr.close();
🔍 Key Improvements:
This approach is more reliable in diverse formatting conditions (e.g., multiple spaces, tabs, or newline
characters). Would you like this adapted to count lines or characters too?
a) Explain the following classes. (i) Byte Stream Class (ii) Character Stream Class
Byte stream classes in Java handle input and output of raw binary data (8-bit bytes).
They are used when working with binary data like images, audio files, and other non-text
files.
Examples:
FileInputStream
FileOutputStream
BufferedInputStream
DataInputStream
🔹 Example:
int b;
System.out.print((char) b);
fis.close();
Character stream classes handle input and output of 16-bit Unicode characters.
They automatically handle character encoding and decoding, which is useful for
reading/writing human-readable text.
Examples:
FileReader
FileWriter
BufferedReader
PrintWriter
🔹 Example:
int ch;
System.out.print((char) ch);
fr.close();
✅ Summary:
Here’s the complete explanation of the Applet Life Cycle with the added points, structured clearly for
academic or exam-oriented use:
When an applet begins, the AWT (Abstract Window Toolkit) calls the following methods in this
sequence:
1. init()
2. start()
3. paint()
When an applet is terminated, the following sequence of method calls takes place:
4. stop()
5. destroy()
1. init( ):
o This method is called only once during the runtime of the applet.
o Example:
o // Initialization code
o }
2. start( ):
o Called immediately after init() and each time the applet's page is displayed
(revisited).
o Example:
o }
3. paint(Graphics g):
o Also called automatically after start() and when the applet is refreshed, resized, or
uncovered.
o Example:
o }
4. stop( ):
o Called when the browser leaves the HTML page containing the applet.
o Example:
o }
5. destroy( ):
o Called when the applet is about to be destroyed (usually when the browser is closed
or navigates away permanently).
o Example:
o // Cleanup code
o }
Can have private, protected, and public Members are public and abstract by
Access Modifiers
members. default.
Would you like an example program that demonstrates both a class and an interface?
d) Define type casting. Explain its types with syntax and example.
Here is the refined and complete explanation based on your provided content, organized neatly for
clarity:
Definition:
The process of converting one data type to another is called type casting or simply casting.
It happens when the source type is smaller than the destination type, i.e., there is no loss of
data.
📌 Example:
int i = 3;
double f;
🔹 Output:
f = 3.0
This process may result in data loss (e.g., truncation of decimal part).
📌 Syntax:
📌 Example:
double f = 3.5;
int i;
🔹 Output:
i=3
Summary Table
Explicit Manual using cast operator Larger to smaller (may lose data) double d = 3.5; int i = (int)d;
Would you like me to format this into a printable note format or add a diagram for better
visualization?
a) Write a java program to copy the contents of one file into another.
Here's a Java program that copies the contents of one file into another using FileInputStream and
FileOutputStream:
import java.io.*;
try {
int byteRead;
fos.write(byteRead);
} catch (IOException e) {
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (IOException e) {
📌 Notes:
Make sure the source.txt file exists in the same directory or provide the full path.
This program reads the source file byte by byte and writes it to the destination file.
Would you like a version that uses buffered streams for better performance?
b) Write a program to create user defined exception “MIN-BAL”. Throw the exception when balance
in account is below 500 rupees.
super(message);
int balance;
// Constructor
BankAccount(int initialBalance) {
balance = initialBalance;
throw new MIN_BAL("Balance is below ₹500. Minimum balance requirement not met.");
} else {
try {
acc1.checkBalance(); // will throw MIN_BAL exception
} catch (MIN_BAL e) {
c) Define a class employee having data members as emp_id, name and salary. Accept and display the
data for five employees.
Here's a Java program that defines a class Employee with data members emp_id, name, and salary. It
accepts and displays the data for five employees using standard input:
import java.io.*;
class Employee {
int emp_id;
String name;
double salary;
emp_id = Integer.parseInt(br.readLine());
name = br.readLine();
salary = Double.parseDouble(br.readLine());
void displayData() {
System.out.println("---------------------------");
// Main method
emp[i].acceptData(br);
System.out.println("\nEmployee Details:");
emp[i].displ
ayData();
This program uses BufferedReader to read input from the user, and it handles five Employee objects
using an array.
In Java, the final keyword is used to restrict the user. It can be applied to variables, methods, and
classes. Here’s how it works:
1. Final Variable:
Once assigned, the value of a final variable cannot be changed (i.e., it becomes a constant).
Example:
class Demo {
void show() {
2. Final Method:
A final method cannot be overridden by subclasses.
Example:
class Parent {
3. Final Class:
A final class cannot be inherited (i.e., no class can extend it).
Example:
void show() {
}
// class SubClass extends FinalClass { } // Error: Cannot subclass the final class
In summary:
Here is a concise and properly formatted answer for “Explain life cycle of thread” worth 4 marks,
based on the Maharashtra State Board format:
A thread in Java passes through the following five states during its life cycle:
1. Newborn State
When a thread object is created using Thread class but the start() method is not yet called, it is in
Newborn state.
2. Runnable State
After calling start(), the thread enters the runnable state. It is ready to run but waiting for CPU time.
Threads are scheduled using priority and round-robin fashion.
3. Running State
The thread is selected by the thread scheduler and is currently executing. It continues to run until it
finishes or yields control.
4. Blocked/Waiting State
A thread enters this state when it is temporarily inactive due to operations like sleep(), wait(), or
suspend(). It resumes execution when the blocking condition is resolved.
5. Dead State
A thread enters this state when the run() method finishes execution or it is terminated explicitly
using stop().
↑ ↓
Blocked/Waiting
Each transition is controlled by methods like start(), yield(), sleep(), wait(), notify(), stop() etc.
Would you like this answer in a PDF or printable format?
Here's a clean and well-formatted answer for Question 4(a): Explain life cycle of a thread (4M), as
per Maharashtra State Board of Technical Education guidelines:
A thread in Java (or any multithreaded environment) goes through several states during its life.
These are:
1. Newborn State:
2. Runnable State:
3. Running State:
o Thread is currently being executed by the CPU.
o It continues until:
Yields
4. Blocked State:
5. Dead State:
o It cannot be restarted.
Would you like help with the remaining sub-questions (b, c, d, etc.) as well?
Logical operators are used to form compound Boolean expressions by combining two or more
conditions. Java supports three logical operators: && (AND), || (OR), and ! (NOT).
Truth Table:
Example:
boolean a = true;
boolean b = false;
Truth Table:
Example:
boolean b = false;
Let me know if you'd like the explanation for the ! (NOT) operator as well or need help with other
sub-questions.
Here is a complete and well-presented answer for Question 4(c): Explain any two logical
operators in Java with example (4 Marks), based on the provided program and MSBTE format:
Logical operators are used to combine multiple boolean expressions or conditions. Java provides
three logical operators:
Operator Meaning
! Logical NOT
boolean a = true;
boolean b = false;
Output:
a && b = false
a || b = true
Explanation:
(The ! operator is shown in the program but can be skipped in explanation if only two operators
are to be discussed.)
Let me know if you'd like similar answers for other parts of Question 4.
Array Vector
1. Array holds multiple values of the same 1. Vector can store different types of
data type (homogeneous). objects (heterogeneous).
3. Array can store primitive data types 3. Vector stores only objects (non-
(e.g., int, char). primitive types).
Vector(3);
Would you like the answer for Question 4(e): List any four methods of String class and state
their use as well?
e List any four methods of string class and state the use of each.