0% found this document useful (0 votes)
4 views

java practice set (2)

practice paper for java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java practice set (2)

practice paper for java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PRACTICE SET OF JAVA PROGRAMMING

Explain the key features of Object-Oriented Programming


(OOP) and how they are implemented in Java. Provide
examples for at least two features.
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects," which can contain data (attributes) and code (methods). OOP emphasizes the
following key features:

### Key Features of OOP

1. **Encapsulation**:

- **Definition**: Encapsulation is the bundling of data (attributes) and methods (functions)


that operate on the data into a single unit called a class. It restricts direct access to some of
the object's components, which can enhance security and maintainability.

- **Implementation in Java**: In Java, encapsulation is implemented using access modifiers


(public, private, protected). By marking the class attributes as private, you can control access
through public methods (getters and setters).
- **Example**:

```java
public class BankAccount {
// Private attributes
private double balance;

public BankAccount() {
this.balance = 0.0; // Initialize balance to zero
}

// Public method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;

}
}

// Public method to get the balance


public double getBalance() {

return balance;
}
}

public class Main {

public static void main(String[] args) {


BankAccount account = new BankAccount();
account.deposit(1000);
System.out.println("Balance: $" + account.getBalance());
}
}
```

2. **Inheritance**:
- **Definition**: Inheritance is a mechanism where a new class (subclass) derives
properties and behavior (methods) from an existing class (superclass). This feature promotes
code reusability and establishes a hierarchical relationship between classes.
- **Implementation in Java**: In Java, inheritance is implemented using the `extends`
keyword. A subclass can inherit fields and methods from a superclass, and it can also override
methods.
- **Example**:
```java
// Superclass

class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass inheriting from Animal


class Dog extends Animal {
@Override
public void makeSound() {

System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Dog barks
}
}

```

3. **Polymorphism**:
- **Definition**: Polymorphism allows objects to be treated as instances of their parent
class, enabling a single function to behave differently based on the object it is acting upon.
This can occur through method overriding and overloading.
- **Implementation in Java**: Java supports polymorphism through method overriding
(runtime polymorphism) and method overloading (compile-time polymorphism).

4. **Abstraction**:
- **Definition**: Abstraction is the concept of hiding the complex implementation details
while exposing only the necessary features of an object. It simplifies the interaction with
objects and reduces complexity.
- **Implementation in Java**: Abstraction can be achieved using abstract classes and
interfaces. Abstract classes can have abstract (no implementation) and concrete methods,
while interfaces provide a contract for classes to implement.

### Summary

In summary, OOP provides robust features like encapsulation, inheritance, polymorphism,


and abstraction that enable developers to create modular, reusable, and maintainable code.
Java, as an object-oriented programming language, implements these features clearly with its
syntax and structural rules, allowing for effective and efficient programming practices. The
examples provided here illustrate encapsulation through access modifiers and inheritance
through class extension, showcasing how Java implements these key features of OOP.

02 Differentiate between JDK, JVM, and JRE. Illustrate their roles in


Java program execution.
In the Java ecosystem, three key components play essential roles in the
development and execution of Java applications: the JDK (Java Development
Kit), the JRE (Java Runtime Environment), and the JVM (Java Virtual Machine).
Each of these components has distinct functions and responsibilities.
### 1. Java Development Kit (JDK)
- **Definition:** The JDK is a complete toolkit for developing Java applications.
It contains everything needed to write, compile, and run Java programs.
- **Components:**
- **Compiler (javac):** Converts Java source code (.java files) into bytecode
(.class files).
- **Java Runtime Environment (JRE):** The JRE is bundled within the JDK,
providing the environment to run Java applications.
- **Development Tools:** Includes tools like the Java debugger (jdb), Java
documentation generator (javadoc), and various other utilities.
- **Role in Execution:** The JDK is used by developers to write and compile
Java code. It is primarily for development purposes.

### 2. Java Runtime Environment (JRE)


- **Definition:** The JRE is a subset of the JDK and provides the environment
necessary to run Java applications. It includes the JVM, standard libraries, and
other components required for executing Java programs.
- **Components:**
- **Java Virtual Machine (JVM):** The core component that executes Java
bytecode.
- **Java Class Libraries:** Predefined classes and libraries that provide
functionality to Java applications.
- **Role in Execution:** The JRE allows users to run Java applications without
having the full development kit installed. When an application is executed, the
JRE provides the necessary environment, including the JVM, to run the compiled
Java bytecode.

### 3. Java Virtual Machine (JVM)


- **Definition:** The JVM is the engine that drives the Java code execution. It
interprets the compiled bytecode and translates it into machine code that runs
on the underlying operating system.
- **Functionality:**
- **Bytecode Execution:** Converts Java bytecode into native machine code.
- **Memory Management:** Manages memory allocation and garbage
collection.
- **Platform Independence:** Enables "Write Once, Run Anywhere" (WORA)
by providing a uniform execution environment across different operating
systems.
- **Role in Execution:** The JVM is responsible for executing Java programs. It
loads the .class files, verifies the bytecode, and executes the instructions
accordingly.

### Illustrative Example of Their Roles in Java Program Execution

To better understand how these components interact during the execution of a


Java program, consider the following steps in the process:

1. **Writing the Code**:


- A developer writes Java code in a file with the `.java` extension (e.g.,
`HelloWorld.java`).

2. **Compiling the Code**:


- The developer uses the JDK's compiler (`javac` command) to compile the Java
source code. This generates bytecode in a file with the `.class` extension (e.g.,
`HelloWorld.class`).
- **Role**: The JDK is utilized for this compilation phase.
3. **Executing the Program**:
- The compiled bytecode (`HelloWorld.class`) is run using the Java command
(`java HelloWorld`).
- The command invokes the JRE, which relies on the JVM to execute the
bytecode.
- **Role of JRE**: Provides the execution environment.
- **Role of JVM**: Interprets the bytecode, converts it into machine code, and
runs it.

### Summary Table

| Component | Purpose | Key Features |


|------------|---------|--------------|
| **JDK** | Development | - Includes JRE and tools for development
(compiler, debugger, etc.) |
| **JRE** | Execution | - Provides the environment to run Java applications,
contains JVM and libraries |
| **JVM** | Execution | - Executes bytecode, manages memory, platform
independence |

### Conclusion

In summary, the JDK, JRE, and JVM are interrelated components of the Java
ecosystem, each playing a critical role in the development and execution of Java
applications. The JDK is needed for development, the JRE is required to run
standalone Java applications, and the JVM is the underlying engine that
executes Java bytecode across different platforms. Together, they enable Java's
principle of "Write Once, Run Anywhere" by abstracting the complexities of the
underlying hardware and operating systems.

3. Describe the concept of type casting in Java. Differentiate


between implicit and explicit type casting with examples.
Type casting in Java is the process of converting a variable from one data type to
another. Java provides two primary types of casting: **implicit casting** (also
known as automatic or widening casting) and **explicit casting** (also known
as manual or narrowing casting). Understanding type casting is crucial for
handling different data types correctly, especially when performing operations
involving variables of different types.

### Implicit Type Casting

**Implicit Casting** occurs when a smaller data type is automatically converted


to a larger data type without any explicit instruction from the programmer. This
type of casting is safe because there is no risk of losing data since the larger type
can accommodate all possible values of the smaller type.

#### Example of Implicit Type Casting

```java
public class ImplicitCastingExample {
public static void main(String[] args) {
int intVariable = 100; // 4 bytes
long longVariable = intVariable; // Automatically casted to long (8 bytes)
System.out.println("Integer value: " + intVariable);
System.out.println("Long value: " + longVariable);
}
}
```

**Output:**
```
Integer value: 100
Long value: 100
```

In this example, the `int` variable `intVariable` is implicitly cast to a `long` type
when assigned to `longVariable`. The value remains the same, and this
conversion is done automatically by Java.

