Basic Java grammar you should know first

Introduction

This article is intended to be read by:

Let's write the main method and run it

Understanding does not progress just by reading a site or a book. It is very important to write the code yourself and run the program.

1. Points of the main method

--The main method must belong to one class (eg Sample1). --The access modifier public means "can be called from anywhere". --The main Java function is public. --static is added to call the main method without instantiating the class. --The return value is void, which means that the main method returns nothing. --"String [] args" written in parentheses of main --String [] means an array of Strings --String is a type for storing a character string. Those classified as reference types. --args is the argument name. You can use the value passed as a command line argument in your program. --Enclose classes and methods in {}. --Standard output with System.out.print (). --The executable statement ends with;. --// is a comment line. Ignored when running the program.

Program example

Sample1.java


public class Sample1 {
    public static void main(String[] args){
        //Standard output here
        System.out.print("hello world");
    }
}

2. Run the program

--Make the file name (Sample1.java) and class name (Sample1) the same. --Note that the program execution is not "java Sample1 **. Class **". --After executing the program, the main method is executed first.

Execution example

> javac Sample1.java  #compile
> java Sample1        #Program execution

hello world       #Execution result

literal

point

—— Literals are the values themselves, such as letters and numbers.

Program example

Sample2.java


public class Sample2 {
    public static void main(String[] args){
        // 1.Character literal
    	System.out.println('A');
    	
    	char c1 = 'B';
    	System.out.println(c1);     //variable

    	//System.out.println('AB');  //Compile error
    	
    	System.out.println('\u0041');//Character code specification
    	
    	// 2.String literal
    	System.out.println("Hello");
    	
    	String str = "123";
    	System.out.println(str);
    	
    	//Supplement:Escape sequence
    	System.out.println("Hello\nWorld!!");
    	
    	// 3.Integer literal(Decimal number)
    	int i = 123;
    	System.out.println(i);
    	System.out.println(i+100);
    	
    	// 4.Floating point literal
    	double d = 3.14;
    	System.out.println(d);
    	System.out.println(d+1.54);
    	d = 2.712e-4;
    	System.out.println(d);
    	
    	// 5.Logical value literal
    	boolean b = true;
    	System.out.println(b);
    	b = (10 == 5);
    	System.out.println(b);
    	
    }
}

operator

point

--Arithmetic operators (+,-, *, /, etc.) --Assignment operator --Comparison operator --Logical operators --Bitwise operator --Operator precedence

Program example

Sample3.java


import java.util.Arrays;  //To display the contents of the array

public class Sample3 {
    public static void main(String[] args){
    	System.out.println("======= 1.Arithmetic operator=======");
    	// 1.1 increment
    	int a = 10;
    	int b = a++;            //Increment after substitution
    	System.out.println(b);  // int b = a;
    	                        // a = a + 1;
    	                        //Same as
    	
    	int x = 10;
    	int y = ++x;            //Increment before assignment
    	System.out.println(y);  // x = x + 1;
    	                        // int y = x;
    	                        //Same as
    	
    	// 1.Concatenation of 2 strings
    	String str1 = "Hello " + "World";
    	System.out.println(str1);
    	
    	System.out.println("======= 2.Assignment operator=======");
    	// 2.1 Assignment (primitive type)
		int x2 = 10;
		int y2 = x2;
		y2 += 1;
		System.out.println(x2);  //Result: 10
		System.out.println(y2);  //Result: 11
    	
    	// 2.2 Substitution (reference type)
		int[] x3 = { 10, 20, 30 };
		int[] y3 = x3;
		y3[0] += 1;
		System.out.println(Arrays.toString(x3)); //result:[11, 20, 30]、x[0]Note that the value of!!
		System.out.println(Arrays.toString(y3)); //result:[11, 20, 30]
    	
    	System.out.println("======= 3.Comparison operator=======");
    	// 3.1 Numerical comparison(Basic type,Reference type)
		int[] x4 = { 1, 2, 3 };
		int[] y4 = { 1, 2, 3 };
    	System.out.println(x4[0] == y4[0]);			//Base type comparison (result: true)
    	System.out.println(x4 == y4); 				//Reference type comparison 1 (result: false)
    	System.out.println(Arrays.equals(x4, y4)); 	//Reference type comparison 2 (Result: true)
    	
    	// 3.2 string comparison
    	String str2 = "abc";
    	String str3 = "ab";
    	str3 += "c";
    	System.out.println(str2==str3); 		//Result: false
    	System.out.println(str2.equals(str3));	//Result: true
    	
    	System.out.println("======= 4.Logical operator=======");
    	System.out.println("======= 5.Bit operator=======");
    }
}

