Home Page > Learning the Java Language > Object-Oriented Programming Concepts
Home Page > Learning the Java Language > Language Basics > Operators, Expressions, Statements and Blocks, Control Flow Statements

Home Page > Learning the Java Language > Language Basics > Variables

kitt posted @ 2014年1月06日 16:55 in Java , 1384 阅读

简单总结语言基础 --> 变量

 

Variables(变量)

 

在Java中,field一般指下面的前两个, variable可指下面的全部. A type's fields, methods, and nested types are collectively called its members. 变量有这几类:

Instance Variables (Non-Static Fields)实例变量

    没有用关键字static声明, object存自己的状态, 每个类的实例的实例变量的值都不同.

Class Variables (Static Fields)类变量

    用static声明,不管类被实例化多少次,只有一个类变量. The code static int numGears = 6; would create such a   static field. 如果加上final关键字,则numGears的值永远不变。

Local Variables局部变量

    A method(方法) will often store its temporary state in local variables. 没有什么特定的关键词,主要看位置,也就是位于一个method的{}之中. 它只对声明它的方法可见, 类的其他部分无法访问局部变量. 

Parameters参数

    public static void main(String[] args). Here, the args variable is the parameter to this method. 参数总被划分为variable而不是fields.

 

Naming(命名)

 

变量名区分大小写,可以以下划线或$开头,  最好以字母开头,变量长度不限, 一般$不用. 使用整个单词而不要用缩写, 以增加代码可读性, 也起到注释的作用. 不能使用keyword(关键字),不能使用white space.

 

变量名只有一个单词时全部小写, 多个单词时第一个单词后面的单词全部首字母大写, 比如gearRatio, currentGear. 如果存的是常量, 则所有字母大写且用下划线间隔. 下划线一般只用于这个目的. static final int NUM_GEARS = 6

 

 

Primitive Data Type(原始数据类型)

 

Java is statically-typed = 所有变量先声明后使用. int gear = 1; 原始数据类型预先定义,用关键字声明,原始数据类型变量值不与其他原始类型分享状态. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Compiler never assigns a default value to an uninitialized local variable. 共8种原始类型:

byte (8 bit, signed, field默认值0):  -128 ~ 127, 大数组时比较省内存

short (16 bit, signed, field默认值0): -32768 ~ 32767, 也可以省内存

int (32, signed, field默认值0): -231 ~ 231-1

long (64, signed, field默认值0L): -263 ~ 263-1

float (field默认值0.0f): a single-precision 32-bit IEEE 754 floating point. Its range of values is in Floating-Point Types, Formats, and Values, 可以省内存. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. 

double (field默认值0.0d): a double-precision 64-bit IEEE 754 floating point. Its range of values is in Floating-Point Types, Formats, and Values. For decimal values, this data type is generally the default choice. This data type should never be used for precise values, such as currency.

boolean (大小没有被准确定义, field默认值false): 只有两个值true和false

char (16 bit, Unicode character, field默认值'\u0000'): '\u0000' (or 0) ~ '\uffff' (or 65,535)

 

Java provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable不可变, which means that once created, their values cannot be changed. 可以认为string也是一个原始类型,它的field默认值为null.

 

Literals(字面常数)

原始类型由Java本身提供, 不是由类创造出的对象. A literal is the source code representation of a fixed value. 字面常数不需计算.

 

boolean result = true;

char capitalC = 'C';

byte b = 100;

short s = 10000;

int i = 100000;

 

Integer Literals(整型字面常数)

以L或l结尾的是long类型(推荐用L),否则是int类型. 

// The number 26, in decimal

int decVal = 26;

//  The number 26, in hexadecimal

int hexVal = 0x1a;

// The number 26, in binary

int binVal = 0b11010;

 

Floating-Point Literals(浮点字面常数)

以F或f结尾的是float类型,没有或以D或d结尾的是double类型. 可以用E或e表示科学计数法.

double d1 = 123.4;

// same value as d1, but in scientific notation

double d2 = 1.234e2;

float f1  = 123.4f;

 

Character and String Literals字符和字符串字面常数

可包含任意Unicode(UTF-16)字符. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u0108'  Always use 'single quotes' for char literals and "double quotes" for String literals. Escape sequence(转义序列) \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).

 

null字面常数: can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence.

 

class字面常数:类型名称+”.class"  (例如String.class) This refers to the object (of type Class) that represents the type itself.

 

Using Underscore Characters in Numeric Literals在数值字面常数中使用下划线

Java SE 7及后续版本中, 数值字面常数中的数字之间可以使用任意数量的下划线, 以提高代码可读性. 下划线不能用于开头和结尾, 小数点附近, F或L后缀的前面, 字符串或数字应该出现的位置.

 

long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi =  3.14_15F;

long hexBytes = 0xFF_EC_DE_5E;

long hexWords = 0xCAFE_BABE;

long maxLong = 0x7fff_ffff_ffff_ffffL;

