02-02.JAVA语言基础

来源:互联网 发布:如何在网络上做推广 编辑:程序博客网 时间:2024/06/07 03:44

01.变量 (Variables)


JAVA语言是静态类型语言,所有变量在使用之前,必须进行声明,包括指定变量的数据类型(基本数据类型和引用类型)和名称。

01)变量类型:
a.  实例变量(Instance Variables 或 Non-Static Fields

b.  静态变量(Class Variables 或 Static Fields)

  用static修饰符修饰的变量。不管该类被实例化多少次,静态变量存储的数据只有一份,且被该类所有实例共享。

c.变量部(Local Variables

  在方法中声明的变量。

d.参数(Parameters 

  在方法、构造器或者try-catch语句中用来接收传入值的变量。

02)命名规则:

a.字母区分大小写,不限长度,Unicode字符。以字母、$符、下划线开头。(按照惯例,通常以字母开头)

b.随后的字符可以是字母、数字、$符和下划线。单词用全拼,这样可增加代码的易读性。不能单独使用JAVA关键字(如:public )或保留字(如:goto和const)。

c.若只含一个单词,所有字母小写。若含多个单词,从第一个单词以后的所有单词首字母大写,剩余字母全部小写。若是常量名,则所有字母大写,并且单词之间用下划线隔开。


01-01. 基本数据类型 (Primary Data Types)


a. 八种基本数据类型:

byte      8位有符号二进制补码    -2^7~2^7-1    

short   16位有符号二进制补码    -2^15~2^15-1

int       32位有符号二进制补码    -2^31~2^31-1

long    64位有符号二进制补码    -2^63~2^63-1

float    单精度32位IEEE754浮点数

double   双精度64位IEEE754浮点数

char    16位Unicode编码字符    "\u0000"~"\uffff"

boolean  布尔类型      true/false

除了八种基本数据类型,其他的都是引用类型,如:字符串、数组等。


b. 默认值 (Default Values)

如果实例变量在声明时未赋值(初始化),编译器会为该变量设置一个默认初始值。

Data TypeDefault Value (for fields)byte0short0int0long0Lfloat0.0fdouble0.0dchar'\u0000'String (or any object)  nullbooleanfalse

c. 字面量 (Literals)

代码中直接赋给变量的值。

1.整数字面量

如果是以“L”或“l”结尾,该字面量是long类型,其他情况则是int类型。支持十进制、十六进制(在数字前加“0x”)和二进制(数字前加“0b”,在JavaSE7及其以后支持)。在这里存在类型自动(隐含)转换问题。如:

byte  b  =  9;字面量9的数据类型是int类型,编译器会把它转换成byte类型。若字面量超出byte或者int的范围,eclipse工具就会报编译错误。(short和char类型同理)

byte  b  =  128;128已经超过了byte的最大值127,eclipse工具会报“Type mismatch:cannot convert from int to byte”的错误。

long  lon  =  2147483648;2147483648已经超出了int的最大值2147483647,eclipse工具会报“The literal 2147483648 of type int is out of range”的错误。

2.浮点数字面量

如果是以“F”或“f”结尾,该字面量是float类型,其他情况是double类型(后缀“D”或“d”可省)。

此处无类型自动转换,如果变量是float类型的,赋给的字面量必须以“F”或“f”结尾,否则会报编译错误。

3.字符和字符串字面量

char  c = ‘s’;字符用单引号

String  s = “string”;字符串用双引号

支持转义字符:\b (backspace), \t(tab), \n (line feed(换行字符)), \f (form feed(换页)), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).

null是一个特殊的字面量,表示引用类型变量未指向任何一个对象。

4.class 字面量

There's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.


01-02. 数组 (Array)


数组:有序存放固定数量同类型数据的容器对象

      数组长度(数组中元素总个数)在创建时就已确定,一旦创建长度不可改变。

      每个元素都有对应的数字下标,下标从0开始,下标0对应第一个元素,下标1对

      应第二个元素,以此类推。


a. 声明指向数组的变量

同声明基本类型变量一样,要指定变量的数据类型和名称,数据类型既可以是基本类型也可以是引用类型,并且数据类型名后加“[]”以示该变量指向的是一个数组。例如:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
以下方式(将“[]”放在变量名称后)也可以但不推荐使用:
int  anArrayOfInt[];

b. 创建、初始化和访问数组

创建数组的三种方式:

1) new  int[3]; 仅指定了数组的长度,编译器会将所有元素设置为该元素类型相对应的默认值。该例实际上是创建了一个长度为3,元素都为0的数组。

2) new  int[]{1,2,3};

3) int[] anArray = {1,2,3};该方式必须和变量的声明同时使用。

