search
HomeJavajavaTutorialJava language basic syntax learning

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
          }
      }

      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    }
      }

       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    }
      }

       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,取反运算符    }
      }

      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    }
      }

      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
          }
      }

       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    }
      }

       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的那个一维数组的长度    }
      }

      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("不及格");
              }
          }
      }

       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);
          }
      }

      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
    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
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    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

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.