Home Java javaTutorial Java language basic syntax learning

Java language basic syntax learning

Jun 23, 2017 pm 02:31 PM

Basic syntax of Java language

1. Identifiers and keywords

  1. Identifier

  • In the java language, it is used to mark class name, object name, variable name, method name, type name, array The valid character sequence of the name and package name is called an "identifier"; the

  • identifier consists of letters, numbers, underscores, and the dollar sign , And the first character of cannot be a number;

  • java language is case sensitive;

  • Identifier naming rules: the first letter of class names is capitalized, variable names and method names use camel case, constants are all capitalized, multiple words are separated by "_", and package names are all lowercase;

  • Keywords

    • In the Java language, some specialized words have been given special meanings, and these words can no longer be used to name identifiers. Characters, these proprietary words are called "keywords";

    • Java has 50 keywords and 3 reserved words, none of which can be used to name identifiers;

      ##extendsfinalfinally floatforgotoifimplementsimportinstanceofintinterfacelongnativenewpackageprivateprotectedpublicreturnshortstaticstrictfpsuper##switchvolatile
    • true, false, and null are not keywords, they are reserved words, but they still cannot be used to name identifiers. Reserved words are keywords reserved by java and may be used as keywords in future upgrades. Keywords;

    • 2. Basic data types

      1. Integer type (int is the default type)

       

       2. Floating point type (double is the default type)

       


        • When assigning a value to a float type variable, if the assigned value has a decimal part, you must add "F" at the end. ” or “f”;

       3. Character type (2 bytes)


        • char ch = 'a';

        • Some characters cannot be entered into the program through the keyboard, so you need to use escape characters;

      4. Boolean type (1 byte)


        • boolean flag = true;

      5. Default value


        • Numeric variable: 0;

        • Character variable :'\0';

        • Boolean variable: false;

        • Reference data type : null;

      6. Conversion between different data types


        • Automatic type conversion (low to high)


        • Coercion (high to low)

      public class Test003 {
          public static void main(String[] args) {
              byte b = 100;
              int i = 22;
              float f = 78.98f;
              int res = b + i + (int)f;    //此处对f使用了强制类型转换(int)f,转换后的值为78
              System.out.println("res: "+res);    //res: 200
          }
      }
      Copy after login

      3. Operators and expressions

       1. Arithmetic operators

      public class Test003 {    public static void main(String[] args) {        int i = 5;
              System.out.println(0/i);    //0
              System.out.println(0%i);    //0
              System.out.println(i/0);    //除数不能为零,报异常java.lang.ArithmeticException
              System.out.println(i%0);    //除数不能为零,报异常java.lang.ArithmeticException    }
      }
      Copy after login

       2. Assignment operator

       3. Increment and decrement operator (++, --)

      public class Test003 {    public static void main(String[] args) {        int i = 5;
              System.out.println(i++);    //5
              System.out.println(++i);    //7
              System.out.println(i);    //7
              System.out.println(--i);    //6
              System.out.println(i--);    //6
              System.out.println(i);    //5    }
      }
      Copy after login

       4. Relational operators

       5. Logical operators

      public class Test003 {    public static void main(String[] args) {        boolean t = true;        boolean f = false;
              System.out.println(t && f);    //false,短路与运算符,若运算符左侧为false则不计算右侧的表达式
              System.out.println(t || f);    //true,短路或运算符,若运算符左侧为true则不计算右侧的表达式
              System.out.println(t & f);    //false,与运算符,不管左侧是否为false都要计算右侧的表达式
              System.out.println(t | f);    //true,或运算符,不管左侧是否为true都要计算右侧的表达式
              System.out.println(t ^ f);    //true,异或运算符,只要左右两侧不相同则为true,反之为false
              System.out.println(!f);    //true,取反运算符    }
      }
      Copy after login

      6. Bit operator

      public class Test003 {    public static void main(String[] args) {        //在位运算符中1相当于true,0相当于false
              int b1 = 6;    //二进制为00000000 00000000 00000000 00000110
              int b2 = 11;    //二进制为00000000 00000000 00000000 00001011
              System.out.println(b1 & b2);    //按位与运算符,二进制为00000000 00000000 00000000 00000010,结果为2
              System.out.println(b1 | b2);    //按位或运算符,二进制为00000000 00000000 00000000 00001111,结果为15
              System.out.println(b1 ^ b2);    //按位异或运算符,二进制为00000000 00000000 00000000 00001101,结果为13
              System.out.println(~b1);    //按位取反运算符,二进制为11111111 11111111 11111111 11111001,结果为-7
              System.out.println(b1 << 2);    //左移位运算符,二进制为00000000 00000000 00000000 00011000,结果为24
              int b3 = -14;    //二进制为11111111 11111111 11111111 11110010
              System.out.println(b3 >> 2);    //带符号右移位运算符,二进制为11111111 11111111 11111111 11111100,结果为-4
              System.out.println(b3 >>> 2);    //无符号右移位运算符,二进制为00111111 11111111 11111111 11111100,结果为1073741820    }
      }
      Copy after login

      7. Ternary operator

      public class Test003 {
          public static void main(String[] args) {
              int a = 1;
              int b = 2;
              int c = 4;
              int res = c==a+b?++a:c>a+b?++b:++c;    //三元运算符 (表达式)?(值1):(值2),若表达式为true则取值1,反之取值2
              System.out.println(res);    //++b,结果为3
          }
      }
      Copy after login

       8. Operator precedence

      ##4. Array

       1. One-dimensional array

      public class Test003 {    public static void main(String[] args) {        int[] i;    //声明一个整型的一维数组变量
              int ii[];    //声明一个整型的一维数组变量
              i = new int[5]; //创建一个长度为5的一维数组对象,并将变量i指向该对象
              float[] f = new float[5];    //直接创建一个长度为5的单精度浮点型一维数组对象,并将变量f指向该对象
              double[] d = {1, 2, 3.4, 4.5};    //直接初始化一个一维数组元素        
              System.out.println(d[3]);    //通过数组下标来获取数组内的元素,数组下标从0开始,结果为4.5
              System.out.println(f[0]);    //当创建出一个数组对象时,该对象内的数组元素为该数据类型的默认值,所以此处结果为0.0        //System.out.println(i[5]);    //当通过数组下标来获取数组内元素时,[]内的值>=数组长度则报异常java.lang.ArrayIndexOutOfBoundsException(数组下标越界)        //System.out.println(ii[0]);    //若一个数组变量只声明而未指向某一个具体的数组对象时,编译出错
              System.out.println(d.length);    //得到该数组的长度,结果为4    }
      }
      Copy after login

       2. Two-dimensional array

      public class Test003 {    public static void main(String[] args) {        int[][] i;    //声明一个整型的二维数组变量
              int ii[][];    //声明一个整型的二维数组变量
              int[] iii[];    //声明一个整型的二维数组变量
              i = new int[5][2]; //创建一个长度为5的二维数组对象,并将变量i指向该对象
              float[][] f = new float[5][2];    //直接创建一个长度为5的单精度浮点型二维数组对象,并将变量f指向该对象
              double[][] d = {{1}, {2,3}, {4,5,6}, {7,8,9,10}};    //直接初始化一个二维数组元素        
              System.out.println(d[3][1]);    //通过数组下标来获取数组内的元素,数组下标从0开始,结果为8
              System.out.println(f[0][0]);    //当创建出二个数组对象时,该对象内的数组元素为该数据类型的默认值,所以此处结果为0.0        //System.out.println(i[5][0]);    //当通过数组下标来获取数组内元素时,[]内的值>=数组长度则报异常java.lang.ArrayIndexOutOfBoundsException(数组下标越界)        //System.out.println(ii[0][0]);    //若一个数组变量只声明而未指向某一个具体的数组对象时,编译出错
              System.out.println(d.length);    //得到该数组的长度,结果为4
              System.out.println(d[2].length);    //得到二位数组内的下标为2的那个一维数组的长度    }
      }
      Copy after login

      5. Flow control statements (if, switch, for, while, do...while)

      1. Conditional branch statement

      public class Test003 {    public static void main(String[] args) {        int[] score = new int[5];
              score[0] = -7;
              score[1] = 65;
              score[2] = 80;
              score[3] = 90;
              score[4] = 59;        for(int i=0; i<score.length; i++) {            if(score[i]>=0 && score[i]<60) {
                      System.out.println("不及格");
                  }else if(score[i]>=60 && score[i]<80) {
                      System.out.println("及格");
                  }else if(score[i]>=80 && score[i]<90) {
                      System.out.println("良");
                  }else if(score[i]>=90 && score[i]<100) {
                      System.out.println("优");
                  }else {
                      System.out.println("成绩异常");
                  }
              }        
              char ch = &#39;a&#39;;        switch(ch) {    //switch括号内只支持 byte,short,int,char,enum五种数据类型,但是JDK1.7版本增加了String类型,所以相对于JDK1.7而言就是六种了
                  case &#39;A&#39;:    //case为switch语句的入口,break为出口,从入口开始执行,直到遇到出口或代码执行完毕才结束
                  case &#39;a&#39;:
                      System.out.println("优");                break;            case &#39;B&#39;:            case &#39;b&#39;:
                      System.out.println("良");                break;            case &#39;C&#39;:            case &#39;c&#39;:
                      System.out.println("及格");                break;            default:    //若上述条件均不匹配,则进default开始执行语句
                      System.out.println("不及格");
              }
          }
      }
      Copy after login

       2. Loop statement

      public class Test003 {    public static void main(String[] args) {        int res = 0;
              out:    //out是一个标号,告诉java从哪里开始执行程序
              for(int i=1; i<=10; i++) {            if(i==3) continue out;    //continue终止本次循环,执行下次循环
                  if(i==5) break out;    //break跳出循环
                  res = res + i;
              }
              System.out.println(res);    //结果为1+2+4=7
              
              int res2 = 0;        int i = 1;
              in:        do{            if(i==3) continue in;    //continue终止本次循环,执行下次循环
                  if(i==5) break in;    //break跳出循环
                  res2 = res2 + i;
                  i++;
              }while(i<=10);
              System.out.println(res2);
          }
      }
      Copy after login

      abstract assert boolean break byte case catch char
      class const continue default do double else enum
      synchronized this throw throws transient try void
      while

    The above is the detailed content of Java language basic syntax learning. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    See all articles