通过数组下标访问数组:

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
多维数组:
数组的元素也是数组,实际可看作数组的嵌套,同C语言的多维数组不同。
元素数组的长度可不尽相同,例如:

class MultiDimArrayDemo {
    public static void main(String[] args) {
       triSng[][] 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]);
    }
}

The output from this program is:

Mr. Smith
Ms. Jones

c. 数组复制

java.lang.System类提供了一个arraycopy()方法,可以高效的将一个数组的数据复制到另一个数组。

public static void arraycopy(Object src, int srcPos,
                             Object dest, int destPos, int length)
src:源数组

dest:目标数组

srcPos:源数组起始下标

destPos:目标数组起始下标

length:要复制元素的个数


d. 数组操作

java还提供了操作数组的工具类:java.util.Arrays

该类包含数组的复制、排序、查找等常用方法。


02. 运算符 (Operators)


运算符的优先级(从高到低):

Operator PrecedenceOperatorsPrecedencepostfixexpr++ expr--unary++expr --expr +expr -expr ~ !multiplicative* / %additive+ -shift<< >> >>>relational< > <= >= instanceofequality== !=bitwise AND&bitwise exclusive OR^bitwise inclusive OR|logical AND&&logical OR||ternary? :assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

02-01. 赋值,算数,一元运算符


a. 简单赋值运算符 (The Simple Assignment Operator):

  =  将该符号右边的值赋给左边的变量

b. 算数运算符 (The Arithmetic Operators)

  +  加法运算符(也用作字符串的连接符)
  -  减法运算符
  *  乘法运算符
  /  除法运算符(若是整数运算,结果取整,如:int num = 9/4; num的值为2)
  %  取余运算(如:int num = 9%4;num的值为1)

c. 一元运算符 (The Unary Operators)

  +  正号(一般情况省略)
  -  负号
  ++ 自增符号(每次加1)
  -- 自减符号(每次减1)
  ! 逻辑求补运算符(即,将一个布尔值取反)
  自增和自减符号既可以放在操作数前(如:++result)又可以放在操作数后(如:result++)。如果单独作为一个表达式,对结果无影响;如果是作为表达式或语句的一部分,是有区别的。前者用自增或自减的结果来参与整个表达式的运算,而后者是用原始值参与表达式的运算,如下所示:
class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;              
        // prints 5
        System.out.println(i);
        // prints 6
        System.out.println(++i);
        // prints 6
        System.out.println(i++);
        // prints 7 说明i已经进行了自增运算,但上条代码中i++是语句的一部分,所以上条输出语句输出结果为原始值:6
        System.out.println(i);
    }
}

02-02. 判等,关系和条件运算符


a. 判等和关系运算符 (The Equality and Relational Operators

==      等于 equal to
!=      不等于 not equal to
>       大于 greater than
>=      大于或等于 greater than or equal to
<       小于 less than
<=      小于或等于 less than or equal to

b. 条件运算符 (The Conditional Operators

&&   与  Conditional-AND  两表达式同时为true,结果才为true,其余情况都为false
||   或  Conditional-OR   两表达式同时为false,结果才为false,其余情况都为true

二者具有“短路效应”,只有在必要的情况下才去判断第二个表达式的真假。
例如:boolean bool = expr1 && expr2;若expr1的值为false,就可以得出最后结果,不会再去判断expr2的值。
如果用&和|,任何情况下,都会判断所有的表达式。

?: 三元运算符 可看作是if-then-else语句的简写版 
result = someCondition ? value1 : value2;
若someCondition=true,则result=true,否则result=value2

c. 类型判断运算符 (The Type Comparison Operator

   instanceof  用来判断对象是否是一个类或其子类,接口的实例,用法如下:

class InstanceofDemo {
    public static void main(String[] args) {
 
        Parent obj1 = new Parent();
        Parent obj2 = new Child();
 
        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}
 
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

Output:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

02-03. 按位运算符和位移运算符


~   按位取反
<<   左移(最低位补零)
>>   右移(最高位保持原数)
>>>  逻辑右移(最高位补零)
&    按位与
^    按位异或
|    按位或


03.表达式, 语句, 语句块


表达式 (Expressions)

由变量,运算符和方法调用组成,并能产生一个结果。运算的顺序由运算符的优先级决定,也可使用()改变表达式的运算顺序。


语句 (Statements)

语句是一个完整的执行单元,下面的表达式加上分号(;)可构成一个语句。


赋值表达式(Assignment expressions)
自增自减表达式(Any use of ++ or --)
方法调用(Method invocations)
对象创建(Object creation expressions)

这样的语句叫做表达式语句(Expression Statements),下面是一些例子:

// assignment statement

aValue = 8933.234;

// increment statement

aValue++;

// method invocation statement

System.out.println("Hello World!");

// object creation statement

Bicycle myBike = new Bicycle();


除了表达式语句,还有两种:
声明语句(Declaration Statements)
流程控制语句(Control Flow Statements)

语句块 (Blocks)

block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example,BlockDemo, illustrates the use of blocks:
class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) {
// begin block 1
               System.out.println("Condition is true.");
          }
// end block one          else { // begin block 2
               System.out.println("Condition is false.");
          }
// end block 2
     }
}


