Java Foundation Learning (Java BASIC programming)

Source: Internet
Author: User

Java BASIC Programming one, the goal of completion
1. 掌握java中的数据类型划分2. 8种基本数据类型的使用及数据类型转换3. 位运算、运算符、表达式4. 判断、循环语句的使用5. break和continue的区别
II. Classification of data types

Java's data types can be categorized into basic data Types and reference data types. The basic data types include the most basic Boolean, char, Byte, short, int, long, float, double, and reference data types are entities that point to a variable in a special way, similar to C + +.

III. Basic data types

The Java language is a strongly typed language that defines specific data types for each data and allocates different sizes of memory space in memory.

byte   1个字节short  2个字节int    4个字节long   8个字节float  4个字节double 8个字节char   2个字节

Range:

Default value:

Data overflow

public class DataDemo01{    public static void main(String [] args){                    int max = Integer.MAX_VALUE;                    //得到整数的最大值            System.out.println("整数的最大值:"+max);          //输出最大值            System.out.println("整数的最大值+1:"+(max+1));    //输出最大值+1            System.out.println("整数的最大值+2:"+(max+2));    //输出最大值+2    } }Process started >>>整数的最大值:2147483647整数的最大值+1:-2147483648整数的最大值+2:-2147483647<<< Process finished. (Exit code 0)

Integer type

You can declare integer variables when the data does not have fractions or decimals. such as 35,-140. In Java, integer types can be divided into byte, short, int, long. For an integer constant, its type is the int type by default.

Character type (char)

The character type occupies two bytes in memory and can be used to hold characters such as English letters. Characters are enclosed in a pair of single quotation marks (')

/***1.声明字符类型的变量ch1,ch2*2.将变量ch1的值设为字符b,ch2的值设为98*3.输出字符变量ch1、ch2的内容*/class TestDemo01{    public static void main(String [] args){        char ch1 = ‘b‘;                     //定义字符        char ch2 = 98;                      //定义字符,整型转字符        System.out.println("ch1 = "+ch1);   //输出        System.out.println("ch2 = "+ch2);    }}Process started >>>ch1 = bch2 = b<<< Process finished. (Exit code 0)

Escape character

/***1.声明字符类型的变量ch1,ch2*2.将变量ch1的值设为\",ch2的值设为\*3.输出字符变量ch1、ch2的内容,在打印的字符串中直接加入转义字符*/class TestDemo02{    public static void main(String [] args){        char ch1 = ‘\"‘;                        //定义转义字符双引号        char ch2 = ‘\\‘;                        //定义转义字符反斜线        System.out.println("ch1 = "+ch1);       //输出        System.out.println("ch2 = "+ch2);        System.out.println("\"Hello World\"");  //直接输出转义字符    }}Process started >>>ch1 = "ch2 = "Hello World"<<< Process finished. (Exit code 0)

floating-point type (float,double)
In Java, a value with a decimal point is called a floating-point number type. When using floating-point numeric values, the default type is double.

/***1.声明浮点型的变量 num1,num2*2.将变量 num1 的值设为4.0,num2的值设为3.0f*3.输出num1*num1、num2*num2的值*/class TestDemo01{    public static void main(String [] args){        float num1 = 4.0;                               //定义float型变量        float num2 = 3.0f;                              //定义float型变量        System.out.println("两个小数相乘 "+num1*num1);    //计算两数相乘        System.out.println("两个小数相乘 "+num2*num2);    //计算两数相乘    }}Process started >>>E:\TestDemo01.java:34: 错误: 不兼容的类型: 从double转换到float可能会有损失        float num1 = 4.0;                       //定义浮点数         ^1 个错误<<< Process finished. (Exit code 1)将float num1 = 4.0;改为float num1 = 4.0f;Process started >>>两个小数相乘 16.0两个小数相乘 9.0<<< Process finished. (Exit code 0)

Boolean Type (Boolean)
Boolean (Boolean) type of variable, only true (true) and False (false) two.

/***1.声明boolean变量,并赋值true*2.通常用来控制程序的流程*/class TestDemo01{    public static void main(String [] args){        boolean flag = true;                //定义boolean变量        System.out.println("flag="+flag);   //输出    }}
Iv. Conversion of data types

Automatic conversion of data types
BYTE--->short--->int--->long--->float--->double
--------Char--->int

/***1.数据类型转换*/public class DataDemo02{    public static void main(String [] args){                    int x = 30;                                 //定义整型变量            float y = 22.19f;                           //定义浮点型变量            System.out.println("x/y= " + (x/y) );       //整型变量除以浮点型变量-float类型            System.out.println("10/0.35= "+(10/0.35));  //整型常量除以浮点型常量-浮点数据            System.out.println("10/3= "+(10/3));        //整型常量除以整型常量-整型,小数部分被忽略    }}Process started >>>x/y= 1.351960310/0.35= 28.57142857142857310/3= 3<<< Process finished. (Exit code 0)

Any type of data is transformed to string

/***1.定义字符串变量*2.任何数据类型碰到String类型的变量或者常量之后都向String类型转换*/public class DataDemo03{    public static void main(String [] args){                    String  str = "billy";                      //定义字符串变量            int x = 10;                                 //定义整型变量            str = str + x;                              //改变字符串的内容            System.out.println("str = "+ str );         //输出            int i = 1;            int j = 2;            System.out.println("i + j = "+ i + j );     //输出 + 表示字符串连接    }}Process started >>>str = billy10i + j = 12<<< Process finished. (Exit code 0)

Data type coercion (display transformation)
Display conversion may result in data loss, Syntax: variable name (data type to convert)

/***1.数据类型强制转换*/public class DataDemo04{    public static void main(String [] args){                    float  f = 3.15f;                                //定义浮点型变量            int x = (int)f;                              //强制转换int型变量            System.out.println("x = "+ x );              //输出            System.out.println("10/3 = "+ ((float)10/3 ) ); //常量计算使用强制类型转换    }}Process started >>>x = 310/3 = 3.3333333<<< Process finished. (Exit code 0)
V. Operators, expressions, and statements

Operator
Assignment operator (=)
Unary operators (+-!) )
Arithmetic operator (+-*/% (modulo: take remainder))
Relational operators (> < >= <= = =)
Self-increment decrement operator (++,--)
Logical operators (&&,| |,&,|)

对于&(与)来说,要求所有的条件都判断,而如果使用&&(短路与)如果第一个条件为false,则后面的条件将不再判断。对于|(或)来说,要求所有的条件都判断,而如果使用||(短路或)如果第一个条件为true,则后面的条件将不再判断。

Parentheses operator (())
Bitwise operator (&,|,^ (XOR),~,<< (shift left),>> (right Shift),>>> (unsigned Right shift))
Operator Precedence


Concise expression


Example:

VI. Selection and Looping statements

In general, the structure of the program includes the following three kinds: sequential structure, selection structure, loop structure. These three different structures have one thing in common, with only one entrance and one exit.
Sequential Structure
The program executes first and next, the next statement executes after a statement is executed, and continues until the end of the program.

Select Structure
A structure that determines which statements to execute, depending on whether the condition is established or not. The selection structure includes if, if...else, switch.

If statement

if (judging condition) {
Statement 1;
Statement 2;
}

/***1.验证选择结构*/public class TestDemo05{    public static void main(String [] args){                    int x = 3;                               //定义整型变量x            int y = 5;                               //定义整型变量y            System.out.println("**开始比较两个数的大小**");                   if(x > y){                               //判断x是否比y大                System.out.println("x比y大!");            }            if(x<y){                                 //判断x是否比y小                System.out.println("x比y小!");            }            System.out.println("**比较完成**");    }}Process started >>>**开始比较两个数的大小**x比y小!**比较完成**<<< Process finished. (Exit code 0)  

If...else statements

if (judging condition) {
Statement body 1;
}else{
Statement body 2;
}

/***1.判断一个数的是奇数还是偶数*2.判断余数是否为1*/class TestDemo05{    public static void main(String [] args){                    int x = 4;                               //定义整型变量x              if(x % 2 == 1){                          //判断余数是否为1                System.out.println("x是奇数!");            }else{                System.out.println("x是偶数!");            }    }}Process started >>>x是偶数!<<< Process finished. (Exit code 0)  

The Trinocular operator (? : )

variable = condition judgment? Expression 1: Expression 2
Depending on whether the condition is established or not, the expression after the result is ":", or ":", if the condition evaluates to True, the expression 1 is executed, and false executes the expression 2

/***1.使用三目运算符求出两个数字的最大值*/class TestDemo05{    public static void main(String [] args){            int max = 0;                             //定义变量保存最大值            int x = 4;                               //定义整型变量x            int y = 10;                              //定义整型变量y            max = (x>y)?x:y;            System.out.println("最大值为:"+max);    //输出max    }}Process started >>>最大值为:10<<< Process finished. (Exit code 0)  

If...else if...else Statements

If necessary in the IF: else when judging multiple conditions, the if is required. else if ... else statement, in the following format:

if (judging condition 1) {
Statement body 1;
}else if (judging condition 2) {
Statement body 2;
}
...//multiple else if () statements
else{statement body 3;}

class TestDemo05{    public static void main(String [] args){            int x = 4;                               //定义整型变量x            if(x==2){                                //判断x的值是否为2                System.out.println("x的值是2");            }else if(x==3){                         //判断x的值是否为3                System.out.println("x的值是3");                    }else if(x==4){                         //判断x的值是否为4                System.out.println("x的值是4");            }    }}Process started >>>x的值是4<<< Process finished. (Exit code 0)

Switch structure

To find and execute one of the statements that match the criteria in a number of selection criteria, you can use if instead. Else constantly judging, you can also use another more convenient way to multiple-select--switch statements, Syntax format:

switch (expression) {
Case Selection Value 1: statement body 1;
Case Selection Value 2: statement body 2;
.......
Case SELECT value N: statement body N;
Default: statement body;
}
It is important to note that selecting a value in a switch statement can only be a character or a constant.

/***1.判断学生成绩,并给出等级A(90~100),B(>80),C(>70),D(>60),E(0~59)*/class TestDemo05{    public static void main(String [] args){            int Score = 85;                              //定义一个学生的分数            switch (Score/10){                case 10:                case  9: System.out.println("A级"); break;                case  8: System.out.println("B级"); break;                case  7: System.out.println("C级"); break;                   case  6: System.out.println("D级"); break;                default: System.out.println("E级"); break;                }    }}Process started >>>B级<<< Process finished. (Exit code 0)/**每一个case语句后面都加上了一个break语句,如果不加入此语句的话,则*switch语句会从第一个满足条件的case开始依次执行操作。*/  不加break,则Process started >>>B级C级D级E级<<< Process finished. (Exit code 0)  

Loop Structure
The cyclic structure determines the number of execution times of the procedure, depending on whether the condition is established or not, and this procedural paragraph is called the loop body.

While loop

while (cyclic condition judgment) {
Statement 1;
Statement 2;
...
Statement N;
Cyclic condition change;
}

/***1.使用while循环进行累加操作**/class TestDemo05{    public static void main(String [] args){            int i = 1;                               //定义整型变量i            int sum = 0;                             //定义整型变量,保存累加结果            while(i <= 100){                         //判断循环条件                sum = sum + i;          //sum + = i; //执行累加结果                i++;                                 //修改循环条件            }            System.out.println("1~100累加和--->"+sum);//输出    }}Process started >>>1~100累加和--->5050<<< Process finished. (Exit code 0)  

Do-while Cycle

do{
Statement 1;
Statement 2;
....
Statement N;
Cyclic conditions change;
}
while (cyclic condition judgment);

/***1.使用do...while循环进行累加操作**/class TestDemo05{    public static void main(String [] args){            int i = 1;                               //定义整型变量i            int sum = 0;                             //定义整型变量,保存累加结果            do{                      //判断循环条件                sum = sum + i;          //sum + = i; //执行累加结果                i++;                                 //修改循环条件            }            while(i <= 100);            System.out.println("1~100累加和--->"+sum);//输出    }}Process started >>>1~100累加和--->5050<<< Process finished. (Exit code 0)   

For loop

For the while and do...while two loops, the operation does not necessarily have to know the number of loops explicitly, and if the developer already knows the number of cycles clearly, then you can use another loop statement--for Loop.

for (assigned initial value; judging condition; assignment increment or decrement) {
Statement 1;
....
Statement N;
}

/***1. Using a For loop to accumulate operations **/class testdemo05{public static void Main (String [] args) {int sum = 0; Defines an integer variable that holds the cumulative result for (int i=1;i<=100;i++) {sum = sum + I          ; sum + = i; Perform cumulative results} System.out.println ("1~100 accumulation and--->" +sum);//output}}process started >>>1~100 accumulation and- -->5050<<< Process finished. (Exit code 0)/***1. Use multiple for loops to print 99 multiplication table **/class testdemo05{public static void Main (String [] args) {for (int i=1                    ; i<=9;i++) {//First layer loop for (int j=1;j<=i;j++) {//Second layer loop System.out.print (i+ "*" +j+ "=" + (i*j) + "\ T");//output} System.out.println ();//NewLine}}}   Process started >>>1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10   5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=77*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9* 2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 <<< Process finished. (Exit code 0)

Cyclic interrupts
Break Statement
The break statement can force the program to interrupt the loop, and when the program executes to the breaks statement, it leaves the loop, resumes execution of the next statement outside the loop, and if the break statement appears in the inner loop of the nested loop, the break statement only jumps out of the current layer's loop.

/***1.使用break**/class TestDemo05{    public static void main(String [] args){            for(int i=1;i<=9;i++){                                      if(i==3){                   //如果i=3,则退出整个循环                    break;                  //退出整个循环                }                System.out.println("i = " + i);//            }            System.out.println("循环结束");    }}Process started >>>i = 1i = 2循环结束<<< Process finished. (Exit code 0)  

Continue statements
The Continue statement forces the program to jump to the beginning of the loop, and when the program runs to the continue statement, it stops running the rest of the loop body, but goes back to the beginning of the loop to continue running.

/***1.使用continue**/class TestDemo05{    public static void main(String [] args){            for(int i=1;i<=9;i++){                                      if(i==3){                   //如果i=3,则退出整个循环                    continue;                   //退出一次循环                }                System.out.println("i = " + i);//            }        System.out.println("循环结束");     }}Process started >>>i = 1i = 2i = 4i = 5i = 6i = 7i = 8i = 9循环结束<<< Process finished. (Exit code 0)

Attention:

Return statement

Ends the execution of the current method and exits, returning the statement at which the method was called.

/***1.使用return**/class TestDemo05{    public static void main(String [] args){            for(int i=1;i<=9;i++){                                      if(i==3){                   //如果i=3,则退出整个循环                    return;                 //退出整个方法                }                System.out.println("i = " + i);//            }        System.out.println("循环结束");    }}Process started >>>i = 1i = 2<<< Process finished. (Exit code 0)可以看到“循环结束”没有输出,当i=3时,满足执行return,结束整个方法的执行。
Vii. Key points
    1. Basic data types and their conversions
    2. Select and Loop statements

Java Foundation Learning (Java BASIC programming)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.