Variable declaration

point

--There is a description to do variable declaration and initialization separately, and a description to do it at the same time.

Example of description to be done separately

Sample5.java


public class Sample5 {
    public static void main(String[] args){
    	// 1.Variable declaration
    	// [Format]Data type name Variable name;
    	int idata;
    	String str;
    	
    	// 2.Value assignment
    	// [Format]Variable name=value;
    	idata = 100;
    	str = "abcdef";
    	
    	//Substitution is "==Note that it is not!
    	// idata == 100;Will result in a compilation error
    	
    }
}

Example of description to be done at the same time

Sample6.java


public class Sample6 {
    public static void main(String[] args){
    	// 1.Variable declaration and value assignment
    	// [Format]Data type name Variable name=value;
    	int idata = 100;
    	String str = "abcdef";
    }
}

Primitive type (basic data type)

point

--Primitive types are the types of variables that are the basis of Java. -It is distinguished from the "reference type" described later. --8 types of primitive types --Integer --byte type --8-bit (1 byte) data --- Integer from -128 to 127 --short type --16-bit data --An integer from -32768 to 32767 --int type --32-bit data --- Integer value from -2147483648 to 2147483647 --long type --64-bit data --- Integer value from 9223372036854775808 to 9223372036854775807 --Floating point numbers --float type --32-bit single precision floating point number --The number of valid digits is 6 --Double type --64-bit double precision floating point number --The number of valid digits is 15 --Logical type --Boolean type --True / false value (true or false)

Program example

Sample4.java


public class Sample4 {
    public static void main(String[] args){
    	System.out.println("======= 1.byte type=======");
    	byte b1 = 127;
    	System.out.println(b1);		
    	b1 += 1;
    	System.out.println(b1);		// -It becomes 128 (overflow)
    	
    	System.out.println("======= 2.short type=======");
    	short s1 = -32768;
    	System.out.println(s1);		
    	s1 -= 1;
    	System.out.println(s1);		//It becomes 32767 (overflow)
    	
    	System.out.println("======= 3.int type=======");
    	int i1 = s1;
    	i1 += 1;
    	System.out.println(i1);		// 32768(correct)
    	
    	System.out.println("======= 4.long type=======");
    	//long l1 = 9223372036854775807; 	//Compile error
    	long l1 = 9223372036854775807L;		//correct
    	System.out.println(l1);
    	
    	System.out.println("======= 5.float type=======");
    	//float f1 = 3.14; 	//Compile error
    	float f1 = 3.14F; 	//correct
    	System.out.println(f1);
    	
    	System.out.println("======= 6.double type=======");
    	double d1 = 3.14; 
    	d1 = d1 + 5.2e3;
    	System.out.println(d1);

    	System.out.println("======= 7.boolean type=======");
    	boolean bl1 = true;
    	System.out.println(bl1);
    	bl1 = (d1 < 3);				//Since d1 is greater than 3, the result is false
    	System.out.println(bl1);
    	
    	System.out.println("======= 8.char type=======");
    	char c1 = 'a';
    	char c2 = 'Ah';
    	//char c3 = "ab";		//Compile error:Cannot store strings
    	System.out.println(c1);
    	System.out.println(c2);
    }
}

Reference type

point

--In Java, variable types other than primitive types are classified as "reference types". --A typical example of a reference type is "String"

Program example

Sample7.java