04.流程控制语句 (Control Flow Statements)


流程控制语句:
1)决策语句 decision-making statements (if-thenif-then-elseswitch),
2)循环语句 the looping statements (forwhiledo-while),
3)分支语句  the branching statements (breakcontinuereturn


04-01. if-then和if-then-else语句


a. if-then语句

需要程序先要测试if语句中的表达式,只有表达式的值true,才执行then语句中的代码,否则,跳过then语句。例如:

void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}
只有isMoving=true,才会执行then语句。

如果then语句中只含有一条语句,那么大括号可以省略,如上面的例子可以改成如下形式:

void applyBrakes() {
    // same as above, but without braces
    if (isMoving)
        currentSpeed--;
}

b. if-then-else语句

void applyBrakes() {
    if (isMoving) {
        currentSpeed--;
    } else {
        System.err.println("The bicycle has already stopped!");
    }
}

class IfElseDemo {

    public static void main(String[] args) {
 
        int testscore = 76;
        char grade;
 
        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

The output from the program is:

    Grade = C

04-02. Swicth语句


  public class SwitchDemo {
    public static void main(String[] args) {
 
        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

In this case, August is printed to standard output.


class SwitchDemo2 {
    public static void main(String[] args) {
 
        int month = 2;
        int year = 2000;
        int numDays = 0;
 
        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) &&
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

在switch语句中使用字符串
public class StringSwitchDemo {
 
    public static int getMonthNumber(String month) {
 
        int monthNumber = 0;
 
        if (month == null) {
            return monthNumber;
        }
 
        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1; break;
            case "february":
                monthNumber = 2; break;
            case "march":
                monthNumber = 3;break;
            case "april":
                monthNumber = 4;break;
            case "may":
                monthNumber = 5;break;
            case "june":
                monthNumber = 6;break;
            case "july":
                monthNumber = 7;break;
            case "august":
                monthNumber = 8;break;
            case "september":
                monthNumber = 9;break;
            case "october":
                monthNumber = 10;break;
            case "november":
                monthNumber = 11;break;
            case "december":
                monthNumber = 12;break;
            default:
                monthNumber = 0;break;
        }
        return monthNumber;
    }
 
    public static void main(String[] args) {
        String month = "August";
 
        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);
 
        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

The output from this code is 8.


04-03. while和do-while语句


a.  while语句

   while (expression) {

    statement(s)
}

b.  do-while语句

do {
     statement(s)
} while (expression);


04-04. for语句


for (initialization;termination;increment/decrement) {
   statement(s)
}
1)initialization初始化条件,仅执行一次,并且是for循环语句的开始。
2)接下来执行termination表达式(循环条件),若表达式为true,则继续,否则跳出for循环。
3)执行increment/decrement表达式。
4)执行循环体中的语句。
5)跳到第二步

04-05. 分支语句  (Branching Statements)


a. break语句 (The Break Statement)

有两种形式:有标记的和无标记的
1)无标记的(unlabeled)
   结束所在的循环语句。
class BreakDemo {
    public static void main(String[] args) {
        int[] arrayOfInts =
            { 32, 87, 3, 589,
              12, 1076, 2000,
              8, 622, 127 };
        int searchfor = 12;
        boolean foundIt = false;
 
        for (int i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }
 
        if (foundIt) {
            System.out.println("Found " + searchfor + " at index " + i);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

2)有标记的  (labeled)
   用在嵌套循环语句中,在内层循环结束外层循环。
class BreakWithLabelDemo {
    public static void main(String[] args) {
        int[][] arrayOfInts = {
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;
        boolean foundIt = false;
 
    search:
        for (int i = 0; i < arrayOfInts.length; i++) {
            for (int j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }
 
        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

b. continue语句

  用来结束当次循环。
1)无标记的  (unlabeled)
class ContinueDemo {
    public static void main(String[] args) {
 
        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;
 
        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;
            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

2)有标记的  (labeled)
class ContinueWithLabelDemo {
    public static void main(String[] args) {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;
        int max = searchMe.length() -substring.length();
 
    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

c. return语句

The return statement exits from the current method, and control flow returns to where the method was invoked.


0 0
原创粉丝点击