0% found this document useful (0 votes)
9 views9 pages

Java Assignment Solutions and Code Examples

Uploaded by

agarwalgarv42
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Java Assignment Solutions and Code Examples

Uploaded by

agarwalgarv42
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java assignment solutions

Thanks — I opened your assignment file and solved all questions (Assignment 2-
[Link]).

Below are clear, runnable Java answers for every question (short answers for Section
A + full example programs for Sections B & C). Copy each code block into its own
.java file (or combine as noted) and run.

Section A — Short answers (5 × 2 = 10 marks)


Q1 — Why we use static classes in Java?

In Java a static nested class (a class declared static inside another class) is
associated with the outer class, not an instance. Use it when the nested class
does not need access to instance members of the outer class — it helps group
related classes, improves encapsulation, and avoids an implicit reference to the
outer instance (memory & clarity benefits).

Q2 — Difference between abstract class and interface in Java


Abstract class: can have fields, constructors, concrete (implemented) methods
and abstract methods; single inheritance (a class can extend one abstract class).
Interface: primarily method contracts; from Java 8+ can have default and
static methods and (Java 9+) private methods; fields are public static

final ; a class can implement multiple interfaces. Use abstract class for shared
implementation/state; interface for pure capability contracts and multiple
inheritance of type.

Q3 — Difference between SIB and IIB


SIB (Static Initialization Block): static { ... } — runs once when the class is
loaded; can initialize static variables.
IIB (Instance Initialization Block): { ... } — runs every time an instance is
created, before constructor; can initialize instance fields common to all
constructors.

Q4 — How to access hidden outer-class variable in inner class?


Use [Link] . Example: [Link].x accesses
outer class x when inner class has a field named x .

Q5 — Boxing vs Unboxing

1/9
Boxing (autoboxing): converting a primitive to its wrapper type (e.g., int →
Integer ).

Unboxing: converting a wrapper to its primitive (e.g., Integer → int ). Java


performs these automatically in many places, but beware of null wrapper
causing NullPointerException on unboxing.

Section B — Coding (7 * 3 = 21 marks)


Q1 — Monkey / Human / BasicAnimal

java

// [Link]
interface BasicAnimal {
void eat();
void sleep();
}

// [Link]
class Monkey {
public void jump() {
[Link]("Monkey jumps!");
}
public void bite() {
[Link]("Monkey bites!");
}
}

// [Link]
class Human extends Monkey implements BasicAnimal {
@Override
public void eat() {
[Link]("Human eats using utensils.");
}
@Override
public void sleep() {
[Link]("Human sleeps at night.");
}
}

2/9
// [Link] (with main)
public class TestHuman {
public static void main(String[] args) {
Human h = new Human();
[Link](); // inherited from Monkey
[Link](); // inherited from Monkey
[Link](); // from BasicAnimal
[Link](); // from BasicAnimal
}
}

Expected output

cpp

Monkey jumps!
Monkey bites!
Human eats using utensils.
Human sleeps at night.

Q2 — Create package Calculation and use its functionality

Create file Calculation/[Link] :

java

package Calculation; // following assignment wording (case-sensitive)

public class Calculator {


public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static double divide(double a, double b) {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;

3/9
}
}

Then use it in another class (in default package or another package), [Link] :

java

import [Link];

public class UseCalc {


public static void main(String[] args) {
[Link]("10 + 5 = " + [Link](10,5));
[Link]("10 - 5 = " + [Link](10,5));
[Link]("10 * 5 = " + [Link](10,5));
[Link]("10 / 5 = " + [Link](10,5));
}
}

Notes: Put [Link] in a folder named Calculation and compile with


javac Calculation/[Link] [Link] , then run java UseCalc .

Q3 — Initializer with static block

java

public class Initializer {


static int initialValue;

static {
initialValue = 1000; // static block initialization
[Link]("Static block executed: initialValue set to " + initialValue);
}

public Initializer() {
[Link]("Initializer constructor called.");
}

public static void main(String[] args) {


// Print before creating instance (class is already loaded by running main so the static block
runs first)
[Link]("Before creating instance: initialValue = " + [Link]);

4/9
Initializer obj = new Initializer();
[Link]("After creating instance: initialValue = " + [Link]);
}
}

Expected flow / output

yaml

Static block executed: initialValue set to 1000


Before creating instance: initialValue = 1000
Initializer constructor called.
After creating instance: initialValue = 1000

Section C — Coding (11 * 3 = 33 marks)


Q1 — Abstract Vehicle , Car , Motorcycle , and Driver

java

import [Link];
import [Link];

// [Link]
abstract class Vehicle {
private String name;
public Vehicle(String name) { [Link] = name; }
public String getName() { return name; }
public abstract void start();
public abstract void stop();
}

// [Link]
class Car extends Vehicle {
public Car(String name) { super(name); }
@Override
public void start() { [Link](getName() + " (Car) starting: ignition ON."); }
@Override
public void stop() { [Link](getName() + " (Car) stopping: ignition OFF."); }
}

