0
0
Javaprogramming~10 mins

Instance variables in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an instance variable named age of type int.

Java
public class Person {
    [1] age;
}
Drag options to blanks, or click blank then click option'
Astatic
Bint
Cvoid
Dfinal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using static makes the variable shared by all objects, not an instance variable.
Using void is only for methods, not variables.
2fill in blank
medium

Complete the code to assign the value 25 to the instance variable age inside the constructor.

Java
public class Person {
    int age;
    public Person() {
        [1] = 25;
    }
}
Drag options to blanks, or click blank then click option'
Athis.age
Bage()
CPerson.age
Dstatic age
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using age() which looks like a method call.
Using Person.age which is for static variables.
3fill in blank
hard

Fix the error in the code by completing the declaration of the instance variable name of type String.

Java
public class Person {
    [1] name;
}
Drag options to blanks, or click blank then click option'
Afinal int
Bstatic String
Cvoid String
DString
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using static String makes it a class variable, not an instance variable.
Using void String is invalid syntax.
4fill in blank
hard

Fill both blanks to complete the constructor that sets the instance variables name and age.

Java
public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = [1];
        this.age = [2];
    }
}
Drag options to blanks, or click blank then click option'
Aname
Bage
C"name"
D0
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Assigning string literals like "name" instead of the parameter name.
Assigning zero 0 instead of the parameter age.
5fill in blank
hard

Fill all three blanks to complete the method that returns a description using instance variables name and age.

Java
public class Person {
    String name;
    int age;

    public String getDescription() {
        return [1] + " is " + [2] + [3];
    }
}
Drag options to blanks, or click blank then click option'
Aname
Bage
C " years old"
D"Hello"
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using string literals instead of variables for name or age.
Forgetting to add the descriptive text like " years old".