Java Assignment Questions
Java Assignment Questions
Example Code:
// Constructor
public Animal(String species, String sound) {
this.species = species;
this.sound = sound;
}
// Display method
public void display() {
System.out.println("Species: " + species + ", Sound: " + sound);
}
public static void main(String[] args) {
Animal a = new Animal("Dog", "Bark");
a.display();
a.setSound("Woof");
a.display();
}
}
Assignment Questions
1. Explain the concept of a class and an object in Java with a real-world analogy.
A class is a blueprint or template for creating objects. It defines properties (attributes) and
behaviors (methods).
For example, consider a class 'Car'. It defines attributes like color, brand, speed and
methods like drive(), brake().
An object is an instance of a class. If 'Car' is the class, then 'myCar = new Car()' is the object,
representing a specific car with actual values.
Analogy: Class is like a recipe, object is the actual dish cooked using that recipe.
2. What are the different categories of data types in Java, and how do they
differ?
Java data types are divided into:
- Primitive Data Types: byte, short, int, long, float, double, char, boolean. These hold simple
values.
- Non-Primitive (Reference) Data Types: Strings, Arrays, Classes, Interfaces. These hold
references to objects.
Primitive types are predefined and have fixed size, while non-primitive types are created by
the programmer and can have methods.
4. What is the default value assigned to different primitive data types in Java if
not explicitly initialized?
- byte, short, int, long: 0
- float, double: 0.0
- char: '\u0000' (null character)
- boolean: false
- Object references: null
5. What are the different types of variable scopes in Java? Explain each with an
example.
Java has the following variable scopes:
- Local Variables: Declared inside a method. Only accessible within the method.
- Instance Variables: Declared inside a class but outside any method. Each object has its own
copy.
- Static Variables: Declared with static keyword. Shared across all instances.
Example:
All are instructed to implement the programs given below against your roll numbers in
team of two, and submit the same with printout copy after completion of execution.