byte nybbles = 0b0010_0101;

long bytes = 0b11010010_01101001_10010100_10010010;

 

// Invalid: cannot put underscores adjacent to a decimal point

float pi1 = 3_.1415F;

// Invalid: cannot put underscores adjacent to a decimal point

float pi2 = 3._1415F;

// Invalid: cannot put underscores prior to an L suffix

long socialSecurityNumber1 = 999_99_9999_L;

 

// This is an identifier, not a numeric literal

int x1 = _52;

// OK (decimal literal)

int x2 = 5_2;

// Invalid: cannot put underscores at the end of a literal

int x3 = 52_;

// OK (decimal literal)

int x4 = 5_______2;

 

// Invalid: cannot put underscores in the 0x radix prefix

int x5 = 0_x52;

// Invalid: cannot put underscores at the beginning of a number

int x6 = 0x_52;

// OK (hexadecimal literal)

int x7 = 0x5_2; 

// Invalid: cannot put underscores at the end of a number

int x8 = 0x52_;

 

Arrays(数组)

数组元素个数固定, 单一类型. Each item in an array is called an element元素, and each element is accessed by its numerical index数组下标. The length of an array is established when the array is created. After creation, its length is fixed. 

 

class ArrayDemo {

    public static void main(String[] args) {

        // declares an array of integers

        int[] anArray;

 

        // allocates memory for 10 integers

        anArray = new int[10];

           

        // initialize first element

        anArray[0] = 100;

        // initialize second element

        anArray[1] = 200;

        // and so forth

        anArray[2] = 300;

        anArray[3] = 400;

        anArray[4] = 500;

        anArray[5] = 600;

        anArray[6] = 700;

        anArray[7] = 800;

        anArray[8] = 900;

        anArray[9] = 1000;

 

        System.out.println("Element at index 0: " + anArray[0]);

        System.out.println("Element at index 1: " + anArray[1]);

        System.out.println("Element at index 2: " + anArray[2]);

        System.out.println("Element at index 3: " + anArray[3]);

        System.out.println("Element at index 4: " + anArray[4]);

        System.out.println("Element at index 5: " + anArray[5]);

        System.out.println("Element at index 6: " + anArray[6]);

        System.out.println("Element at index 7: " + anArray[7]);

        System.out.println("Element at index 8: " + anArray[8]);

        System.out.println("Element at index 9: " + anArray[9]);

    }

 

Output:

Element at index 0: 100

Element at index 1: 200

Element at index 2: 300

Element at index 3: 400

Element at index 4: 500

Element at index 5: 600

Element at index 6: 700

Element at index 7: 800

Element at index 8: 900

Element at index 9: 1000

 

The declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type. 

 

// this form is discouraged

float anArrayOfFloats[];

 

Creating, Initializing, and Accessing an Array(数组的创建,初始化与访问)

 

使用new,anArray = new int[10];

也可以 int[] anArray = {100, 200, 300, 400, 500}; 长度为5

也可创建multidimensional array多维数组,String[][] names  

Rows are allowed to vary in length.

 

class MultiDimArrayDemo {

    public static void main(String[] args) {

        String[][] names = {

            {"Mr. ", "Mrs. ", "Ms. "},

            {"Smith", "Jones"}

        };

        // Mr. Smith

        System.out.println(names[0][0] + names[1][0]);

        // Ms. Jones

        System.out.println(names[0][2] + names[1][1]);

    }

}

 

Output:

Mr. Smith

Ms. Jones

 

查看数组大小 System.out.println(anArray.length);

 

Copying Arrays 数组的拷贝

 

The System class has an arraycopy() method that you can use to efficiently copy data from one array into another:

 

public static void arraycopy(Object src, int srcPos,

                             Object dest, int destPos, int length)

 

class ArrayCopyDemo {

    public static void main(String[] args) {

        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',

    'i', 'n', 'a', 't', 'e', 'd' };

        char[] copyTo = new char[7];

 

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);

        System.out.println(new String(copyTo));

    }

}

 

Output:

caffein

 

Array Manipulations数组的操作

Java SE提供了常用数组操作(copying, sorting, searching), ing arrays)  java.util.Arrays. CopyOfRange() method does not require you to create the destination array before calling the method:

 

class ArrayCopyOfDemo {

    public static void main(String[] args) {

        

        char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',

            'i', 'n', 'a', 't', 'e', 'd'};

            

        char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);

        

        System.out.println(new String(copyTo));

    }

}

 

java.util.Arrays中一些有用的操作:

binarySearch() 

    Searching an array for a specific value to get the index at which it is placed

equals() 

    Comparing two arrays to determine if they are equal or not

fill() 

    Filling an array to place a specific value at each index

sort() 

    Sorting an array into ascending order. This can be done either sequentially, using the sort() method, or concurrently, using the parallelSort() method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.

Avatar_small
ididi 说:
2014年6月18日 12:02

dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter