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

JAVA Unit 1.Model questions

The document explains key concepts of Object-Oriented Programming (OOP) features such as encapsulation, abstraction, inheritance, and polymorphism, as well as Java-specific features like platform independence and robustness. It covers Java's primitive data types, operators, control flow statements, and constructors, providing examples for clarity. Additionally, it discusses the Java Virtual Machine (JVM) and naming conventions, emphasizing their importance in programming practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

JAVA Unit 1.Model questions

The document explains key concepts of Object-Oriented Programming (OOP) features such as encapsulation, abstraction, inheritance, and polymorphism, as well as Java-specific features like platform independence and robustness. It covers Java's primitive data types, operators, control flow statements, and constructors, providing examples for clarity. Additionally, it discusses the Java Virtual Machine (JVM) and naming conventions, emphasizing their importance in programming practices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

List and explain Object-Orientied features

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).

5. Classes and Objects


A class is a blueprint for creating objects, defining their attributes and
behaviors. An object is an instance of a class that contains actual data and can
perform actions defined by the class methods.
2.List features of java and explain any three

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.

4.How to declare constants in Java? Explain with example statements.

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.

Syntax: final data_type CONSTANT_NAME = value;

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 follows specific naming conventions to make code more readable,


consistent, and maintainable. These conventions act as a guideline for naming
classes, methods, variables, constants, and packages.
Camel casing
Pascal casing
Snake casing

How Naming Notations Help in Java Programming


1. Improves Readability:
Consistent naming conventions make code easier to understand for
developers.
Example: calculateArea is more descriptive than calc.
2. Enhances Maintainability:
Clear naming reduces confusion when working in teams or revisiting old
code.
3. Promotes Standardization:
Adhering to standard notations ensures uniformity in large codebases.
4. Simplifies Collaboration:
Developers can quickly understand the purpose of variables, methods,
and classes.
6.Explain java Primitive datatypes with their memory allocations and
example

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.

7.Explain following operators: a) Arithmetic operators


b) Relational operators
c) Logical operators

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 (!)

8.Explain if-else statement with example program

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");
}
}
}

9. Explain else-if statement with example program

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");
}
}
}

10.Explain for loop with example program

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.

public class Main {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the iteration when i is 3
}
System.out.println(i);
}
}
}
12.Explain object decleration in java

In Java, an object is an instance of a class. To create an object, you must first


declare a reference variable that holds the object, and then instantiate the object
using the new keyword.
Syntax: ClassName objectName = new ClassName();

Example :
class Car {
String model;

// Constructor
Car(String model) {
this.model = model;
}
}

public class Main {


public static void main(String[] args) {
// Object declaration and instantiation
Car myCar = new Car("Tesla");

System.out.println("Car model: " + myCar.model);


}
}
13.Explain initialization of one dimensional and two dimensional array with
example.

Initialization of One-Dimensional Array


A one-dimensional array is a collection of elements of the same type stored in a
contiguous memory location. To initialize it, you specify the array size or
directly assign values.
Syntax: data_type[] array_name = new data_type[size];
Example:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Initialization with values

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]);
}
}
}

Initialization of Two-Dimensional Array


A two-dimensional array is an array of arrays, often referred to as a matrix. It
can be initialized by specifying rows and columns.
Syntax: data_type[][] array_name = new data_type[rows][columns];
Example:
public class Main {
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}}; // Initialization with values

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

14.List and explain any 3 overloaded constructors of class String, with


example.

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

// 3. String(String original) Constructor


String str3 = new String("Welcome");
System.out.println("String 3: " + str3); // Prints: String 3: Welcome
}
}

15. Explain following String member functions:


a) lengrh()
b) charAt()
c) toCharArray()
d) equalsIgnoreCase()
e) indexOf()
f) replace()
g) substring()

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.

16. Write a program to demonstrate following Vector functions:


a) addElement()
b) size()
c) capacity()
d) removeElement()
e) elementAt()

import java.util.*;

public class Main {


public static void main(String[] args) {
// Creating a Vector
Vector<String> vec = new Vector<>();

// 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));
}
}

17. Explain the application of constructors, also explain default constructor


with example.

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";
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // Calls the default constructor
System.out.println("Car model: " + myCar.model); // Prints: Unknown
}
}

18. Explain parameterized constructor with example program.

A parameterized constructor is a constructor that accepts one or more


parameters. It allows you to initialize an object with specific values when it is
created, providing more flexibility than a default constructor.

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);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Tesla", 2023); // Parameterized constructor is
called
myCar.display();
}
}

19. Explain method overloading with example program.

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;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of two numbers: " + calc.add(5, 10)); // Calls
first method
System.out.println("Sum of three numbers: " + calc.add(5, 10, 15)); // Calls
overloaded method
}
}

20. Write a program to obtain sum of elements entered as command line


argument.

public class SumOfArguments {


public static void main(String[] args) {
int sum = 0;

// Loop through command-line arguments and add to sum


for (String arg : args) {
sum += Integer.parseInt(arg);
}

System.out.println("Sum of the elements: " + sum);


}
}
21. Explain different access specifiers in java

Access specifiers in Java are keywords used to define the visibility or


accessibility of classes, methods, and variables. There are four types of access
specifiers in Java:

Access Specifiers in Java:


1. public
o Accessible from anywhere, including any class in any package.
2. private
o Accessible only within the same class.
3. protected
o Accessible within the same package and by subclasses, even if they
are in different packages.
4. Default (Package-Private)
o Accessible only within classes in the same package. No access
modifier is specified.

You might also like