JAVA beginner notes

Simple understanding of the basic rules and syntax of java

Learning website: Java tutorial | rookie tutorial

Beginner Java

Java language is a pure object-oriented programming language

Java (Standard Edition)


  • JDK : Java Development Kit
  • JRE : Java Runtime Environment
  • JVM : JAVA Virtual Machine

JDK Download

public class Hello {
    public static void main(String[] args) {
        //Output a Hello,World!

IDEA (JAVA development software)
IDE: integrated development environment

IDEA official website: Paid and free versions

psvm : public static void main(String[] args)

sout : System.out.println();

Java basic syntax

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

  • Case sensitive: 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.
  • Method name: all method names should start with lowercase letters.
  • Source file name: the source file name must be the same as the class name. When saving a file, you should use the class name as the file name (remember that Java is case sensitive), and the suffix of the file name is java. (if the file name and class name are different, it will lead to compilation errors).
  • Main method entry: all Java programs are executed by the public static void main(String[] args) method.

Java keyword

keyword describe
abstract Abstract method, modifier of abstract class
assert Whether the assertion condition is satisfied
boolean Boolean data type
break Jump out of loop or label code segment
byte 8-bit signed data type
case A condition of a switch statement
catch Match with try to catch exception information
char 16 bit Unicode character data type
class Define class
const not used
continue The rest of the loop body is not executed
default Default branch in switch statement
do Loop statement, the loop body will be executed at least once
double 64 bit double precision floating point number
else Branch taken when the if condition is not true
enum Enumeration type
extends Indicates that a class is a subclass of another class
final Indicates that a value cannot be changed after initialization, that the representation method cannot be overridden, or that a class cannot have subclasses
finally Designed to complete the executed code, it is mainly for the robustness and integrity of the program. The code is executed whether there are exceptions or not.
float 32-bit single precision floating point number
for for loop statement
goto not used
if Conditional statement
implements Indicates that a class implements an interface
import Import class
instanceof Test whether an object is an instance of a class
int 32-bit integer
interface Interface, an abstract type, has only the definition of methods and constants
long 64 bit integer
native The presentation method is implemented in non java code
new Assign a new class instance
package A series of related classes form a package
private Represents private fields or methods, which can only be accessed from within the class
protected Indicates that a field can only access subclasses or other classes in the same package through a class or its subclasses
public Represents a common property or method
return Method return value
short 16 digit number
static Represents a class defined at the class level and shared by all instances
strictfp Floating point comparisons use strict rules
super Represents the base class
switch Select statement
synchronized Represents a block of code that can only be accessed by one thread at a time
this Means to call the current instance or another constructor
throw Throw exception
throws Define the exceptions that the method may throw
transient Modify fields not to be serialized
try Indicates that the code block needs to handle exceptions or cooperate with finally, indicating whether to throw exceptions and execute the code in finally
void The tag method does not return any value
volatile Tag fields may be accessed by multiple threads at the same time without synchronization
while while Loop

Java annotation

public class MyFirstJavaProgram{
   /* 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){
       // This is an example of a single line comment
       /* This is also an example of a single line comment */
       System.out.println("Hello World"); 

Java objects and classes

It's the same as python

  • Object: an object is an instance of a class with state and behavior. For example, a dog is an object, and its status includes: color, name and variety; Behaviors include wagging tail, barking, eating, etc.
  • Class: a class is a template that describes the behavior and state of a class of objects.

public class Dog{
  String breed;
  int age;
  String color;
  void barking(){
  void hungry(){
  void sleeping(){

A class can contain the following types of variables:

  • local variable
  • Member variable
  • Class variable

A class can have multiple methods. In the above example, barking(), hungry() and sleeping() are all methods of Dog class.

Construction method

When creating an object, at least one constructor must be called. The name of the constructor must have the same name as the class. A class can have multiple constructors.

public class Dog{
    public Dog(){
    public Dog(String name){
        // This constructor has only one parameter: name

create object

Objects are created from classes. In Java, the keyword new is used to create a new object. Creating objects requires the following three steps:

  • Declaration: declare an object, including object name and object type.
  • Instantiation: use the keyword new to create an object.
  • Initialization: when using new to create an object, the constructor will be called to initialize the object.

Access member variables and member methods through the created object, as follows:

/* Instantiate object */
Object referenceVariable = new Constructor();
/* Accessing variables in a class */
/* Accessing methods in classes */


public class Man {
    int stage;
    public Man(String name){

    public void setAge(int age){
        stage = age;

    public int getAge(){
        return 2020-stage;

    public void ageif(){
            System.out.println("Old man");
        else {
            System.out.println("little fresh meat");

    public static void main(String[] args) {
        int v;
        // instantiation 
        Man student = new Man("Xiao Wang");
        // Call method
        v = student.getAge();
        System.out.println("Year of birth:"+v);

Source file declaration rules

  • There can only be one public class in a source file
  • A source file can have multiple non-public classes
  • The name of the source file should be consistent with the class name of the public class. For example, if the class name of the public class in the source file is Employee, the source file should be named Employee java.
  • If a package should be defined in the first line of a package file.
  • If the source file contains an import statement, it should be placed between the package statement and the class definition. If there is no package statement, the import statement should be at the top of the source file.
  • The import statement and package statement are valid for all classes defined in the source file. You cannot declare different packages for different classes in the same source file.

Java basic data type

Two data types of Java:

  • Built in data type
  • Reference data type

Built in data type

The Java language provides eight basic types. There are six numeric types (four integers, two floating-point types), one character type, and one Boolean.


Type default

data type Default value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char 'u0000'
String (or any object) null
boolean false

reference type

  • In Java, variables of reference type are very similar to C/C + + pointers. The reference type refers to an object, and the variable pointing to the object is the reference variable. These variables are specified as a specific type when declared, such as Employee, purchase, etc. Once a variable is declared, the type cannot be changed.
  • Objects and arrays are reference data types.
  • The default value for all reference types is null.
  • A reference variable can be used to refer to any compatible type.
    Example: site = new site ("Runoob").

Java constants

Constants cannot be modified while the program is running.

In Java, the final keyword is used to modify constants. The declaration method is similar to that of variables:

final double PI = 3.1415927;

Both string constants and character constants can contain any Unicode character. For example:

char a = '\u0001';
String a = "\u0001";

Automatic type conversion

Integer, real (constant) and character data can be mixed. In the operation, different types of data are first transformed into the same type, and then the operation is carried out.

Convert from low-level to high-level.

low  ------------------------------------>  high

byte,short,char—> int —> long—> float —> double 

Data type conversion must meet the following rules:

  1. Cannot type convert boolean type.

  2. You cannot convert an object type to an object of an unrelated class.

  3. Cast must be used when converting a high-capacity type to a low-capacity type.

  4. Overflow or loss of accuracy may occur during conversion

  5. The conversion of floating-point numbers to integers is obtained by discarding decimals, not rounding

Cast type

  1. The condition is that the converted data types must be compatible.

  2. Format: (type)value type is the data type to be cast

public class Tansf {
    public static void main(String[] args) {
        int i1 = 123;
        byte i = (byte)i1; //Force conversion

Implicit cast
3. The default type of integer is int.

  1. This is not the case for floating-point types, because when defining a float type, the number must be followed by f or F.

Java variable type

In the Java language, all variables must be declared before use. The basic format of declaring variables is as follows:

type identifier [ = value][, identifier [= value] ...] ;
int a, b, c;         // Declare three int integers: a, b, c
int d = 3, e = 4, f = 5; // Declare three integers and give initial values
byte z = 22;         // Declare and initialize z
String s = "runoob";  // Declare and initialize string s
double pi = 3.14159; // The double precision floating-point variable pi is declared
char x = 'x';        // Declare that the value of variable x is the character 'x'.

The variable types supported by the Java language are:

  • Class variables: variables independent of methods, decorated with static (shared by all instances).
  • Instance variables: variables independent of methods, but without static modification.
  • Local variables: variables in the methods of a class.
public class Variable{
    static int allClicks=0;    // Class variable 
    String str="hello world";  // Instance variable 
    public void method(){ 
        int i =0;  // local variable

Java local variable

  • Local variables are declared in methods, construction methods or statement blocks;
  • Local variables are created when methods, construction methods, or statement blocks are executed. When they are executed, the variables will be destroyed;
  • Access modifiers cannot be used for local variables;
  • A local variable is only visible in the method, constructor or statement block that declares it;
  • Local variables are allocated on the stack.
  • Local variables have no default value, so they can only be used after initialization after being declared.
public class Man {
    int stage;
    public Man(String name){

    public void setAge(int age){
        stage = age;

    public int getAge(){
        return 2020-stage;

    public void ageif(){
            System.out.println("Old man");
        else {
            System.out.println("little fresh meat");

    public static void main(String[] args) {
        int v;
        // instantiation 
        Man student = new Man("Xiao Wang");
        // Call method
        v = student.getAge();
        System.out.println("Year of birth:"+v);

Instance variable

  • Instance variables are declared in a class, but outside methods, constructor methods and statement blocks;
  • When an object is instantiated, the value of each instance variable is determined;
  • Instance variables are created when the object is created and destroyed when the object is destroyed;
  • The value of the instance variable should be referenced by at least one method, construction method or statement block, so that the external can obtain the instance variable information through these methods;
  • Instance variables can be declared before or after use;
  • Access modifiers can modify instance variables;
  • Instance variables are visible to methods, constructors, or statement blocks in a class. In general, instance variables should be set to private. You can make instance variables visible to subclasses by using access modifiers;
  • Instance variables have default values. The default value of a variable of type 0 is null, and the default value of a variable of type 0 is Boolean. The value of the variable can be specified at the time of declaration or in the construction method;
  • Instance variables can be accessed directly through variable names. But in static methods and other classes, you should use the fully qualified name: obejectreference VariableName.
public class Employee{
    // This instance variable is visible to subclasses
    public String name;
    // Private variable, visible only in this class
    private double salary;
    //Assign a value to name in the constructor
    public Employee (String empName){
        name = empName;
    //Set the value of salary
    public void setSalary(double empSal){
        salary = empSal;
    // Print information
    public void printEmp(){
        System.out.println("name : " + name );
        System.out.println("salary : " + salary);

    public static void main(String[] args){
        Employee empOne = new Employee("RUNOOB");

Class variable (static variable)

  • Class variables, also known as static variables, are declared in the class with the static keyword, but must be outside the method.
  • No matter how many objects a class creates, a class has only one copy of the class variable.
  • Static variables are rarely used except when declared as constants. Constants refer to variables declared as public/private, final and static types. Constants cannot be changed after initialization.
  • Static variables are stored in the static storage area. It is often declared as a constant, and static is rarely used alone to declare variables.
  • Static variables are created the first time they are accessed and destroyed at the end of the program.
  • Has similar visibility to instance variables. However, in order to be visible to the users of the class, most static variables are declared as public.
  • Default values are similar to instance variables. The default value of numeric variable is 0, the default value of Boolean is false, and the default value of reference type is null. The value of a variable can be specified at the time of declaration or in the construction method. In addition, static variables can be initialized in static statement blocks.
  • Static variables can be through: classname Variablename.
  • When a class variable is declared as public static final, it is generally recommended to use uppercase letters for the name of the class variable. If the static variable is not of public or final type, its naming method is consistent with that of instance variable and local variable.
public class Employee {
    //salary is a static private variable
    private static double salary;
    // DEPARTMENT is a constant
    public static final String DEPARTMENT = "Developer";
    public static void main(String[] args){
    salary = 10000;
        System.out.println(DEPARTMENT+"average wage:"+salary);

Tags: Java

Posted by Eratimus on Thu, 19 May 2022 21:18:15 +0300