What are class attributes in Java?
B
Local variables inside methods
C
Variables declared inside a class but outside methods
D
Parameters passed to constructors
Analysis & Theory
Class attributes are variables declared inside a class but outside any method or constructor.
What is the default value of an `int` attribute in a Java class?
Analysis & Theory
Java assigns default values to attributes. For `int`, the default is 0.
Which keyword is used to make an attribute belong to the class rather than instances?
Analysis & Theory
The `static` keyword makes the attribute shared among all instances of the class.
What is the output?
```java
class MyClass {
int x = 10;
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println(obj.x);
}
}```
Analysis & Theory
The object `obj` accesses its instance variable `x`, which is 10.
Can class attributes have access modifiers like `private`, `public`, or `protected`?
Analysis & Theory
Attributes can use any access modifier depending on visibility requirements.
Which keyword is used to prevent modification of an attribute after it's assigned?
Analysis & Theory
The `final` keyword makes a variable constant — it cannot be changed after initialization.
What is the output?
```java
class Test {
static int count = 5;
public static void main(String[] args) {
System.out.println(Test.count);
}
}```
Analysis & Theory
Static attribute `count` is accessed using the class name, and its value is 5.
Which of the following is true about instance attributes?
A
They can only be accessed from static methods
B
They are shared across all objects
C
Each object has its own copy
Analysis & Theory
Each object gets its own copy of instance (non-static) attributes.
What is the purpose of using `private` for class attributes?
A
To make them accessible everywhere
B
To hide them from outside classes and allow controlled access
C
To share them across all instances
D
To prevent garbage collection
Analysis & Theory
`private` restricts access, allowing encapsulation through getter and setter methods.
What is the output?
```java
class Book {
String title = "Java";
int pages;
}
class Main {
public static void main(String[] args) {
Book b = new Book();
System.out.println(b.pages);
}
}```
Analysis & Theory
`pages` is an uninitialized int instance variable, so its default value is 0.