3.4. Variables
In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. Here are some examples:

double salary;
int vacationDays;
long earthPopulation;
boolean done;

Notice the semicolon(分号)at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.
A variable name must begin with a letter and must be a sequence of letters or digits. Note that the terms "letter" and "digit" are much broader in Java than in most languages. A letter is defined as 'A'–'Z', 'a'–'z', '_', '$', or any Unicode character that denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a π. Similarly, digits are '0'–'9' and any Unicode characters that denote a digit in a language. Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. All characters in the name of a variable are significant and case is also significant. The length of a variable name is essentially unlimited.


Tip
If you are really curious as to what Unicode characters are "letters" as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.
Tip
Even though $ is a valid Java letter, you should not use it in your own code. It is intended for names that are generated by the Java compiler and other tools.


You also cannot use a Java reserved word for a variable name. (See the Appendix for a list of reserved words.)

You can have multiple declarations on a single line:

int i, j; // both are integers

However, we don’t recommend this style. If you declare each variable separately, your programs are easier to read.


Note

As you saw, names are case sensitive, for example, hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name as the type, for example
Box box; // "Box" is the type and "box" is the variable name
Other programmers prefer to use an “a” prefix for the variable:
Box aBox;


3.4.1. Initializing Variables
After you declare a variable, you must explicitly initialize it by means of an assignment statement—you can never use the value of an uninitialized variable(声明一个变量后必须要初始化). For example, the Java compiler flags the following sequence of statements as an error:

int vacationDays;
System.out.println(vacationDays); // ERROR--variable not initialized

You assign to a previously declared variable by using the variable name on the left, an equal sign (=), and then some Java expression with an appropriate value on the right.

int vacationDays;
vacationDays = 12;

You can both declare and initialize a variable on the same line. For example:

int vacationDays = 12;

Finally, in Java you can put declarations anywhere in your code(可以在任意地方声明变量). For example, the following is valid code in Java:

double salary = 65000.0;
System.out.println(salary);
int vacationDays = 12; // OK to declare a variable here

In Java, it is considered good style to declare variables as closely as possible to the point where they are first used.


C++ Note
C and C++ distinguish between the declaration and definition of a variable. For example,
int i = 10;
is a definition, whereas
extern int i;
is a declaration. In Java, no declarations are separate from definitions.


3.4.2. Constants
In Java, you use the keyword final to denote a constant(使用final关键字来声明产量). For example:

public class Constants
{
public static void main(String[] args)
{
final double CM_PER_INCH = 2.54;
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);
}
}

The keyword final indicates that you can assign to the variable once, and then its value is set once and for all. It is customary to name constants in all uppercase.
It is probably more common in Java to create a constant so it's available to multiple methods inside a single class. These are usually called class constants(类常量). Set up a class constant with the keywords static final. Here is an example of using a class constant:

public class Constants2
{
public static final double CM_PER_INCH = 2.54;
public static void main(String[] args)
{
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);
}
}

Note that the definition of the class constant appears outside the main method. Thus, the constant can also be used in other methods of the same class. Furthermore, if the constant is declared, as in our example, public, methods of other classes can also use it—in our example, as Constants2.CM_PER_INCH.


C++ Note
const is a reserved Java keyword, but it is not currently used for anything(const是Java中的一个关键字,但是没有使用). You must use final for a constant.


Core Java Volume I — 3.4. Variables的更多相关文章

  1. Core Java Volume I — 1.2. The Java "White Paper" Buzzwords

    1.2. The Java "White Paper" BuzzwordsThe authors of Java have written an influential White ...

  2. Core Java Volume I — 4.7. Packages

    4.7. PackagesJava allows you to group classes in a collection called a package. Packages are conveni ...

  3. Core Java Volume I — 4.10. Class Design Hints

    4.10. Class Design HintsWithout trying to be comprehensive or tedious, we want to end this chapter w ...

  4. Core Java Volume I — 3.10. Arrays

    3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You ac ...

  5. Core Java Volume I — 3.8. Control Flow

    3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...

  6. Core Java Volume I — 5.1. Classes, Superclasses, and Subclasses

    5.1. Classes, Superclasses, and SubclassesLet's return to the Employee class that we discussed in th ...

  7. Core Java Volume I — 4.6. Object Construction

    4.6. Object ConstructionYou have seen how to write simple constructors that define the initial state ...

  8. Core Java Volume I — 4.5. Method Parameters

    4.5. Method ParametersLet us review the computer science terms that describe how parameters can be p ...

  9. Core Java Volume I — 4.4. Static Fields and Methods

    4.4. Static Fields and MethodsIn all sample programs that you have seen, the main method is tagged w ...

随机推荐

  1. JSP 服务器响应

    Response响应对象主要将JSP容器处理后的结果传回到客户端.可以通过response变量设置HTTP的状态和向客户端发送数据,如Cookie.HTTP文件头信息等. 一个典型的响应看起来就像下面 ...

  2. eclipse-mysql-tomcat bug之旅

    赶紧默念三遍google大法好... [连接数据库 servlet调用提示找不到可加载的driver,普通的.java文件没问题] 表示不服啊...明明可以连上啊...为什么多了几个中间界面就不好使了 ...

  3. 学习记录012-NFS

    1.Network file System 主要是通过网络让不同的主机进行通信,构建于ip协议之上的现代文件系统,用来存储共享视频,图片,文件等 2.并发大的时候会有点问题(维护不好会丢数据) 3.N ...

  4. 利用百度地图开源sdk获取地址信息。

    注册百度开发者帐号,下载相关sdk 添加权限: 添加百度注册访问应用(AK)码 添加源代码文件到libs文件: 代码如下: package com.lixu.baidu_gps; import com ...

  5. GET /hello/fred/0926xxx572

    GET /hello/fred/0926xxx572 app.get('/hello/:name/:tel', function(req, res) { console.log(req.params. ...

  6. NOIP2013 提高组day2 3 华容道 BFS

    描述 小 B 最近迷上了华容道,可是他总是要花很长的时间才能完成一次.于是,他想到用编程来完成华容道:给定一种局面,华容道是否根本就无法完成,如果能完成,最少需要多少时间. 小 B 玩的华容道与经典的 ...

  7. 跨域SSO的实现

    翻译自CodeProject网站ASP.NET9月份最佳文章:Single Sign On (SSO) for cross-domain ASP.NET applications. 翻译不妥之处还望大 ...

  8. iOS开发中关于nslog的几种流行做法小结

    不管哪种方法,都必须在PCH文件中做下宏定义 DEBUG和RELEASE要分开,RELEASE时log打印要取消 方法一:简单直接,用几行代码搞定,简洁但功能少 #ifdef DEBUG #defin ...

  9. struts2内Action方法调用

    1.struts2流程: jsp页面-->web.xml-->struts.xml-->user.acrion-->UserAction.java 中的execute()--r ...

  10. 2013年7月份第1周51Aspx源码发布详情

    启睿网络信息服务器实例源码  2013-7-5 [ VS2005 ]功能介绍:睿网络信息服务器,QiRui Net Information Services简称QRNIS,该软件前身系KCIS.当前版 ...