---
title: "【Java】final和常量之间的关系（个人理解）"
author: "JavaPerl"
date: "2010-12-15T10:36:40Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "java-final"
draft: false
lastmod: "2010-12-15T10:37:12Z"
id: 842536
url: "https://javaperl.iteye.com/blog/842536"
---

Java中用final来定义一个引用引用一个对象后就不能再被用来引用其他对象（基本数据类型也一样），但是允许引用的对象改变。举个例子来说：

```java

final StringBuilder str = new StringBuilder("hello");
str.append(" world");
System.out.println(str);
```

上面的代码是允许的。因为str始终只引用了唯一的一个StringBuilder对象。所以输出结果为hello world。
如果代码这样写：

```java

final StringBuilder str = new StringBuilder("hello");
str = new StringBuilder("hello world");
```

这个时候是不能通过编译的。
简单来说，final后的变量只能进行一次赋值，这次赋值可以发生在声明时，也可以在声明后。