In Java, the final keyword prevents a variable’s value from being changed after assignment, but its behavior differs for primitives and object references. For primitive variables, final makes the value constant, as in final int MAX_SPEED = 100; where reassignment causes an error. For object references, final locks the reference, not the object — so while names.add("Alice") is allowed, reassigning names to a new object is not. Final variables help avoid accidental changes, improve thread safety, enhance code clarity, and are required for variables used in anonymous inner classes. They can also be initialized later (blank finals) or set in constructors to allow flexible immutable classes. Thus, final ensures either a constant value or a fixed reference, aiding in cleaner and safer code.
In Java, when you use the final
keyword with a variable, it means that the variable's value cannot be changed after it’s assigned. That might sound simple, but there are some nuances depending on whether the variable is a primitive type or an object reference.
final
with Primitive Variables
When you declare a primitive variable (like int
, double
, or boolean
) as final
, its value becomes constant — you can't assign a new value to it after initialization.
final int MAX_SPEED = 100; MAX_SPEED = 120; // Compilation error!
This is straightforward: once set, the value stays the same. It’s useful for constants in your code, like configuration values or limits that shouldn’t change during execution.
final
with Object References
Here’s where things get a bit tricky. If you mark an object reference as final
, what exactly is fixed?
final List<String> names = new ArrayList<>(); names.add("Alice"); // This is fine names = new ArrayList<>(); // Compilation error
- The reference can't be changed — meaning you can't assign a new object to
names
. - But the object itself can still be modified — so adding or removing elements from the list is allowed.
So, final
here doesn't make the object immutable, only the reference to it.
When and Why to Use final
for Variables
There are a few practical reasons to use final
:
- Avoid accidental reassignment: Especially helpful in large methods or complex logic.
- Immutability and thread safety: Final variables are easier to reason about in multi-threaded environments.
- Clarity and readability: Signals to other developers (and to yourself) that this variable isn’t meant to change.
Some common places where final
shines:
- Constants (
public static final
) - Local variables used in anonymous inner classes (they must be final or effectively final)
- Configuration values inside methods
You’ll often see it used in defensive coding styles or when building immutable objects.
A Few Things to Keep in Mind
- You don’t always have to assign a value at the time of declaration.
- A
final
variable can be initialized later, but only once — this is called a blank final. - In constructors,
final
fields can be assigned during object creation, which helps build flexible immutable classes.
For example:
public class Person { private final String name; public Person(String name) { this.name = name; // Allowed once in constructor } }
This lets each instance have its own constant name
.
So, basically, using final
on a variable locks its value or reference, depending on the type. It’s not complicated, but it does help write cleaner and safer code if used wisely.
The above is the detailed content of What is the `final` keyword for variables?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Environment variables are the path to the location (or environment) where applications and programs run. They can be created, edited, managed or deleted by the user and come in handy when managing the behavior of certain processes. Here's how to create a configuration file to manage multiple variables simultaneously without having to edit them individually on Windows. How to use profiles in environment variables Windows 11 and 10 On Windows, there are two sets of environment variables – user variables (apply to the current user) and system variables (apply globally). However, using a tool like PowerToys, you can create a separate configuration file to add new and existing variables and manage them all at once. Here’s how: Step 1: Install PowerToysPowerTo

Strict mode was introduced in PHP7, which can help developers reduce potential errors. This article will explain what strict mode is and how to use strict mode in PHP7 to reduce errors. At the same time, the application of strict mode will be demonstrated through code examples. 1. What is strict mode? Strict mode is a feature in PHP7 that can help developers write more standardized code and reduce some common errors. In strict mode, there will be strict restrictions and detection on variable declaration, type checking, function calling, etc. Pass

The difference between final, finally, and finalize in Java requires specific code examples. In Java programming, you often encounter the three keywords final, finally, and finalize. Although they are spelled similarly, they have different meanings and usages. This article will explain the differences between these three keywords in detail and give code examples to help readers better understand. 1. Final keyword The final keyword can be used for classes, methods and variables. Its function is to make the modified class

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

A constant variable is a variable whose value is fixed and only one copy exists in the program. Once you declare a constant variable and assign a value to it, you cannot change its value again throughout the program. Unlike other languages, Java does not directly support constants. However, you can still create a constant by declaring a variable static and final. Static - Once you declare a static variable, they will be loaded into memory at compile time, i.e. only one copy will be available. Final - Once you declare a final variable, its value cannot be modified. Therefore, you can create a constant in Java by declaring the instance variable as static and final. Example Demonstration classData{&am

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery is a JavaScript library widely used in web development. It provides many simple and convenient methods to operate web page elements and handle events. In actual development, we often encounter situations where we need to determine whether a variable is empty. This article will introduce several common methods of using jQuery to determine whether a variable is empty, and attach specific code examples. Method 1: Use the if statement to determine varstr="";if(str){co
