Final Keyword
How to Prevent Changing the Value of a Variable in Java
For this purpose, Java has a keyword called final. Let's consider a code snippet where we use this keyword:
Main.java
123456789101112package com.example; public class Main { public static void main(String[] args) { int number = 10; final int finalNumber = 5; number = 15; finalNumber = 20; System.out.println(number); System.out.println(finalNumber); } }
You can see that in the code above, we have created two variables of type int, but one of them is marked with the final keyword. When we try to change the value of this variable, the compiler tells us about an error. Specifically, it indicates that we cannot modify a value that is marked with the final keyword.
What can we use final keyword for:
-
To create constants. A constant is a variable whose value cannot be changed after it has been initialized. In Java, constants are always declared using the
finalkeyword; -
To indicate that the value of a variable is final and should not be modified;
-
To prevent accidental modification of a final variable's value in our code.
Swipe to start coding
Your task is to add the final keyword before the variables that are not modified later in the code.
Oplossing
Bedankt voor je feedback!
single
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Geweldig!
Completion tarief verbeterd naar 6.67
Final Keyword
Veeg om het menu te tonen
How to Prevent Changing the Value of a Variable in Java
For this purpose, Java has a keyword called final. Let's consider a code snippet where we use this keyword:
Main.java
123456789101112package com.example; public class Main { public static void main(String[] args) { int number = 10; final int finalNumber = 5; number = 15; finalNumber = 20; System.out.println(number); System.out.println(finalNumber); } }
You can see that in the code above, we have created two variables of type int, but one of them is marked with the final keyword. When we try to change the value of this variable, the compiler tells us about an error. Specifically, it indicates that we cannot modify a value that is marked with the final keyword.
What can we use final keyword for:
-
To create constants. A constant is a variable whose value cannot be changed after it has been initialized. In Java, constants are always declared using the
finalkeyword; -
To indicate that the value of a variable is final and should not be modified;
-
To prevent accidental modification of a final variable's value in our code.
Swipe to start coding
Your task is to add the final keyword before the variables that are not modified later in the code.
Oplossing
Bedankt voor je feedback!
single