JAVA Unit 1.Model questions
JAVA Unit 1.Model questions
Encapsulation
Encapsulation involves bundling data (attributes) and methods (functions) into a
single unit, the object. Access to the data is restricted using access modifiers
like private, and controlled through public methods. This protects the data and
enhances modularity.
2. Abstraction
Abstraction hides the internal implementation of a class and exposes only the
functionality to the user. It focuses on what an object does rather than how it
does it. Abstract classes and interfaces are used to achieve abstraction.
3. Inheritance
Inheritance allows a class (child or subclass) to acquire the properties and
methods of another class (parent or superclass). It promotes code reuse and
establishes a hierarchical relationship between classes.
4. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class,
enabling a single method or operator to behave differently based on the context.
It is achieved through method overloading (compile-time polymorphism) and
method overriding (runtime polymorphism).
Object-Oriented
Platform-Independent
Simple
Secure
Robust
Portable
Multithreaded
High Performance
1. Platform-Independent
Java's "Write Once, Run Anywhere" (WORA) principle makes it platform-
independent. Java code is compiled into bytecode by the Java compiler, which
can be executed on any platform using the Java Virtual Machine (JVM). This
eliminates the need to rewrite code for different operating systems.
2. Robust
Java emphasizes reliability and prevents common errors such as memory leaks.
It uses features like exception handling, automatic garbage collection, and
strong memory management to make programs more robust and error-resistant.
3. Multithreaded
Java supports multithreading, allowing multiple threads to run concurrently.
This makes it possible to perform several tasks simultaneously, improving the
performance of applications such as games, web servers, and GUI-based
programs.
3.Write a short note on Java Virtual machine (JVM)
The Java Virtual Machine (JVM) is a key component of the Java platform that
enables Java programs to run on any device or operating system. It is an abstract
computing machine responsible for executing Java bytecode, which is generated
after compiling Java source code.
Key Responsibilities of JVM
1. Loading: Reads the .class files (bytecode) and loads them into memory.
2. Verification: Ensures the bytecode does not violate Java's security
restrictions.
3. Execution: Converts bytecode into machine-specific instructions using
an interpreter or Just-In-Time (JIT) compiler.
4. Memory Management: Manages application memory through Garbage
Collection, automatically freeing unused memory.
5. Exception Handling: Provides mechanisms to handle runtime errors
effectively.
In Java, constants are declared using the final keyword. A constant is a variable
whose value cannot be modified once it is assigned. By convention, constant
names are written in uppercase letters with underscores (_) separating words.
Example :
class MathConstants {
public static final double PI = 3.14159;
public static final int MAX_LIMIT = 100;
}
class Main {
public static void main(String[] args) {
System.out.println("Value of PI: " + MathConstants.PI);
System.out.println("Maximum Limit: " + MathConstants.MAX_LIMIT);
}
}
5.Explain java Naming Notations. Also specify how they are helpful to java
programming
Java provides 8 primitive data types for handling simple data values. Each
data type has a fixed size, making Java portable across platforms.
byte
Size: 1 byte (8 bits)
Range: -128 to 127
Usage: Saves memory in large arrays and is useful for file handling or
data streams.
short
Size: 2 bytes (16 bits)
Range: -32,768 to 32,767
Usage: Suitable for saving memory in scenarios where int is not required.
int
Size: 4 bytes (32 bits)
Range: -2,147,483,648 to 2,147,483,647
Usage: Most commonly used integer type in Java.
long
Size: 8 bytes (64 bits)
Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Usage: Used for very large integer values.
float
Size: 4 bytes (32 bits)
Range: Approximately ±3.40282347E+38 (7 decimal digits of precision)
Usage: Suitable for saving memory in large floating-point computations.
double
Size: 8 bytes (64 bits)
Range: Approximately ±1.79769313486231570E+308 (15 decimal digits
of precision)
Usage: Default type for decimal values and preferred for high-precision
calculations.
char
Size: 2 bytes (16 bits)
Range: 0 to 65,535 (Represents Unicode characters)
Usage: Used to store single characters or Unicode values.
boolean
Size: 1 bit (implementation-dependent in memory)
Range: true or false
Usage: Represents logical values.
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulus. They work with
numerical data types like int, float, and double. These operators are fundamental
for calculations and are used in expressions to manipulate numeric values.
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
b) Relational Operators
Relational operators are used to compare two values or expressions. They
evaluate the relationship between the operands and return a boolean result (true
or false). These operators are commonly used in control statements (e.g., if or
while) to make decisions based on comparisons.
1. Equal to (==)
2. Not equal to (!=)
3. Greater than (>)
4. Less than (<)
5. Greater than or equal to (>=)
6. Less than or equal to (<=)
c) Logical Operators
Logical operators are used to perform logical operations on boolean
expressions. They allow combining multiple conditions or inverting a
condition's value. These operators are essential in decision-making and control
flow for evaluating complex boolean expressions.
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
The if-else statement is a control flow structure that allows a program to make
decisions based on certain conditions. If the condition in the if block is true, it
executes the associated block of code; if false, it executes the code in the else
block.
Example:
public class Main {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
}
}
else-if Statement
The else-if statement is used to test multiple conditions in sequence. If the first
condition is false, it checks the next condition, and so on. If none of the
conditions are true, the code inside the else block is executed.
Example:
public class Main {
public static void main(String[] args) {
int num = 0;
if (num > 0) {
System.out.println("Positive number");
} else if (num < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
}
}
The for loop is used to execute a block of code a specific number of times. It is
particularly useful when the number of iterations is known beforehand. The
loop consists of three parts: initialization, condition, and increment/decrement.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
11.Explain the use of keyword break and continue with example programs
break Keyword
The break keyword is used to exit from a loop or switch statement prematurely.
When encountered, it immediately terminates the loop or switch and transfers
control to the next statement outside the loop or switch.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exits the loop when i is 3
}
System.out.println(i);
}
}
}
continue Keyword
The continue keyword is used to skip the current iteration of a loop and move
to the next iteration. It does not terminate the loop but skips the remaining
statements for the current iteration.
Example :
class Car {
String model;
// Constructor
Car(String model) {
this.model = model;
}
}
In Java, the String class has several constructors to create string objects in
different ways. Here are three commonly used overloaded constructors:
1. String() Constructor
This constructor creates an empty string with no characters.
2. String(char[] charArray) Constructor
This constructor creates a new string by converting the character array into a
string.
3. String(String original) Constructor
This constructor creates a new string by copying the value of the provided
string.
Example:
public class Main {
public static void main(String[] args) {
// 1. String() Constructor
String str1 = new String();
System.out.println("String 1: " + str1); // Prints: String 1:
// 2. String(char[] charArray) Constructor
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(chars);
System.out.println("String 2: " + str2); // Prints: String 2: Hello
length()
Returns the number of characters in the string.
charAt(int index)
Returns the character at the specified index.
toCharArray()
Converts the string into a new character array.
equalsIgnoreCase(String other)
Compares the string to another string, ignoring case.
indexOf(int ch)
Returns the index of the first occurrence of the specified character.
replace(char oldChar, char newChar)
Replaces all occurrences of oldChar with newChar.
substring(int start)
Returns a substring starting from the specified start index to the end of the
string.
import java.util.*;
// a) addElement()
vec.addElement("Apple");
vec.addElement("Banana");
// b) size()
System.out.println("Size of vector: " + vec.size());
// c) capacity()
System.out.println("Capacity of vector: " + vec.capacity());
// d) removeElement()
vec.removeElement("Apple");
// e) elementAt()
System.out.println("Element at index 0: " + vec.elementAt(0));
}
}
Key Applications:
1. Initialization: Constructors are used to set initial values for an object’s
attributes when it is created.
2. Object Creation: They are essential in object creation and provide a
mechanism to pass parameters during object instantiation.
3. Encapsulation: Constructors allow you to enforce constraints or
validation when creating an object.
Example :
class Car {
String model;
// Default Constructor
Car() {
model = "Unknown";
}
}
Example :
class Car {
String model;
int year;
// Parameterized Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
Method overloading in Java allows a class to have more than one method with
the same name, but with different parameter lists. The methods must differ in
the number or type of parameters (not just in the return type). The correct
method is called based on the number and type of arguments passed during the
method call.
Example:
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}