5/9
// [Link]
class Motorcycle extends Vehicle {
public Motorcycle(String name) { super(name); }
@Override
public void start() { [Link](getName() + " (Motorcycle) starting: kick-
start/ignition."); }
@Override
public void stop() { [Link](getName() + " (Motorcycle) stopping: brakes
applied."); }
}

// [Link]
class Driver {
private List<Vehicle> vehicles = new ArrayList<>();

public void addVehicle(Vehicle v) {


[Link](v);
}

public void startAll() {


[Link]("Starting all vehicles...");
for (Vehicle v : vehicles) [Link]();
}

public void stopAll() {


[Link]("Stopping all vehicles...");
for (Vehicle v : vehicles) [Link]();
}
}

// [Link] (main)
public class TestVehicles {
public static void main(String[] args) {
Car car1 = new Car("Honda City");
Motorcycle bike1 = new Motorcycle("Yamaha R15");

Driver driver = new Driver();


[Link](car1);
[Link](bike1);

[Link]();
[Link]("--- doing some driving ---");

6/9
[Link]();
}
}

Sample output

sql

Starting all vehicles...


Honda City (Car) starting: ignition ON.
Yamaha R15 (Motorcycle) starting: kick-start/ignition.
--- doing some driving ---
Stopping all vehicles...
Honda City (Car) stopping: ignition OFF.
Yamaha R15 (Motorcycle) stopping: brakes applied.

Q2 — this keyword with Student

java

class Student {
private String name;
private int age;

public Student(String name, int age) {


[Link] = name; // using 'this' to distinguish instance variables
[Link] = age;
}

public void displayDetails() {


[Link]("Student name: " + [Link] + ", age: " + [Link]);
}

public static void main(String[] args) {


Student s = new Student("Amit", 20);
[Link]();
}
}

Expected output

7/9
yaml

Student name: Amit, age: 20

Q3 — Method overriding and use of super

java

// Superclass: Animal
class Animal {
public void makeSound() {
[Link]("Animal makes a sound.");
}
}

// Subclass: Dog overrides and calls super


class Dog extends Animal {
@Override
public void makeSound() {
// call superclass method
[Link]();
// then extend/override behavior
[Link]("Dog barks: Woof! Woof!");
}
}

// [Link] (main)
public class TestOverride {
public static void main(String[] args) {
Animal a = new Animal();
[Link]();

[Link]("---");

Dog d = new Dog();


[Link](); // will call Dog's method which calls [Link]()
}
}

Expected output

8/9
yaml

Animal makes a sound.


---
Animal makes a sound.
Dog barks: Woof! Woof!

If you'd like, I can:

Combine related classes into single files ready for submission, or


Prepare a small ZIP of .java files for you to download, or
Add comments/line-by-line explanations for any specific question.

Which would you prefer?

9/9

Common questions

Powered by AI

The 'this' keyword is used inside a constructor to refer to the current object's instance variables. It helps to distinguish between instance variables and local variables or parameters with the same name. For example, in the class Student, 'this.name = name;' explicitly assigns the parameter 'name' to the instance variable 'name' of the object being created .

In Java, a static nested class is associated with its outer class without needing an instance of it. This association aids in grouping related classes together, enhancing encapsulation by reducing data visibility. Furthermore, it avoids the implicit reference to the outer class instance, providing memory efficiency by not storing a reference to the outer instance, which can clarify the code structure .

Upon executing the Initializer class, the static initialization block executes first, setting the static variable and printing the message about its execution. This is followed by printing the initial value, demonstrating that the static block runs even before any object instantiation. When the Initializer object is created, the constructor runs, confirming the sequence where static initializations precede constructors, as the output reflects setting the initial value once, prior to the constructor's execution .

The 'Calculator' package encapsulates arithmetic operations within a dedicated class, making them reusable and easy to integrate into other Java applications. By organizing related functionalities into a package, it promotes modularity and maintainability, allowing developers to import and use these operations as needed across various parts of an application. Furthermore, it simplifies the arithmetic operations through static methods, providing ease of use and compact code .

An abstract class can have fields, constructors, concrete (implemented) methods, and abstract methods and supports single inheritance where a class can extend only one abstract class. An interface primarily defines method contracts and, from Java 8+, can include default and static methods, and from Java 9+, private methods. Fields in interfaces are implicitly public static final. Abstract classes are suitable for shared implementation and state, while interfaces are used for type contracts and multiple inheritance of types .

The 'super' keyword is essential in method overriding to access the method of a superclass from a subclass. It allows a subclass to invoke the superclass's implementation of a method while still providing its own version of that method. This is demonstrated in the Dog class, where 'super.makeSound()' calls the Animal superclass method before executing additional subclass-specific behavior (Dog's barking).

The TestOverride example demonstrates inheritance and method overriding by having the Dog class extend the Animal class and override its makeSound method. While Animal's makeSound outputs a general sound, Dog overrides this method to include additional barking behavior, using 'super' to also call the original method. This demonstrates Java's support for polymorphism, allowing subclasses to tailor inherited methods while retaining the ability to invoke the parent class version, showcasing flexibility and extensibility in Java's object-oriented programming .

Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class object (e.g., int to Integer), while unboxing is the reverse process (e.g., Integer to int). These conversions simplify coding by allowing primitives to be used interchangeably with objects in operations that require the wrapper class. However, developers should be aware that unboxing can lead to NullPointerException if a null reference is unboxed, since there is no valid primitive representation of a null value .

A static initialization block should be chosen when you need to initialize static variables of a class. This block runs once when the class is loaded, making it ideal for setting up class-level resources or configurations that should be computed once, such as configuration values or computing constants. In contrast, an instance initialization block is used for setting up or initializing data specific to each instance and runs every time an instance is created .

The 'Driver' class in the example demonstrates polymorphism by maintaining a list of Vehicle references and invoking start and stop methods on them without knowing their specific types (Car or Motorcycle). This design allows for flexibility and reusability, as new vehicle types can be added without modifying the Driver class. By leveraging the abstract methods in the Vehicle class, the Driver class can call start and stop on any Vehicle subclass, illustrating polymorphic behavior where one interface supports methods for multiple data types .

You might also like