Welcome to visit the blog Java Basic Syntax
First Java program (Helloworld.java)
The public class HelloWorld {//Exposes classes publicly
static void main (String []args) {//Program entry
System.out.println ("Hello World" ); Standard output
}
}
A Java program can be thought of as a collection of objects that work together by calling each other's methods. Classes, objects, methods, and instances
Class: A class is a template that describes the behavior and state of a class of objects. Object: An object is an instance of a class that has state and behavior. Method: The method is behavior. Instance variables: Each object has a unique instance variable, and the state of the object is determined by the value of those instance variables. Basic syntax
Case sensitive class name uppercase method name lowercase source filename must be the same as the class name Main method Portal: All Java programs are executed by the public static void main (String []args) method
Identifier letters, dollar and underscore start characters can be a combination of any characters cannot use keyword case sensitivity
Cosmetic characters Access: default, public, protected, private inaccessible: final, abstract, STRICTFP
Variable local variable class variable (static variable) member variable (non-static variable)
Array arrays can store multiple variables of the same type.
Enumeration enumeration limit variables can only be preset values. Use enumerations to reduce bugs in your code.
Comment Single-line Comment://Multiline Comment:/*....*/
Inheriting a class can be derived from other classes. Using inherited methods, you can reuse methods and properties of existing classes without rewriting them. Super class → subclass.
A protocol for communicating between interface objects. Interfaces define only the methods that are used to derive, but the exact implementation of a method depends entirely on the derived class.
Key words
Key Words |
Description |
Abstract |
Abstract methods, modifiers for abstract classes |
Assert |
Assert whether the condition satisfies |
Boolean |
Boolean data type |
Break |
Jump out of loops or label code snippets |
Byte |
8-bit Signed data type |
Case |
A condition of a switch statement |
Catch |
Catch exception information with try Collocation |
Char |
16-bit Unicode character data type |
Class |
Defining classes |
Const |
Not used |
Continue |
Do not execute the remainder of the loop body |
Default |
Default branch in a switch statement |
Todo |
Loop statement, the loop body executes at least once |
Double |
64-bit double-precision floating point numbers |
Else |
Branch to execute if condition is not established |
Enum |
Enum type |
Extends |
Represents a class that is a subclass of another class |
Final |
Indicates that a value cannot be changed after initialization. Indicates that the method cannot be overridden, or a class cannot have subclasses |
Finally |
Designed to accomplish code execution, it is primarily for the robustness and integrity of the program to execute code regardless of any anomalies. |
Float |
32-bit single-precision floating-point numbers |
For |
For Loop statement |
Goto |
Not used |
If |
Conditional statement |
Implements |
Represents a class that implements an interface |
Import |
Import class |
instanceof |
Test whether an object is an instance of a class |
Int |
32-bit integer number |
Interface |
interface, an abstract type, with only the definition of methods and constants |
Long |
64-bit integer number |
Native |
Presentation method is implemented in non-Java code |
New |
Assigning a new class instance |
Package |
A series of related classes form a package |
Private |
Represents a private field, or method, that can only be accessed from within a class |
Protected |
Indicates that a field can be accessed only through a class or its subclasses. Subclasses or other classes in the same package |
Public |
Represents a common property or method |
Return |
Method return value |
Short |
16-digit number |
Static |
Represents a class-level definition in which all instances are shared |
Strictfp |
Floating point comparisons use strict rules |
Super |
Represents the base class |
Switch |
SELECT statement |
Synchronized |
A block of code that represents only one thread at a time |
This |
Indicates that the current instance is invoked, or another constructor is called |
Throw throws an exception |
|
Throws |
Defining exceptions that a method might throw |
Transient |
To decorate a field that is not serialized |
Try |
Indicates that the code block is to be handled abnormally or that a finally match indicates whether the exception is thrown to execute the code in finally |
void |
Tag method does not return any values |
Volatile |
Tag fields can be accessed by multiple threads at the same time without synchronizing |
While |
While loop |
Java objects and classes
Java supports the following concepts: polymorphic inheritance encapsulates an abstract class: A class is a template that describes the behavior and state of a class of objects. Object: An object is an instance of a class that has state and behavior. Instance method overload
Example: Defining a Class
public class dog{//Dog Class (template)
String breed; Instance variable (property)
int age;
String color;
void Barking () {//Method
}
}
Class variables: local variables : variables defined in a method, construction method, or statement block are called local variables. Variable declarations and initializations are in the method, and when the method is finished, the variable is automatically destroyed. member variables : Member variables are variables that are defined outside the method body in the class. This variable is instantiated when the object is created. Member variables can be accessed by methods, construction methods, and statements blocks of specific classes in the class. Class variables : Class variables are also declared in the class, outside the method body , but must be declared as a static type .
The name of the constructed method constructor must be the same as the class. A class can have more than one construction method. If you do not explicitly define a construction method for a class, the Java compiler will provide a default constructor for the class.
Creates an object using the keyword new to create a new object. To create an object:
Declaration: Includes name and type. Instantiation: Creates an object with new . Initialization: Invokes the constructor method to initialize the object.
To access the variables and method operators of an instance:.
/* Instantiate Object *
/objectreference = new Constructor ();
* * Access to the variable * *
objectreference.variablename;
/* Access the method in the class *
/Objectreference.methodname ();
Source file declaration rule only one public class in a source file a source file can have more than one Non-public class source file name should be maintained with the class name of the public class if a class is defined in a package, then the package statement should be in the first line of the source file. The mport statement is placed between the package statement and the class definition. The import statement and the package statement are valid for all classes defined in the source file.
Java packages: Used to categorize classes and interfaces. The import statement is used to provide a reasonable path so that the compiler can find a class. Basic data Types
Java two major data types: built-in data type reference data type
The built-in data type Java language provides eight basic types . Six numeric types (four integers, two floating-point types), one character type, and one Boolean type. Four types of integers: Byte, short, int, long. Two floating-point types: float, double. Boolean: Boolean (True, False) one character: char (bits Unicode character)
Reference types are similar to C + + pointers. Reference types point to an object, and the variable that points to the object is a reference variable. objects, arrays are reference data types. The default values for all reference types are null. A reference variable can be used to reference any type that is compatible with it. Example: Site site = new site ("Runoob")
Constants use the final keyword to modify constants. Generally expressed in uppercase letters . Constant prefix: octal (0) and hexadecimal (0x). String constants: "..." Both string constants and character constants can contain any Unicode character. String a = "\u0001";. Java Variable type declares variable format: type identifier [= value][, identifier [= value] ...]; Java Variable type:
Local variables
Declared in a method, construction method, or statement block; it is only visible in the method, constructor, or statement block that declares it; It is allocated on the stack ; there is no default value and initialization is required. Member variable (instance variable)
Declared in a class, but in a method, construction methods and statement blocks, can be declared before or after use, created when an object is created, destroyed when an object is destroyed, access modifiers can decorate instance variables, and instance variables are visible to methods, construction methods, or statement blocks in a class. In general, you should set the instance variable to private. The instance variable has a default value. The default value for a numeric variable is 0, and the default value for a Boolean variable is false, and the default value for the reference type variable is null. Instance variables can be accessed directly through variable names. However, in static methods and other classes, you should use the fully qualified name: Obejectreference.variablename. Class variable (static variable)
Declared in the class as a static keyword, but must be outside the method construction method and the statement block. Class only has a copy of the class variable. Static variables are stored in a static storage area. Static variables are created at the start of the program and are destroyed at the end of the program. A static variable has a default value. When a class variable is declared as a public static final type, the class variable name must use uppercase letters. Java modifiers
Divided into 2 categories: access modifiers Fu Fei access modifiers
Access modifier default, which is visible in the same package and does not use modifiers. Private, proprietary, visible within the same class. Public, publicly owned, visible to all classes. Protected, protected, the same package and all subclasses are visible.
Basic knowledge classes and interfaces cannot be declared private. The use of private access modifiers is used primarily to hide the implementation details of the class and to protect the data of the class. A variable of a private access type can only be accessed by an external class through a public getter method in the class. Public classes, methods, construction methods, and interfaces can be accessed by any other class. If several mutually accessible public classes are distributed in different packages, you need to import the package that contains the corresponding public class. The Java program's main () method must be set to public, otherwise the Java interpreter will not be able to run the class. Protected variables, methods, and constructors can be accessed by any other class in the same package, or by subclasses in different packages.
Method Inheritance rule: A method declared public in a parent class must also be public in a subclass. A method declared as protected in a parent class is either declared as protected in a subclass, or declared as public. cannot be declared private. A method declared private in a parent class cannot be inherited.
Non-access modifier static, creating class methods and class variables. Final,inal-decorated classes cannot be inherited, decorated methods cannot be redefined by inheriting classes, and the modified variables are constants and cannot be modified. Abstract, create an abstraction class and an abstract method. Synchronized and volatile, for threading programming.
Basic knowledge: An abstract class cannot be used to instantiate an object, and the sole purpose of declaring an abstract class is to extend the class in the future. If a class contains an abstract method, the class must be declared as an abstract class, or a compilation error will occur. Abstract classes can contain abstract methods and Non-abstract methods. Abstract methods are a method without any implementation, and the specific implementation of this method is provided by subclasses. Java Operators
Operator Category: arithmetic operator relational operator bitwise operator logical operator assignment operator other operators
Arithmetic operators + 、-、 *,/,%, + + 、--relational operators
==/!=, >, <, >=, <=
Bitwise operators are applied to the object: byte type, character (char), short integer (shorter), Integer, and Long Integer. And, by bit with |, bitwise OR ^, bitwise XOR or ~, by the position complement, flip each <<, by the bit left >>, >>> to the right by the position, the right shift to 0
Logical operators &&, | |,!
Assignment operators =, + =, =, *=,/=,%=, <<=, >>=, &=, ^=, |=
Conditional operator (?:) variable x = (expression)? Value if True:value if False
instanceof Check if the object is a specific type (class type or interface type)
Operator Precedence
Java cyclic structure three kinds of loop structure:
While do...while for (primarily for arrays)
While most basic loop
while (Boolean expression) {
//loop content
}
Do...while execute at least once
do {
//code Statement
}while (boolean expression);
The number of executions for a for loop is determined before execution
for (initialization; Boolean expression; update) {
//code statement
}
An enhanced for loop is primarily used for arrays
For (Declaration statement: expression)
{
//code sentence
}
Break jumps out of a loop and switch statement blocks
Continue skip once cycle Java branch structure
2 Kinds of branch structure: if...else ... switch
If
if (Boolean expression)
{
//If the Boolean expression is true the statement to be executed
}
If...else ...
if (Boolean expression) {
//If the Boolean expression evaluates to True
}else{
//If the Boolean expression evaluates to False
}
If...else If...else
if (Boolean expression 1) {
//If Boolean expression 1 evaluates to True execute code
}else if (Boolean expression 2) {
//If Boolean expression 2 evaluates to True execute code
}else if (Boolean expression 3) {
//If Boolean expression 3 evaluates to True execute code
} else {
//If the above Boolean expression is not true to execute code
}
Nested if...else
if (Boolean expression 1) {
////Execute code if (Boolean expression 2) {////If the value of Boolean expression 1 is true executes
code if the value of Boolean expression 2 is true)
The switch determines whether a variable is equal to a value in a series of values, and each value is called a branch. The variable type in the switch statement can only be byte, short, int, or char.
switch (expression) {case
value:
//Statement break
;//Optional case
value:
//Statement break
;//optional
// You can have any number of case statements
default://optional
//Statement
}
Number classThe Java language provides the corresponding wrapper class for each of the built-in data types. All wrapper classes (Integer, Long, Byte, Double, Float, short) are subclasses of the abstract class number. The wrapper specifically supported by the compiler is called
Boxing, so when the built-in data type is used as an object, the compiler will boxed the built-in type as
Packing class。 Similarly, the compiler can also put an object
Split Boxis a built-in type. The number class belongs to the Java.lang package.
Differentiate: Built-in data types and objects.
Integer x = 5;
character classUsed to manipulate a single character. The Character class wraps a value of the base type char in the object. You need to use the object instead of the built-in data type. Note: The string class is immutable, so once you create a string object, its value cannot be changed. If you need to make a lot of changes to a string, you should choose to use the StringBuffer & StringBuilder class.
The method used to get information about the object is called the accessor method.
Character ch = ' a ';
String ClassIn Java, a string belongs to an object. Create string: String greeting = "Hello world!";
Method: String Length: Str.length () connection string: Str.concat (), STR1+STR2 create a formatted string
The static method format () of the printf () format () String class can be used to create reusable formatted strings, not just for a single printout.
System.out.printf ("The value of the floating-point variable is" +
"%f, the integer variable has the value" +
"%d, the string variable has the value" +
"is%s", Floatvar, Intvar, stringvar);
//or
String FS;
FS = String.Format ("The value of a floating-point variable is" +
"%f, the value of the integer variable is" +
"%d, the value of the string variable is" +
"%s, Floatvar, Intvar, stringvar);
SYSTEM.OUT.PRINTLN (FS);
StringBuffer and StringBuilderWhen you modify a string, you need to use the StringBuffer and StringBuilder classes. The StringBuilder method is not thread-safe (cannot be synchronized), unlike StringBuffer.
StringBuilder has a speed advantage and generally uses it. When a program requires thread safety, you must use StringBuffer.
public class test{public
static void Main (String args[]) {
StringBuffer sbuffer = new StringBuffer ("Test");
Sbuffer.append ("String Buffer");
System.out.println (Sbuffer);
}
Java ArraysJava arrays are the same type of elements that are used to store fixed sizes.
Declaring an array variable:
Datatype[] Arrayrefvar; Preferred method
//or
dataType arrayrefvar[]; The effect is the same, but not the preferred method
Create Array (new)
Arrayrefvar = new Datatype[arraysize];
1. An array was created using datatype[arraysize].
//2. Assign a reference to the newly created array to the variable Arrayrefvar.
Creating arrays and declaring array variables
datatype[] Arrayrefvar = new Datatype[arraysize];
Datatype[] Arrayrefvar = {value0, value1, ..., valuek};
Handling array array element types and sizes is OK, usually using a basic loop or a foreach loop. A foreach loop or a reinforced loop that iterates through an array without using the subscript. Arrays can be passed as arguments to methods. Array as the return value of the function. The java datetime java.util Package provides a date class to encapsulate the current date and time. The date class provides two constructors to instantiate a Date object.
The first constructor uses the current date and time to initialize the object. The second constructor receives a parameter, which is the number of milliseconds since January 1, 1970. Java Regular Expressions
The Java regular expression regular expression defines the pattern of the string. Regular expressions can be used to search, edit, or work with text. Java regular expressions are the most similar to Perl. The Java.util.regex package mainly includes the following three categories:
Pattern class: Pattern object is a compilation representation of a regular expression. Matcher class: The Matcher object is an engine that interprets and matches an input string. Patternsyntaxexception class: Patternsyntaxexception is a non-mandatory exception class that represents a syntax error in a regular expression pattern.
A capturing group capturing group is a method of handling multiple characters as a single unit, which is created by grouping characters within parentheses. Java Methods System.out.println ()
System: Systems class out: Standard Output Object println (): Method
The definition of the method:
Modifier returns the value type method name (parameter type parameter name) {
...
Method Body
...
return value;
}
Method call:
According to whether to return a value, divided into 2 kinds:
method returns a value, the method call is usually treated as a value. If the method return value is void, the method call must be a statement.
Java Stream, File, IOThe java.io package contains almost all the classes that are required for operation input and output. All of these stream classes represent input sources and output targets. Streams in java.io packages support a wide variety of formats. A stream can be understood as a sequence of data.
Reading console input
BufferedReader br = new BufferedReader (new
InputStreamReader (system.in));
Reads a single character
char C = br.read from the console ();
Reads a string from the console strings
str = Br.readline ();
Console output
The output of the console is completed by print () and println (). These methods are defined by the class PrintStream, System.out is a reference to the class object. PrintStream inherits the OutputStream class and implements the method write (). As such, write () can also be used to write operations to the console.
Reference:Java Tutorials