Java_Assignment (2)
Java_Assignment (2)
// Animal.java
public class Animal {
private String species;
private String sound;
// Main.java
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal("Dog", "Bark");
myAnimal.display();
myAnimal.setSpecies("Cat");
myAnimal.setSound("Meow");
myAnimal.display();
}
}
Assignment Questions
1. Explain the concept of a class and an object in Java with a real-world analogy.
A class is like a blueprint for creating objects. It defines the structure and behavior
(attributes and methods). An object is an instance of a class.
Real-world analogy: Think of a class as a 'Car blueprint', and an object as an actual car made
from that blueprint. Multiple cars (objects) can be created from the same blueprint (class),
each with its own values (color, speed).
2. What are the different categories of data types in Java, and how do they
differ from each other?
Java has two main categories:
Differences:
- Primitives are faster and require less memory.
- Reference types can store more complex data and behaviors.
3. What is the default value assigned to different primitive data types in Java if
not explicitly initialized?
Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Note: These default values apply to instance variables, not local variables.
4. What are the different types of variable scopes in Java? Explain each with an
example.
1. Local Variables:
- Declared inside a method or block and only accessible there.
Example:
void method() {
int localVar = 5;
}
2. Instance Variables:
- Declared inside a class but outside methods. Each object gets its own copy.
Example:
public class Demo {
int instanceVar = 10;
}
3. Class/Static Variables:
- Declared with static. Shared among all instances of the class.
Example:
public class Demo {
static int staticVar = 20;
}