I tried to summarize Java learning (1)

This is a summary of what I learned in the reference text for learning Java. I omitted the detailed explanation and decided to summarize the points as a memorandum of my own.

Reference material

A refreshing introduction to Java 2nd edition

1. Basic configuration

Describe as follows. Enter your favorite class name in "Class name" and do the same for the file name. Example) Class name → TestJava ファイル名→TestJava.java

public class class name{
  public static void main(String[] args) {
  
  "Processing content"

  }
}

2. Run

Write "test" as the following content in a file, compile it, and execute it.

public class TestJava{
	public static void main(String[] args){
		System.out.println("test");
	}
}

compile

javac TestJava.java



 Execution (TestJava.java is created by compiling, but ".class" is not added at runtime)
```java testjava```

 Output result
```test```

## 3. Line feed (println)
 The line feed of the display content to be output as standard is switched by the method. The \ <br> tab in html.

public class Kaigyo {   public static void main(String[] args) {

System.out.print("print is");     System.out.print("No line breaks");     System.out.println("");     System.out.println("println");     System.out.println("Make a line break");   } }


 Output result

print does not break println Make a line break


 * From here, only the method processing is described.

## 4. Evaluate large values (Math.max)

int a =10; int b =100; //Math.max(①,②)The larger value is adopted int big = Math.max(a,b); System.out.println("Math.Evaluated with max method." + a + "When" + b + "The big one is" + big );


 Output result

