---
title: "java中final关键字的使用"
author: "yoyo08"
date: "2013-05-31T10:04:15Z"
tags: []
categories: ["编程语言"]
slug: "java-final"
draft: false
lastmod: "2013-05-31T10:10:25Z"
id: 1880435
url: "https://yoyo08.iteye.com/blog/1880435"
---

**java中final关键字的使用**

**1. 用final修饰基本数据类型**

 

```
public class Test {   
	  
    public void test() {   
        final int a = 2;   
        a = 3;   
  
        final String s = "2";   
        s = "3";   
    }   
  
    public void test(final int a, final String s) {   
        a = 3;  
        s = "3";
    }   
} 
```

    
这两个方法中都会提示编译错误：The final local variable s cannot be assigned. It must be blank and not using a compound assignment

**2. 用final修饰引用类型**

 

```
public class Test {

	public void test() {
		final StringBuffer buffer = new StringBuffer("1");
		buffer = new StringBuffer("2");
	}

	public void test(final StringBuffer buffer) {
		buffer = new StringBuffer("2");
	}
}
```

 

这两个方法中都会提示编译错误：The final local variable s cannot be assigned. It must be blank and not using a compound assignment

但是，用final修饰的引用类型的值却是可以改变的。下面的使用方式是正确的。

 

```
public class Test {

	public void test() {
		final StringBuffer buffer = new StringBuffer("1");
		buffer.append("**");
	}

	public void test(final StringBuffer buffer) {
		buffer.append("%%");
	}
}
```