Static Variables Flashcards

1
Q

Give me the definition of a final static variable !

A

a final static variable is a variable that belongs to the class itself and that can only be initialized once , either inline or in a static initializer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give the naming conventions of a final variable !

A

The recommended naming conventions for a final variable in Java are:

  • The final variable should be in capital letters.
  • If it is composed of multiple words, they should be separated by underscores
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give an example that results in a compilation error and run it !

A

EXAMPLE :

public class Initializers {
private static final int NUM_BUCKETS = 45;
public static void main(String[] args) {
NUM_BUCKETS = 5; /* DOES NOT COMPILE */
} }

NOTE :
The compiler will make sure that you do not accidentally try to update a final variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give a characteristic of final variables when it comes to collections like ArrayList !

A

When it comes to collections like ArrayList if we declare a reference variable of type ArrayList as final, we can add values to that arraylist and remove values from it, the only thing that you’re not allowed to do is assign the reference variable to a new object.

Key Concepts :

  • Final Reference: A final reference variable cannot be reassigned after it has been initialized.
  • Mutable Object: The object referenced by a final reference variable can still be changed if it is mutable. This means you can modify the object’s state using its methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give 2 examples (one of them results in a compilation error) !

A

EXAMPLE 1 :
private static final ArrayList<String> values = new ArrayList<>();
public static void **main(String[] args)** {
values.add("changed"); /* It actually does compile */
}</String>

EXAMPLE 2 :

public class Limits {

static final ArrayList <Integer> values=new ArrayList<> ();
static public void **main(String[] args)** {
/* TODO Auto-generated method stub */</Integer>

	 ArrayList <Integer>   values2=new ArrayList<>  ();
	 values=values2; /* The final field Limits.values can not be
             assigned */
	
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly