Java basic syntax [2]

Source: Internet
Author: User
Tags assert modifiers throw exception java keywords

Java Basic Syntax

A Java program can be thought of as a collection of a series of objects that work together by invoking each other's methods. The following is a brief introduction to the concepts of classes, objects, methods, and instance variables.

    • Object : An object is an instance of a class that has state and behavior. For example, a dog is an object whose state is: color, name, variety, behavior: wagging the tail, barking, eating, etc.
    • class : A class is a template that describes the behavior and state of a class of objects.
    • method : The method is the behavior, a class can have many methods. Logical operations, data modifications, and all actions are done in a method.
    • instance variables : Each object has a unique instance variable, and the state of the object is determined by the value of these instance variables.
The first Java program

Here's a simple Java program that will print the string Hello World

InstancePublic Class HelloWorld { /*The first Java program * It will print the string Hello World*/ Public Static void Main(String []args) { System. Out. println("Hello World"); // print Hello World } }
Run an instance?

Here's how to save, compile, and run the program:

    • Open Notepad, add the above code;
    • Save the file name as: Helloworld.java;
    • Open the CMD Command window and enter the location of the target file, assuming c \
    • In the Command Line window, type Javac Helloworld.java press ENTER to compile the code. If the code has no errors, the cmd command prompt goes to the next line. (assuming that the environment variable is set up).
    • Then type Java HelloWorld Press ENTER to run the program.

You'll see Hello World in the window

:>HelloWorld.:>HelloWorldHello     World 

Gif Diagram Demo:

Basic syntax

The following points should be noted when writing Java programs:

    • case-sensitive : Java is case-sensitive, which means that the identifier Hello is different from hello.
    • 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, such as 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 to save the filename (remember that Java is case-sensitive), and the suffix of the file name is. java. (a compilation error is caused if the file name and the class name are not the same).
    • Main Method Entry : All Java programs are executed by the public static void main (String []args) method.
Java identifiers

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

For the Java identifiers, there are a few things to note:

    • All identifiers should start with a letter (A-Z or a-Z), a dollar symbol ($), or an underscore (_).
    • The first character can be a letter (A-Z or a-Z), a dollar symbol ($), an underscore (_), or any character combination of a number
    • Keyword cannot be used as an identifier
    • Identifiers are case-sensitive
    • Examples of legal identifiers: Age, $salary, _value, __1_value
    • Examples of illegal identifiers: 123abc,-salary
Java modifier

Like other languages, Java can use modifiers to decorate methods and properties in a class. There are two main types of modifiers:

    • Access control modifiers: default, public, protected, private
    • Non-access control modifiers: final, abstract, STRICTFP

In a later chapter we'll go into the Java modifier in more detail.

There are several types of variables in Java variable java.
    • Local variables
    • class variables (static variables)
    • Member variables (non-static variables)
Java arrays

An array is an object stored on a heap and can hold multiple variables of the same type. In the following chapters, we will learn how to declare, construct, and initialize an array.

Java Enumeration

Java 5.0 introduces enumerations, and enumeration limit variables can only be pre-set values. Use enumerations to reduce bugs in your code.

For example, we design a program for the juice shop that will limit the juice to small cups, medium cups, and large cups. This means that it does not allow customers to spot fruit juices other than these three sizes.

InstanceClass Freshjuice { Enum Freshjuicesize{ SMALL,MEDIUM,LARGE } Freshjuicesize Size;} Public Class Freshjuicetest { Public Static void Main(String []args) { freshjuice Juice = new Freshjuicejuice. Size = freshjuice. Freshjuicesize. Medium}} /span>

Note: enumerations can be declared individually or declared inside a class. Methods, variables, and constructors can also be defined in enumerations.

Java keywords

The following is a list of Java reserved words. These reserved words cannot be used for constants, variables, and names of any identifiers.

Key Words Description
Abstract Abstract methods, modifiers for abstract classes
Assert Whether the assertion condition satisfies
Boolean Boolean Data types
Break Jump out of a loop or label code snippet
Byte 8-bit Signed data types
Case A condition for a switch statement
Catch Match the try with catch exception information
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 the switch statement
Do Loop statement, the loop body is executed at least once
Double 64-bit double-precision floating-point number
Else The branch that executes when the 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 a method cannot be overridden, or that a class cannot have subclasses
Finally In order to complete the execution of the code design, mainly for the robustness and integrity of the program, regardless of whether there is no exception to execute code.
Float 32-bit single-precision floating-point number
For For Loop statement
Goto Not used
If Conditional statements
Implements Indicates that a class implements an interface
Import Import class
instanceof To 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 Represents methods implemented in non-Java code
New Assigning a new class instance
Package A series of related classes make up a package
Private Represents a private field, or method, etc., accessible only from within the class
Protected Indicates that a field can only be accessed through a class or its subclasses
Subclasses or other classes within the same package
Public Represents a shared property or method
Return Method return value
Short 16-digit number
Static Represents a class-level definition that is shared by all instances of the
Strictfp Floating-point comparisons use strict rules
Super Represents a base class
Switch SELECT statement
Synchronized A block of code that represents a single thread that can be accessed at the same time
This Represents the invocation of the current instance
or call another constructor
Throw Throw exception
Throws Defining exceptions that a method might throw
Transient Modify fields that do not serialize
Try Represents a code block to do exception handling or a finally mate to indicate whether throwing an exception executes the code in the finally
void Tag method does not return any values
Volatile Tag fields may be accessed by multiple threads at the same time without synchronizing
While While loop
Java annotations

Similar to C/c++,java also supports single-line and multiline annotations. The characters in the note will be ignored by the Java compiler.

Public Class HelloWorld { /*This is the first Java program * It will print Hello World * This is an example of a multiline comment*/ Public Static void Main(String []args< Span class= "Hl-brackets" >) { // This is an example of a single-line comment /* This is also a single-line comment example */ System. Out. Println ( "hello World ") }} /span> Java Empty Line

Blank lines, or annotated lines, are ignored by the Java compiler.

Inherited

In Java, a class can be derived from another class. If you are creating a class that already has a class that has the properties or methods you need, you can inherit the class from the newly created class.

With inherited methods, you can reuse the methods and properties of existing classes without rewriting the code. The inherited class is called the superclass (Super Class), and the derived class is called a subclass (subclass).

Interface

In Java, interfaces can be understood as protocols that communicate with each other between objects. Interfaces play an important role in inheritance.

An interface defines only the methods to be used for derivation, but the concrete implementation of the method depends entirely on the derived class.

Java source program differs from compile-time operation

As shown in the following:

The next section describes the classes and objects in Java programming. You will then have a clearer idea of the classes and objects in Java.

Java Development Environment Configuration Java objects and classesList of Notes
  1. Android

    297***[email protected]

    Identifiers can be used to identify variable names, class names, method names and file names in a class, and so on.

    Naming rules:

      • (1) consists of letters, numbers, underscores, and $, and cannot begin with a number.
      • (2) Case sensitive.
      • (3) Do not use keywords and reserved words in Java.

    Keywords: are lowercase, jdk1.2 more strictfp (quasi-floating-point type), the keyword jdk1.4 more assert (assertion) keyword, jdk1.5 more enum (enum) keyword.

    True, FALSE, and Null strictly speaking should not be counted as keywords, it should be called the reserved word more appropriate.

    Habit:

      • (1) Identifiers conform to semantic information.
      • (2) package name all letters lowercase.
      • (3) The class name is capitalized in the first letter of each word, and other lowercase, such as: Tarenastudent.
      • (4) Variables and methods: The first word lowercase, starting with the second word capitalized, such as: Tarenastudent.
      • (5) Constant: All letters are capitalized, and each word is connected by _.

    Commonly used escape characters:

     "\b"   (BACKSPACE)  "\f"   (page change)  "\ n"   (newline)  "\ r"   (carriage return)  "\ t"  (horizontal tab (to next tab position))   (single quote) " \ ""   (double quotes)   "\ \"   (backslash)    
    Android

    Android

    297***[email protected]

    3 months ago (08-10)
  2. Amy

    143***[email protected]

    Eight basic types of Java: (by bytes)

    Boolean 1-byte 8bit (8-bit)

    byte byte type 1 bytes

    Char character type 2 bytes

    Short shorter integer 2-byte

    int integer 4-byte

    float Float (single-precision) 4 bytes

    Long Integer 8 bytes

    Double Doubles type 8 bytes

    The default integer type in Java is int, and if you want to define it as long, add L or L to the value

    The default float is a double-precision floating point, and if you want to define float, add F or F after the value

    One byte equals 8 bits, and 1 bytes equals 256 digits. 2^8

    An English letter or Arabic numeral takes one byte

    A kanji account of 2 bytes

Java basic syntax [2]

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.