### Explicit Type Casting

**Explicit Casting** occurs when a larger data type is manually converted to a


smaller data type. This type of casting requires a cast operator because there is
a potential risk of data loss (for example, when converting from `double` to
`int`). The programmer explicitly indicates that they want to perform this
conversion.

#### Example of Explicit Type Casting


```java
public class ExplicitCastingExample {
public static void main(String[] args) {
double doubleVariable = 9.78; // 8 bytes
int intVariable = (int) doubleVariable; // Manually casted to int (4 bytes)

System.out.println("Double value: " + doubleVariable);


System.out.println("Integer value after explicit casting: " + intVariable);
}
}
```

**Output:**
```
Double value: 9.78
Integer value after explicit casting: 9
```

In this example, the `double` variable `doubleVariable` is explicitly cast to an


`int` type when assigned to `intVariable`. The fractional part of the number is
discarded during this conversion, leading to data loss.

### Summary of Differences


| Feature | Implicit Casting | Explicit Casting |
|-------------------------|------------------------------------|----------------------------------------|
| **Definition** | Automatic conversion from a smaller to a larger data
type. | Manual conversion from a larger to a smaller data type. |
| **Type Safety** | Safe, no data loss occurs. | Risk of data loss, must
be done cautiously. |
| **Syntax** | No special syntax, done automatically. | Requires cast
operator (e.g., `(type)`). |
| **Examples** | `int` to `long`, `float` to `double`. | `double` to `int`,
`long` to `short`. |

### Conclusion

Type casting is an essential feature in Java that allows variable type conversions.
Implicit casting automates the process when it is safe to do so, while explicit
casting requires developer intervention due to potential data loss.
Understanding these concepts helps in writing robust and error-free Java
programs, especially when dealing with different numeric types or objects.

4. Write a Java program to demonstrate the use of access


specifiers by creating a class with fields and methods having
different access levels. Explain the behavior of each access
specifier.
In Java, access specifiers (or access modifiers) control the visibility of classes,
methods, and variables. The four main access specifiers in Java are:
1. **public**: The member is accessible from any other class.
2. **private**: The member is accessible only within its own class.
3. **protected**: The member is accessible within its own package and by
subclasses.
4. **default** (no modifier): The member is accessible only within its own
package.

### Java Program Demonstrating Access Specifiers

Here's a simple Java program to demonstrate the use of access specifiers:

```java
// Class to demonstrate access specifiers
class AccessSpecifiersDemo {
// Public field
public String publicField = "Public Field";

// Private field
private String privateField = "Private Field";

// Protected field
protected String protectedField = "Protected Field";

// Default (package-private) field


String defaultField = "Default Field";
// Public method
public void showPublicMethod() {
System.out.println("Public Method: " + publicField);
}

// Private method
private void showPrivateMethod() {
System.out.println("Private Method: " + privateField);
}

// Protected method
protected void showProtectedMethod() {
System.out.println("Protected Method: " + protectedField);
}

// Default (package-private) method


void showDefaultMethod() {
System.out.println("Default Method: " + defaultField);
}
}

// Test class to access the members of AccessSpecifiersDemo


public class AccessSpecifiersTest {
public static void main(String[] args) {
AccessSpecifiersDemo demo = new AccessSpecifiersDemo();

// Accessing the public field and method


System.out.println(demo.publicField); // Accessible
demo.showPublicMethod(); // Accessible

// Accessing the private field and method


// System.out.println(demo.privateField); // NOT Accessible (will cause a
compile error)
// demo.showPrivateMethod(); // NOT Accessible (will cause a compile
error)

// Accessing the protected field and method


System.out.println(demo.protectedField); // Accessible only if in the same
package or subclass
demo.showProtectedMethod(); // Accessible only if in the same package or
subclass

// Accessing the default field and method


System.out.println(demo.defaultField); // Accessible only in the same
package
demo.showDefaultMethod(); // Accessible only in the same package
}
}
```
### Explanation of Access Specifiers