public class Sample7 {
    public static void main(String[] args){
    	String str = "Hello";	//The string is"(Double quotation)Enclose in
    	
    	str += "World!!";
    	
    	System.out.println(str);// "HelloWorld!!"Displayed as
    	
    }
}

What is the difference between a primitive type and a reference type?

point

――Both represent "variable type". ――The difference is the "value to put in the variable". --In the primitive type, the "value" itself is put in the variable. --100, 200, 0, etc. for integers --For letters, ‘a’, ‘a’, etc. --True, false for logical type --For the reference type, the variable contains "memory address value (memory location where the value is stored)". --If it is a character string type String, an address value with the character string "abcdef" (address 1000, etc.)

Program example

Sample8.java


public class Sample8 {
    public static void main(String[] args){
    	//Primitive type
		int x = 10;
		int y = x;
    	
    	//Reference type
		String s1 = "abc";
		String s2 = s1;
    }
}

What is contained in a primitive type variable is the "value" itself

image.png

What is contained in the reference type variable is "memory address value"

The character string "abc" is entered at address 1000. image.png

Array

Program example 1

Sample9.java


public class Sample9 {
    public static void main(String[] args){
    	// 1.Array variable declaration
    	// [Format]Data type name[]Array name;
    	int[] ai;
    	String[] as;
    	
    	// 2.Reserve area for array
    	// [Format]Array name=new type name[Element count];
    	ai = new int[5];
    	as = new String[10];
    	
    	// 3.Array initialization
    	// [Format]Array name[Element number] =initial value;
    	//Note: Element numbers start with "0"
    	ai[0] = 1;
    	ai[1] = 2;
    	as[0] = "abc";
    	as[1] = "defg";
    }
}

Program example 2

Sample10.java


public class Sample10 {
    public static void main(String[] args){
    	//Method 1: Combine array variable declaration and area allocation into one
    	// [Format]Data type name[]Array name=new type name[Element count];
    	int[] ai1 = new int[5];
    	String[] as1 = new String[10];
    	
    	//Method 2: Array variable declaration,Secure area,Combine initialization into one
    	// [Format]Data type name[]Array name= {Initial value 1,Initial value 2,・ ・ ・};
    	int[] ai2 = {1, 2, 3};
    	String[] as2 = {"abc", "de", "fghij"};
    }
}

Do you know the three major elements of programming?

It is an important concept common to all programming languages, not just Java.

1. Sequential processing (sequential processing)

The processes must be executed in order from the top (top) to the bottom (end) of the program.

Program example 1

Sample12.java


public class Sample12 {
    public static void main(String[] args){
    	//The execution result is "1" no matter how many times you do it., 2, 3, 4,Displayed in the order of "5"
    	System.out.println("1"); 
    	System.out.println("2"); 
    	System.out.println("3"); 
    	System.out.println("4"); 
    	System.out.println("5"); 
    }
}

Program example 2

Sample13.java


public class Sample13 {
    public static void main(String[] args){
    	//Same when calling a method.
    	//The execution result is "1" no matter how many times you do it., 2, 3, 4,It is displayed in the order of "5".
    	System.out.println("1"); 
    	sub();
    	System.out.println("5"); 
    }
	
	public static void sub(){
    	System.out.println("2"); 
    	System.out.println("3"); 
    	System.out.println("4"); 
	}
}

2. Conditional branch

So-called if statement or switch statement. It is used when changing the flow of the program, such as when a certain condition is met and when it is not met, and when you want to perform different processing.

Program example

Sample14.java


//Execution result
//i is an even number.
//j is an odd number.
//k is an even number and 10 or less.
//D
public class Sample14 {
    public static void main(String[] args){
    	int i = 10;
    	int j = 9;
    	int k = 8;
    	int l = 2;
    	
    	// 1.1 if statement
    	if(i % 2 == 0){
    		System.out.println("i is an even number."); 
    	}
    	
    	// 1.2 if-else statement
    	if(j % 2 == 0){
    		System.out.println("j is an even number."); 
    	}else{
    		System.out.println("j is an odd number."); 
    	}
    	
    	// 1.3 if-else if statement
    	if(k % 2 == 0 && k > 10){
    		System.out.println("k is even and greater than 10."); 
    	}else if(k % 2 == 0 && k <= 10){
    		System.out.println("k is an even number and 10 or less."); 
    	}else{
    		System.out.println("k is an odd number."); 
    	}
    	
    	//2 switch statement
    	switch (l){
    	case 0:
    		System.out.println("zero"); 
    		break;
    	case 1:
    		System.out.println("Ichi"); 
    		break;
    	case 2:
    		System.out.println("D"); 
    		break;
    	default:
    		System.out.println("Other"); 
    		break;
    	}
    }
}

