Java basic syntax

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

  • Object : An object is an instance of a class with state and behavior. For example, a dog is an object, its state is: color, name, breed; behavior: waving tail, calling, eating and so on.
  • Class : A class is a template that describes the behavior and state of a class of objects.
  • Methods : Methods are behaviors. A class can have many methods. Logical operations, data modifications, and all actions are done in the method.
  • Instance variables : Each object has a unique instance variable, the state of the object is determined by the value of these instance variables.

The first Java program

Let's look at a simple Java program that will print the string Hello World

Examples

/* The first Java program
* It will print the string Hello World */
Public class HelloWorld {
public static void main ( String [ ] args ) {
System.out . println ( " Hello World " ) ; // Print Hello World }
}
The following will introduce how to save, compile and run this program step by step:
  • Open Notepad and add the code above.
  • Save the file name as: HelloWorld.java;
  • Open the cmd command window and enter the location of the target file, assuming C:\
  • Type javac HelloWorld.java in the command line window and press enter to compile the code. If there is no error in the code, the cmd command prompt will advance to the next line. (Assuming that the environment variables are set up).
  • Then type java HelloWorld Press Enter to run the program
You will see Hello World in the window
C : > javac HelloWorld.java
C : > java HelloWorld 
Hello World


Basic grammar

When writing Java programs, the following points should be noted:
  • 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 begin with a lowercase letter. If the method name contains several words, 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 file name (remember that Java is case-sensitive) and the file name has the suffix .java. (If the file name and class name are not the same, a compilation error will result.)
  • Main method entry : All Java programs are executed by the public static void main(String [] args) method.

Java identifier

All parts of Java need names. Class names, variable names, and method names are all referred to as identifiers.
About Java identifiers, the following points need attention:
  • All identifiers should start with the letters (AZ or az), dollar sign ($), or underscore (_)
  • The first character can be followed by any combination of letters (AZ or az), dollar sign ($), underscore (_), or digit
  • Keywords cannot be used as identifiers
  • Identifiers are case-sensitive
  • Examples of legal identifiers: age, $salary, _value, __1_value
  • Examples of illegal identifiers: 123abc, -salary

Java modifiers

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
We will discuss the Java modifier in depth in later chapters.

Java variables

There are mainly the following types of variables in Java
  • Local variables
  • Class variables (static variables)
  • Member variables (non-static variables)

Java array

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

Java enumeration

Java 5.0 introduced enumeration, enumeration limit variables can only be pre-defined values. Using enums can reduce bugs in the code.
For example, we design a program for a juice shop that will restrict juices to small cups, medium cups, and large cups. This means that it does not allow customers to order juices other than these three sizes.

Examples

Class FreshJuice {
enum FreshJuiceSize { SMALL , MEDIUM , LARGE } FreshJuiceSize size ; }
public class FreshJuiceTest {
public static void main ( String [ ] args ) {
FreshJuice juice = new FreshJuice() ;
juice . size = FreshJuice . FreshJuiceSize . MEDIUM; } }
Note: Enumerations can be declared individually or declared within a class. Methods, variables, constructors can also be defined in the enumeration.

Java keywords

The Java keywords are listed below. These reserved words cannot be used for the names of constants, variables, and any identifiers.
categoryKeywordsInstructions
Access controlPrivateprivate
Protectedbe protected
Publicpublic
Class, method, and variable modifiersAbstractDeclaration abstraction
Classclass
ExtendsExpanded, inherited
FinalFinal value, immutable
ImplementsImplementation (interface)
Interfaceinterface
NativeNative, native methods (non-Java implementations)
NewNew, create
StaticStatic
StrictfpStrict, precise
SynchronizedThread, synchronization
Transientshort
VolatileVolatile
Program control statementBreakJump out of the loop
CaseDefine a value for switch selection
Continuecarry on
Defaultdefault
Dorun
Elseotherwise
Forcycle
Ifin case
InstanceofExamples
Returnreturn
SwitchSelect execution based on value
Whilecycle
Error handlingAssertAssert whether the expression is true
CatchCatch an exception
FinallyAre there any exceptions to execute
ThrowThrows an exception object
ThrowsDeclaring an exception may be thrown
TryCatch an exception
Package relatedImportIntroduce
Packagepackage
basic typeBooleanBoolean
ByteByte type
CharCharacter type
DoubleDouble precision floating point
FloatSingle precision floating point
IntIntegral
LongLong integer
ShortShort type
Variable referenceSuperParent class, super class
ThisThis category
VoidNo return value
Reserved keywordsGotoIs a keyword but cannot be used
ConstIs a keyword but cannot be used
Nullair

Java annotations

Like C/C++, Java also supports single-line and multi-line comments. The characters in the comment will be ignored by the Java compiler.
/* This is the first Java program
* It will print Hello World
* This is an example of a multi-line comment */

Public class HelloWorld {
public static void main ( String [ ] args ) {
// This is an example of a single-line comment / * This is an example of a single line comment * /
System.out.println( " the Hello World " ) ; }
}

Java blank line

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

inherit

In Java, a class can be derived from other classes. If you want to create a class and you already have 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 methods and properties of existing classes without overwriting them. The inherited classes are called super classes, and the derived classes are called subclasses.

interface

In Java, an interface can be understood as a protocol in which objects communicate with each other. The interface plays an important role in inheritance.
The interface defines only the methods to be used for derivation, but the exact implementation of the method depends entirely on the derived class.

Comments