- **Public (`public`)**:
- Members declared as public can be accessed from any class in any package. In
the above example, `publicField` and `showPublicMethod()` can be accessed
without restriction.

- **Private (`private`)**:
- Members declared as private are accessible only within the class where they
are defined. Attempting to access `privateField` and `showPrivateMethod()`
from `AccessSpecifiersTest` will result in a compile-time error. This
encapsulation is crucial for data hiding.

- **Protected (`protected`)**:
- Members declared as protected can be accessed within the same package or
by subclasses in different packages. In the example, accessing `protectedField`
and `showProtectedMethod()` is allowed in a subclass. However, because
`AccessSpecifiersTest` is not inheriting `AccessSpecifiersDemo`, it should be
encapsulated to prevent access outside the context defined.

- **Default (no modifier)**:


- Members declared with no access modifier (default access) are accessible
only within other classes in the same package. The `defaultField` and
`showDefaultMethod()` can be accessed in `AccessSpecifiersTest` because they
reside in the same package.

### Behavior Summary


- **public**: Accessible everywhere.
- **private**: Accessible only within the defining class.
- **protected**: Accessible within the same package and by subclass members.
- **default**: Accessible only within the same package.

### Conclusion

This program demonstrates how to use and understand Java access specifiers
effectively. By employing the right access levels, developers can achieve better
encapsulation and control over how their classes and methods interact with
other parts of their application.

5. Develop a Java program to showcase method overloading by creating


methods with the same name but different parameter lists. Include at least
three overloaded methods.
Method overloading in Java occurs when multiple methods in the same class
share the same name but differ in their parameter lists (different types or a
different number of parameters). This allows for more readable and
manageable code, as you can perform different tasks using the same method
name.

### Java Program Demonstrating Method Overloading


Here's a simple Java program that showcases method overloading by defining
three methods with the same name but different parameter lists.

```java
public class MethodOverloadingDemo {

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

// Overloaded method to add two double values


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

public static void main(String[] args) {


MethodOverloadingDemo demo = new MethodOverloadingDemo();

// Calling the first overloaded method (two integers)


int sum1 = demo.add(5, 10);
System.out.println("Sum of two integers (5 + 10): " + sum1); // Output: 15

// Calling the second overloaded method (three integers)


int sum2 = demo.add(5, 10, 15);
System.out.println("Sum of three integers (5 + 10 + 15): " + sum2); //
Output: 30

// Calling the third overloaded method (two doubles)


double sum3 = demo.add(5.5, 10.5);
System.out.println("Sum of two doubles (5.5 + 10.5): " + sum3); // Output:
16.0
}
}
```

### Explanation of the Program

1. **Method Definitions**:
- The class `MethodOverloadingDemo` contains three overloaded methods
named `add`:
- `add(int a, int b)`: This method takes two `int` parameters and returns their
sum.
- `add(int a, int b, int c)`: This method takes three `int` parameters and
returns their cumulative sum.
- `add(double a, double b)`: This method takes two `double` parameters and
returns their sum as a `double`.

2. **Main Method**:
- An instance of `MethodOverloadingDemo` is created to call these methods.
- `demo.add(5, 10)`: Calls the first overloaded method and computes the sum
of two integers.
- `demo.add(5, 10, 15)`: Calls the second overloaded method and computes
the sum of three integers.
- `demo.add(5.5, 10.5)`: Calls the third overloaded method to compute the
sum of two doubles.

### Output

When you run the program, you will see the following output:

```
Sum of two integers (5 + 10): 15
Sum of three integers (5 + 10 + 15): 30
Sum of two doubles (5.5 + 10.5): 16.0
```

### Conclusion

The program effectively demonstrates method overloading by allowing the


same method name to be used for different operations based on the method
signature (parameter types and counts). This enhances code clarity and
organizes similar functionalities under a common method, making it easier to
maintain and understand.

6. Create a Java class with both static and non-static members. Write a program
to call these members from the main method and explain the difference
between their behavior.

You might also like