3. Iterative processing (repetitive processing)

So-called for statement and while statement. Used when repeating a certain process.

Program example

Sample15.java


//Execution result
//  [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
//  [200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
//  [300, 300, 300, 300, 300, 300, 300, 300, 300, 300]
import java.util.Arrays;

public class Sample15 {
    public static void main(String[] args){
    	int[] ai = new int[10];
    	
    	// 1.for statement: Set 100 for all elements of the array
    	for(int i = 0; i < ai.length; i++){
    		ai[i] = 100;
    	}
    	System.out.println(Arrays.toString(ai)); 
    	
    	// 2.while statement: Set all elements of the array to 200
    	int j = 0;
    	while(j < ai.length){
    		ai[j] = 200;
    		j += 1;
    	}
    	System.out.println(Arrays.toString(ai)); 
    	
    	//Extra edition Of course.There is a method that does not use iterative processing, but it is inefficient.
    	ai[0] = 300;
    	ai[1] = 300;
    	ai[2] = 300;
    	ai[3] = 300;
    	ai[4] = 300;
    	ai[5] = 300;
    	ai[6] = 300;
    	ai[7] = 300;
    	ai[8] = 300;
    	ai[9] = 300;
    	System.out.println(Arrays.toString(ai)); 
    }
}

Make a method

point

--A method (function) is a collection of processes. --Define the process with one method, such as when performing the same process in multiple places. --There are two methods, "class method" and "instance method". Let's start with the class method. --Access modifier: public, private, etc. --static: required --Return value: Type of value returned to the method caller (void if nothing is returned) --Dummy argument: Value to be passed to the method (omitted when nothing is passed)

Class method declaration

Access modifier static return value method name(Formal argument) {
Method processing;
   :
}

Program example

Sample11.java


import java.util.Arrays;  //Required to display the contents of the array
public class Sample11 {
    public static void main(String[] args){
    	int[] ai = new int[5];
    	
    	//Pass a value (actual argument) when calling a method
    	//In the case below, the actual arguments are "ai" and "0".
    	setArray(ai, 0);
    	System.out.println(Arrays.toString(ai)); //result:[0, 0, 0, 0, 0]

    	setArray(ai, 100);
    	System.out.println(Arrays.toString(ai)); //result:[100, 100, 100, 100, 100]
    }
	
	//Method to set the specified value in the array
	//argument(Formal argument)     int[]array An array to set the value
	//int val value
	//Return value(Return value)None
	public static void setArray(int[] array, int val){
		for(int i = 0; i < array.length; i++){
			array[i] = val;
		}
	}
}

reference

Recommended Posts

Basic Java grammar you should know first
Java basic grammar
Java basic grammar
Java basic grammar
[Java] I personally summarized the basic grammar.
Java basic knowledge 1
[Java] Basic structure
[Java] [Basic] Glossary
Java exercises [Basic]
After all, if you learn first, I think Java
Java review ① (development steps, basic grammar, variables, data types)
Java (while statement) basic problem that beginners did first
About Android basic grammar
I first touched Java ②
Basic knowledge of computer science and its practice that you should know for improving performance
I first touched Java ③
java basic knowledge memo
I first touched Java ④
First gradle build (Java)
Do you know Decorator?
Java basic date manipulation
Java basic naming conventions
Java learning memo (basic)
I first touched Java
[Java] Basic method notes
Java basic data types
Basic Java OOps concepts
Java reserved word summary that you do not know unexpectedly