#### **`Math.Evaluated with max method. 10 and 100 are the largest 100`**
```Evaluated with max method. 10 and 100 are the largest 100


## 5. Convert strings to numbers (Integer.parseInt)

String age = "30"; //Convert String type to int type int n = Integer.parseInt(age); System.out.println("When converted to a number" + ( n + 1 ) + "Will be" ); System.out.println("When not converting to a number" + ( age + 1 ) + "Will be" );


 Output result
 By comparison, it can be seen that n converted to a numerical value is added, and age as a character string is combined without being added.

When converted to a number, it will be 31 If you do not convert it to a number, it will be 301.

    	
## 6. Random
 Randomly display numbers greater than or equal to 0 and less than the value specified by "nextInt". Only "nextInt (6)" is displayed as 0-5. If you want to display from 1 to 6, set "nextInt (6) + 1" and 1 will be added to the generated random number, so the range from 0 to 5 will be 1 to 6.

int r = new java.util.Random() .nextInt(6)+1; System.out.println("Roll the dice" ); System.out.println("The result of the dice is" + r + "is" );


 Output result

Roll the dice The result of the dice is 6


## 7. Input reception (Scanner (System.in))
 You can receive input information from the keyboard during execution.

System.out.println("Please enter your name." ); //Accepts the input of one line of character string from the keyboard. nextLine is a string String gest = new java.util.Scanner(System.in).nextLine();

System.out.println("Please enter your age." ); //Accepts the input of one integer from the keyboard. nextInt is a number int tosi = new java.util.Scanner(System.in).nextInt();

System.out.println ("Welcome," + tosi + "of age" + gest + "Mr.");


 Execution result

Please enter your name. ○○○ ← Input from the keyboard Please enter your age. △△ ← Input from keyboard Welcome, Mr. ○○○, aged △△


## 8. Relational operator
 Conditional symbol for branching the process used in the conditional expression

 |operator|meaning|
 |:--:|:--|
 |==|Left side and right side are equal|
 |!=|The left side and the right side are different|
 |>|The left side is larger than the right side|
 |<|The left side is smaller than the right side|
 |>=|Left side is greater than or equal to right side|
 |<=|Left side is less than or equal to right side|

 * When comparing character strings, use "character string type variable .equals (comparison character string)".
 Example of use)

String moziretu = new String("Comparison"); String moziretu2 = new String("Comparison");  if(moziretu.equals(moziretu2)) {    System.out.println("OK");  }else{  System.out.println("NG");  }


## 9. Logical expression

 |operator|meaning|
 |:--:|:--|
 |&&|~ And|
 |pipe|~ Or|
 |!|Reversal of conditional expression|

 ※pipe=||

if((age >= 18 && grender ==1 ) || (age >= 16 && gender ==0 )) { //age is 18 or higher and gender is 1 or age is 16 or higher and gender is 0

//When the condition is negated if(!( age == 10 )) { //age is not 10

    	
## 10. Conditional branch
 * From here, the execution result will not be described, so if you cannot imagine the processing result, please try it on your own terminal.

 ① if statement
 There are 3 patterns of writing, if statement, if-else statement, if-else if-else statement.

 if statement
 If the conditional expression is true, execute the process. If not, do nothing.

if( kakunin.equals( "OK" )) { System.out.println("Start fortune-telling");      }


 if-else statement
 If the conditional expression is true, execute the process. If this is not the case, execute else processing.

if( kakunin.equals( "OK" )) { System.out.println("Start fortune-telling");      }else{ System.out.println("Exit the fortune-telling app"); }


 if-else if-else statement
 If the condition is not met, how to evaluate under another condition. Specify another condition with else if.

System.out.println("Do you want to use the Omikuji app?");

System.out.print("Y/N:");
String ck = new java.util.Scanner(System.in).nextLine();

if( ck.equals( "Y" ) || ck.equals( "y" )) { System.out.println("Your fortune has come out.");

	int omikuji = new java.util.Random().nextInt(9);
omikuji++;

	if(omikuji ==1 ) {
		System.out.println("The result is Daikichi");
	} else if(omikuji <=3 ) {
		System.out.println("The result is Nakayoshi");
	} else if(omikuji <=6 ) {
		System.out.println("The result is Kokichi");
	} else if(omikuji <=9 ) {
		System.out.println("The result is bad");
    //if-else if-The else statement may or may not use the last else
	} else {
		System.out.println("The result is terrible");
	}
} else {
	System.out.println("Exit the Omikuji app");
}
    	
 ② switch statement
 If there are multiple conditions, the process may be refreshed by using a switch statement.
 [Switch statement rule]
 -">", "<", "! =", Etc. are not used in all conditional expressions that compare whether the left and right sides match.
 -The values to be compared are integers, character strings, and character matches, not decimals or boolean values.
 -It is not a conditional expression but a variable name that is written immediately after the switch.
 ・ Next to the case is a value and a colon
 -Break statement at the end of case processing
 -The default label can be omitted if no other processing is required.

System.out.println("Would you like to run the Omikuji app again?");

System.out.print("Y/N:");
String ck2 = new java.util.Scanner(System.in).nextLine();
if( ck2.equals( "Y" ) || ck2.equals( "y" )) {
	System.out.println("Your fortune has come out.");
	
	int omikuji2 = new java.util.Random().nextInt(4);
	omikuji2++;
	
	switch (omikuji2) {
	case 1:
		System.out.println("The result is Daikichi");
		break;
	case 2:
		System.out.println("The result is Nakayoshi");
		break;
	case 3:
		System.out.println("The result is Kokichi");
		break;
	case 4:
		System.out.println("The result is bad");
		break;
	case 5:
		System.out.println("The result is terrible");
		break;
	}
} else {
	System.out.println("Exit the Omikuji app");
}

 Unless the process is explicitly interrupted by a break statement after each case statement, the process under that condition will continue to be executed. That's because the switch statement just jumps to the process that meets the conditions.
 However, the example below is a pattern that uses two conditions without writing a break statement.

System.out.println("Would you like to run the Omikuji app again?");

System.out.print("Y/N:"); String ck3 = new java.util.Scanner(System.in).nextLine(); if( ck3.equals( "Y" ) || ck3.equals( "y" )) { System.out.println("Your fortune has come out.");

int omikuji3 = new java.util.Random().nextInt(9);
omikuji3++;

switch (omikuji3) {
case 1:
	System.out.println("The result is Daikichi");
	break;

case 2:
case 3:
	System.out.println("The result is Nakayoshi");
	break;

case 4:
case 5:
case 6:
	System.out.println("The result is Kokichi");
	break;

case 7:
case 8:
case 9:
	System.out.println("The result is bad");
	break;

case 10:
	System.out.println("The result is terrible");
	break;
}

} else { System.out.println("Exit the Omikuji app"); }

    	
## 11. Repeat
 ① while statement
 There are two variations of the while statement.

 while statement (prefix judgment)
 Make a conditional decision before executing the block.

int temperature =25; //Repeat this block if the while condition is met while (temperature >20) { temperature--; System.out.println("I lowered the temperature by 1 degree"); }


 do while statement (postfix judgment)
 After executing the block, the condition is judged.

System.out.print("Y/N:"); String ck4 = new java.util.Scanner(System.in).nextLine(); if( ck4.equals( "Y" ) || ck4.equals( "y" )) {

int temperature2 =25; do { temperature2--; System.out.println("I lowered the temperature by 1 degree"); } while(temperature2 >20); } else { System.out.println("Finish"); }

    		
 ② for sentence
 [For statement rule]
 ・ For ((1) Variable initialization processing; (2) Repeat condition; (3) Repeat end processing)
 -Variables declared elsewhere cannot be used
 -The number declared in the for statement disappears after execution, so it can be reused.
 ・ How to increase / decrease the value in the for statement i + = 2 | Decrease by 1 i--

for( int i =0 ; i <10 ; i++ ) { System.out.println( "for statement repeat" + ( i + 1 ) + "Week"); }


 It is also possible to go out the loop variable and omit the initialization process from for.

int i = 0 ; for(; i < 5 ; i++ ) { System.out.print( "for statement repeat" + ( i + 1 ) + "Week →"); }

   
 When the loop of the for statement is doubled.
 		

//Multiplication table System.out.println("It is a multiplication table.");

for( int x = 1; x < 10; x++) { for( int y =1; y < 10; y++) { System.out.print( x * y ); System.out.print(" "); } System.out.println(""); }


 The break statement interrupts the iterative process itself.

//Multiplication table //In the break statement, skip after the target process System.out.println("Multiplication table(break statement), Up to 5 steps.");

for( int x = 1; x < 10; x++) { if( x == 6 ) { break; } for( int y =1; y < 10; y++) { System.out.print( x * y ); System.out.print(" "); } System.out.println(""); }


 The continue statement interrupts only the target process and proceeds to the next iteration.

//Multiplication table //Skip only the target process with the continue statement System.out.println("Multiplication table(continue statement), Skip the fifth step.");

for( int x = 1; x < 10; x++) {
	if ( x == 5 ) {
	continue;
	}
	for( int y =1; y < 10; y++) {
		System.out.print( x * y );
		System.out.print(" ");
	}
	System.out.println("");
}

 How to create an infinite loop intentionally
 * Repeat forever unless forced to terminate
 It is generally made by the following two methods.

 ① while (ture) {processing}
 ② for (;;) {processing}

    	
## 12. Array
 -Create array: "Type [] Array variable name = new type [5];"
 -You can check the number of elements with the array variable name.length.

 In the following example, an array is created, the number of elements is confirmed, and the value put in the array (score [1]) is confirmed.

int[] score = new int[5]; int kakunin = score.length; score[1] = 30; System.out.println("Array values:" + kakunin); System.out.println("score[1]The value of the:" + score[1]);

		
 Variables are not initialized automatically, so if you do not set the initial values as shown below, a compile error will occur.

int x; System.out.println(x);


 Array variables are automatically initialized.
 int, double, etc. → 0
boolean→false

 In the following cases, 0 is output.

int[] score2 = new int[5]; System.out.println("score2[1]The value of the:" + score2[1]);


 In the following cases, false is output.

boolean[] score3 = new boolean[5]; System.out.println("score3[1]The value of the:" + score3[1]);


 In String type, if the initial value is not set, null is returned.

String[] score4 = new String[5]; System.out.println("score4[1]The value of the:" + score4[1]);

    	
 Abbreviation notation
 ・ Even if you don't put a number in [], you can use {} to allocate.
 -The new array variable name can be omitted.


//score5 o~Set 4 elements int[] score5 = new int[] { 20 ,30 ,40 ,50 ,60 }; //score6 o~Set 4 elements int[] score6 = { 20 ,30 ,40 ,50 ,60 };

System.out.println("score5[3]The value of the:" + score5[3]); System.out.println("score6[4]The value of the:" + score6[4]);


 Loop the array
 By setting the number of elements in the repetition condition of the for statement, the repetition is performed by the number of elements in the array.
 for (int i = 0; i <array variable name.lenght; i ++);

int[] score7 = new int[] { 100 ,200 ,300 ,400 ,500 }; for( int i = 0 ; i < score7.length ; i++ ) { System.out.println(score7[i]); }


 Try to calculate the sum and average using an array
    	

//Store points in an array int[] score8 = { 80 , 85 , 70 , 70 , 80 }; int sum = 0 ;      //Iterative processing for the number of arrays for( int i = 0 ; i < score8.length ; i++ ) { //Add array values to sum variable sum = sum + score8[i]; } System.out.println("sum:" + sum); //Divide the number of elements from sum to calculate the average   int ave = sum / score8.length;     System.out.println("ave:" + ave);


 Extended for statement
 -For (element type arbitrary variable name: array variable name)
 -For statement used to easily write a loop that retrieves array elements one by one

 Looking at the example below, you can see that it is fairly simple.
 for statement: for (int i = 0; i <score8.length; i ++) {
 Extended for statement: for (int value: score9) {

int[] score9 = { 100 , 90 , 100 , 100 , 90 }; int sum2 = 0 ; for( int value : score9 ) { sum2 = sum2 + value; } System.out.println("sum2:" + sum2); int ave2 = sum / score9.length; System.out.println("ave2:" + ave2);

 	
 Array length and string length ()
 -For arrays, count the number of elements with "array variable name.length"
 -For character strings, count the number of characters with "character string variable name.length ()"

String s ="Developed with JAVA"; System.out.println( s + "Is" + s.length() + "It is a character." );


 A two-dimensional array
 -Declaration-> Element type [] Array variable name = new Element type [Number of rows] [Number of columns]
 -Array variable name [row subscript] [column subscript]

 In the following example, the number of elements in the parent array and child array is displayed.

int[][] score10 = { { 10 , 20 ,30 } , { 40 , 50 , 60 } }; System.out.println("Show number of lines" + score10.length ); //Parent array(Number of lines)Show System.out.println("Show the number of columns" + score10[0].length ); //Child array(Number of columns in element 0)Show


## 13. Garbage collection
 A mechanism to automatically delete unused memory that is not referenced to prevent memory pressure
 If you put null in the reference type variable, the reference will be cut (if it is not referenced from anywhere, it will be subject to garbage collection)

 The following example is intentionally unreferenced.

int[] a = { 1 , 2 , 3}; a = null; a[0] = 10; System.out.println(a[0]); In the above case, the reference is cut, so "NullPointerException" is output.


## 14. Method
 Method definition

public static return value method name (argument list){ What to do when the method is called }


 Creation example

public static void hello(String name){ System.out.println( name + "Hi,"); }

	
 Use of return value
 Put the calculation formula in ans and use the content to return by putting the value in the red method

public static int ret(int a, int b){ int ans = a + b; return ans; }

	
 How to call the method
 Method (argument list) * Specify variables, etc. that you want to pass at the time of calling in the argument list separated by commas.

public static void main(String[] args){ hello("Taro"); hello("Jiro");

int ans = ret(100,50);
System.out.println("The return value is:" + ans);

System.out.println(ret(ret(10,20) , ret(30,40)));
ret(10,5);

}


## 15. Overload
 -Normally, the same method cannot be used, but it can be used if the type is different. The definition of the same name is called overload
 -Overload is possible if the information after the return type (method signature: method name, argument type / number / order) is different.

 Example of use

//int type public static int ret(int a, int b){ return a + b; }

//double type public static double ret(double a, double b){ return a + b; }

//String type public static String ret(String a, String b){ return a + b; }

//Overload is possible even if the number of arguments is different public static int ret2(int a, int b){ return a + b; }

public static int ret2(int a, int b, int c){
	return a + b + c;
}

## 16. Use an array for method arguments and return values
 Since the array is passed for each address, not the contents of the variable, changing the callee will have an effect as it is.

//Put an array in the argument(Use extended for statement) public static void ckArray(int[] array){ for(int x : array){ System.out.println(x); } }


//Pass the array in a method call public static void methArray(int[] array){ for(int i =0; i < array.length; i++){ array[i]++; } }


//Pass an array as the return value(Use extended for statement) public static int[] retArray(int size){ int[] newArray = new int[size]; for(int i = 0; i < newArray.length; i++ ){ newArray[i] = i; } return newArray; }


## 17. Command line arguments
 You can receive a string array by executing the String type array of the main method with an argument at runtime.

public class CmdLine { public static void main(String[] args){ //Name as the first argument System.out.println("Hello," + args[0] +"Mr."); //Occupation in the second argument System.out.println("Occupation is" + args[1] +"is not it"); } }


 Create a file with the above contents, compile it, and execute it as follows.
```java cmdline Taro engineer```

 Execution result

Hi, Taro Occupation is an engineer


 That is all for this summary.
 In addition, I plan to post when the learning content is accumulated.


Recommended Posts

I tried to summarize Java learning (1)
I tried to summarize Java 8 now
I tried to summarize Java lambda expressions
I tried to implement deep learning in Java
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to summarize the basics of kotlin and java
I tried to summarize the methods used
I tried to summarize the Stream API
What is Docker? I tried to summarize
I tried to summarize the methods of Java String and StringBuilder
I tried to summarize about JVM / garbage collection
java I tried to break a simple block
[Must see !!!] I tried to summarize object orientation!
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
I tried to break a block with java (1)
[Introduction to Java] I tried to summarize the knowledge that I think is essential
[After learning Progate] I tried to summarize form_with while comparing with form_tag
I tried Drools (Java, InputStream)
I tried using Java REPL
I tried to verify yum-cron
I tried metaprogramming in Java
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
I tried to summarize the state transition of docker
[Java] I tried to solve Paiza's B rank problem
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to summarize various link_to used this time
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
Java learning (0)
I tried to create a java8 development environment with Chocolatey
I tried to chew C # (indexer)
I tried to modernize a Java EE application with OpenShift.
[JDBC] I tried to access the SQLite3 database from Java.
I tried UDP communication with Java
I tried to explain the method
I tried using Java8 Stream API
I tried to summarize personally useful apps and development tools (development tools)
I tried using JWT in Java
I tried to summarize personally useful apps and development tools (Apps)
I tried using Dapr in Java to facilitate microservice development
I tried to understand nil guard
I tried to make a client of RESAS-API in Java
What I researched about Java learning
I tried to chew C # (polymorphism: polymorphism)
I tried to summarize object orientation in my own way.
I tried using Java memo LocalDate
I tried to explain Active Hash
I tried using GoogleHttpClient of Java
I tried to summarize what was asked at the site-java edition-
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
Special Lecture on Multi-Scale Simulation: I tried to summarize the 5th
I tried setting Java beginners to use shortcut keys in eclipse