Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Final Keyword | Deep Java Structure
Java Extended

book
Final Keyword

How to prevent changing the value of a variable

For this purpose, Java has a keyword called final. Let's consider a code snippet where we use this keyword:

Main.java

Main.java

copy
package 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);
}
}
123456789101112
package 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 final keyword;

  • 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.

Task

Swipe to start coding

Your task is to add the final keyword before the variables that are not modified later in the code.

Solution

solution.java

solution.java

package com.example;

public class Main {
public static void main(String[] args) {
// initializing variables
int a = 9;
final int b = 15;
int c = 21;
int d = -62;
final int e = 0;
// performing mathematical operations on the variables
c = c + 9;
d = d - 8;
a = a + 1;
int result = a + b + c + d + e;
// displaying the result
System.out.println(result);
}
}
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 3
single

single

package com.example;

public class Main {
public static void main(String[] args) {
// initializing variables
int a = 9;
int b = 15;
int c = 21;
int d = -62;
int e = 0;
// performing mathematical operations on the variables
c = c + 9;
d = d - 8;
a = a + 1;
int result = a + b + c + d + e;
// displaying the result
System.out.println(result);
}
}

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt