Home > Java > Java Tutorial > body text

[java tutorial] Java basic syntax

黄舟
Release: 2016-12-26 11:15:07
Original
1052 people have browsed it

Java basic syntax

A Java program can be thought of as a collection of objects, and these objects work together by calling each other's methods. The following briefly introduces the concepts of classes, objects, methods and instance variables.

Object: An object is an instance of a class and has state and behavior. For example, a dog is an object. Its status includes: color, name, and breed; its behaviors include: wagging its tail, barking, eating, etc.

Class: A class is a template that describes the behavior and status of a type of object.

Method: Method is behavior, and a class can have many methods. Logical operations, data modification, and all actions are completed in methods.

Instance variables: Each object has unique instance variables, and the state of the object is determined by the values ​​of these instance variables.

The first Java program

The following is a simple Java program that will print the string Hello World

public class MyFirstJavaProgram {
   /* 第一个Java程序.  
    * 它将打印字符串 Hello World
    */
    public static void main(String []args) {
       System.out.println("Hello World"); // 打印 Hello World
    }
}
Copy after login

The following will introduce step by step how to save, compile and run this Program:

Open Notepad and add the above code;

Save the file name as: MyFirstJavaProgram.java;

Open the cmd command window and enter the directory where the target file is located The location, assuming it is C:

, type javac MyFirstJavaProgram.java in the command line window and press the enter key to compile the code. If there are no errors in the code, the cmd command prompt will go to the next line. (Assuming the environment variables are all set).

Type java MyFirstJavaProgram and press Enter to run the program

You will see Hello World in the window

C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram 
Hello World
Copy after login

Basic syntax

Writing When writing Java programs, you should pay attention to the following points:

Case sensitivity: Java is case-sensitive, which means that the identifiers Hello and hello are different.

Class name: For all classes, the first letter of the class name should be capitalized. If the class name consists of several words, the first letter of each word should be capitalized, for example, MyFirstJavaClass .

Method name: All method names should start with a lowercase letter. If the method name contains several words, the first letter of each subsequent word is capitalized.

Source file name: The source file name must be the same as the class name. When saving the file, you should use the class name as the filename (remember Java is case-sensitive) and the filename suffix .java. (If the file name and class name are different, a compilation error will occur).

Main method entry: All Java programs start execution from the public static void main(String args[]) method.

Java identifiers

All components of Java require names. Class names, variable names, and method names are all called identifiers.

Regarding Java identifiers, there are the following points to note:

All identifiers should start with a letter (A-Z or a-z), dollar sign ($), or underscore (_)

The first character can be followed by any combination of characters

Keywords cannot be used as identifiers

Identifiers are case-sensitive

Legal identifiers Examples: age, $salary, _value, __1_value

Illegal identifier examples: 123abc, -salary

Java modifiers

Like other languages, Java can use modifiers To modify the methods and properties in the class. There are two main types of modifiers:

Accessible modifiers: default, public, protected, private

Inaccessible modifiers: final, abstract, strictfp

at the back We will discuss Java modifiers in depth in this chapter.

Java variables

There are mainly the following types of variables in Java

Local variables

Class variables (static variables)

Member variables (non-static variables)

Java arrays

Arrays are objects stored on the heap and can store multiple variables of the same type. In later chapters, we will learn how to declare, construct, and initialize an array.

Java Enumerations

Java 5.0 introduced enumerations, which restrict variables to preset values. Using enumerations can reduce bugs in your code.

例如,我们为果汁店设计一个程序,它将限制果汁为小杯、中杯、大杯。这就意味着它不允许顾客点除了这三种尺寸外的果汁。

实例

class FreshJuice {
   enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
   FreshJuiceSize size;
}
public class FreshJuiceTest {
   public static void main(String args[]){
      FreshJuice juice = new FreshJuice();
      juice.size = FreshJuice. FreshJuiceSize.MEDUIM ;
   }
}
Copy after login

注意:枚举可以单独声明或者声明在类里面。方法、变量、构造函数也可以在枚举中定义。

Java关键字

下面列出了Java保留字。这些保留字不能用于常量、变量、和任何标识符的名称。


关键字

描述


abstract 抽象方法,抽象类的修饰符

assert 断言条件是否满足

boolean 布尔数据类型

break 跳出循环或者label代码段

byte 8-bit 有符号数据类型

case switch语句的一个条件

catch 和try搭配扑捉异常信息

char 16-bit Unicode字符数据类型

class 定义类

const 未使用

continue 不执行循环体剩余部分

default switch语句中的默认分支

do 循环语句,循环体至少会执行一次

double 64-bit双精度浮点数

else if条件不成立时执行的分支

enum 枚举类型

extends 表示一个类是另一个类的子类

final 表示一个值在初始化之后就不能再改变了
表示方法不能被重写,或者一个类不能有子类

finally 为了完成执行的代码而设计的,主要是为了程序的健壮性和完整性,无论有没有异常发生都执行代码。

float 32-bit单精度浮点数

for for循环语句

goto 未使用

if 条件语句

implements 表示一个类实现了接口

import 导入类

instanceof 测试一个对象是否是某个类的实例

int 32位整型数

interface 接口,一种抽象的类型,仅有方法和常量的定义

long 64位整型数

native 表示方法用非java代码实现

new 分配新的类实例

package 一系列相关类组成一个包

private 表示私有字段,或者方法等,只能从类内部访问

protected 表示字段只能通过类或者其子类访问
子类或者在同一个包内的其他类

public 表示共有属性或者方法

return 方法返回值

short 16位数字

static 表示在类级别定义,所有实例共享的

strictfp 浮点数比较使用严格的规则

super 表示基类

switch 选择语句

synchronized 表示同一时间只能由一个线程访问的代码块

this 表示调用当前实例
或者调用另一个构造函数

throw 抛出异常

throws 定义方法可能抛出的异常

transient 修饰不要序列化的字段

try 表示代码块要做异常处理或者和finally配合表示是否抛出异常都执行finally中的代码

void 标记方法不返回任何值

volatile 标记字段可能会被多个线程同时访问,而不做同步

while while循环

Java注释

类似于C/C++,Java也支持单行以及多行注释。注释中的字符将被Java编译器忽略。

public class MyFirstJavaProgram{
   /* 这是第一个Java程序
    *它将打印Hello World
    * 这是一个多行注释的示例
    */
    public static void main(String []args){
       // 这是单行注释的示例
       /* 这个也是单行注释的示例 */
       System.out.println("Hello World"); 
    }
}
Copy after login

Java 空行

空白行,或者有注释的的行,Java编译器都会忽略掉。

继承

In Java, a class can be derived from other classes. If you are creating a class and there is already a class that has the properties or methods you need, then you can inherit the newly created class from that class.

Using inheritance, you can reuse methods and properties of existing classes without having to rewrite these codes. The inherited class is called a super class, and the derived class is called a subclass.

Interface

In Java, interface can be understood as a protocol for mutual communication between objects. Interfaces play a very important role in inheritance.

The interface only defines the methods to be used by the derived class, but the specific implementation of the method completely depends on the derived class.

The next section introduces classes and objects in Java programming. Afterwards you will have a clearer understanding of classes and objects in Java.

The above is the content of basic Java syntax. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!