I will summarize Java to deepen my understanding. I will update it from time to time.
References ☆ Kiyotaka Nakayama / Daigo Kunimoto "Introduction to Java for a refreshing 3rd edition"
The extension of the source file is ".java"
$ javac source file name ① .java source file name ② .java
$ javac Split.java SplitLogic.java
-Use a compiler (: software) to convert the source file into a class file ➡︎ (Creating a class file) -Extension is ".class" -Includes bytecode (code that allows the computer to recognize source code instructions)
$ java class file name
$ java Split
// Cannot start with java Split Logic Error: The main method cannot be found in class SplitLogic.
//パッケージに属したクラスの実行 $ java FQCN of the class to start
$ java splitapp.main.Split
-The interpreter (: software) uses the JVM (Java Virtual Machine) to decrypt the bytecode. -The class name included in the main method must be specified. ・ Therefore, the computer will operate as instructed.
jar -cvf class file name .jar * .class // Create
Write "Main-Class: class file name" in the "class file name.mf" file // Line break at the end of the line jar -cvfm class file name .jar class file name .mf * .class // create manifest file java -jar class file name.jar // execute
An archive file similar to a ZIP file that combines multiple classes into one
public class class name {* Class name starts with uppercase letters // Class block public static void main (String [] args) {// method block } } Double structure with blocks
Data type variable name;
[Integer] Small byte: quite small byte glasses; glasses = 7; short: small short age; age = 7; ⭐︎ int: Normal int salary; salary = 7777; long: Large long Japanese; Japanese = 124_000_000L;
[Decimal] Large float: Ambiguous float weight; weight = 60.0F; ✨ double: Normal double height; height = 177.7;
[True / False Value] boolean: true or false boolean isValid;
[letter] char: Only one character char color; color ='green';
[String] ⭐︎String: String of characters String name; name = "John"
Data type variable name = value;
String likes = "cat"; // Variable initialization * Simultaneous declaration and assignment likes = "dog"; // reassignment * "cat" is overwritten System.out.println (likes + "I like");
final data type constant name = initial value; * Constant names are basically all uppercase
final double PI = 3.14; // Declaration of constants int pie = 7; PI = 10; // Check for compilation errors System.out.println ("radius" + pie + "cm circle area is"); System.out.println(pie * pie * PI);
The value can be fixed to prevent rewriting
Consists of operands and operators
・ Refers to the value used in the formula -Specific specified values in the source code are called "literals". -The notation method of literals differs depending on the data type.
Special characters used in String and char types ¥ "Double quotation ¥'Single quotation ¥\ Yen symbol (¥) \ N Line break
Calculation processing according to the formula based on the three principles
The operator performs the calculation using the operand and arrives at the calculation result.
2 + 7 * 10 = 72 // Multiplication takes precedence (2 + 7) * 10 = 90 // Priority can be given by enclosing in parentheses If there are multiple operators, they take precedence according to Java rules
If there are multiple operators with the same precedence, the fixed directional order for each operator takes precedence.
Refers to the symbol used in the formula
・ All from the left ・ Higher priority
・ Similarly from the left ・ Higher priority
・ All from the right ・ Low priority ・ The last thing to be done
・ Also called unary operator ・ Same as JavaScript ・ Highest priority -It is desirable not to use it together with other operators (it may cause bugs).
float y = 7; // Automatic type conversion at the time of assignment double z = y; // Automatic type conversion at the time of assignment int w = 0.7; // Type smaller than type will result in compilation error byte q = 2; // byte. Exception to int type assignment to short type
Assignment to a type larger than each type automatically converts the value
int e = (int) 7.7; // cast operator
(Type name of conversion destination) Value; ・ Instruct forced conversion
[Demerit] -The contents of the data are lost because the data is converted even if part of the data is damaged. ➡︎ In the above case, the decimal point will not be output. It is recommended not to use it unless there is a good reason
long b = 7 + 7L; // Convert int to long double c = 7.7 * 2; // Convert int to double String msg1 = 7 + "I like"; // Convert int to String
・ The principle is the same type ・ When different types are used, they are automatically unified into a larger type.
Statement (argument);
int p = 1, o = 2;
int m = Math.max (p, o); // Compare values and substitute the larger one System.out.println (m); // Display on screen System.out.print (m); // Display on screen (no line breaks)
String age = "12";
int n = Integer.parseInt (age); // Convert a string to a number System.out.println ("Age is" + n + "");
int r = new java.util.Random (). nextInt (7); // Generate a random number System.out.println ("Age is" + r + "?");
System.out.println ("Enter your name"); String name = new java.util.Scanner (System.in) .nextLine (); // Receive one line of string input from the keyboard System.out.println ("How old?"); int age1 = new java.util.Scanner (System.in) .nextInt (); // Receive one integer input from the keyboard System.out.println ("Welcome!" + Age1 + "years old" + name + "san");
・ Consists of conditional expressions and blocks ・ The mechanism is similar to JavaScript
String type variable .equals (string to be compared)
if (str.equals ("Good morning")) ・ "==" Indicates equality ・ However, character strings cannot be compared with "=="
① if-else statement ② if statement
➡︎ If the else block is empty, it can be omitted entirely
➡︎ If statement can be made smart Condition ❶ It must be an expression of whether the left and right sides match. ❷ The comparison value is not a decimal value and a boolean value
➡︎ Prefix judgment (evaluate conditional expression before executing block)
do {
temp++;
System.out.println ("1 degree up"); } while(temp > 27); ➡︎ Postfix judgment (evaluate the conditional expression after executing the block)
for (int variable name = 0; variable name <repeating value; variable name ++)
for (int variable name = 1; variable name <repeating value; variable name ++) // Start loop variable from 1 for (int variable name = 0; variable name <repeating value; variable name + = n) // increase the loop variable by n for (int variable name = n; variable name> 1; variable name--) // Decrease the loop variable by 1 from n for (; variable name <n; variable name ++) // Do not initialize loop variable for (int variable name = 0; variable name <repeated value;) // do not repeat processing ・ Similar to JavaScript ・ Used when the number of repetitions is fixed
・ Similar to JavaScript ① break statement ② continue statement
①while (true) {
processing }
②for (;;) {
processing } Keep looping intentionally unless interrupted
Similar to JavaScript
Data type [] array variable name;
int[] scores;
Array variable name = new data type [value];
scores = new int[5];
① Data type [] Array variable name = new Data type [] {value}; ② Data type [] Array variable name = {value};
int[] scores = new int[] {10, 20, 30, 40, 50};
int[] scores = {10, 20, 30, 40, 50};
Array variable name.length
int num = scores.length;
String variable name.length ();
String str = "Learn Java"; System.out.println(str.length());
ArrayIndexOutOfBoundsException
Because you are using an element that does not exist
for (int i = 0; i <array variable name.length; i ++) { Processing using array variable name [i] }
for (int i = 0; i < scores.length; i++) {
System.out.println (scores [i]); // i changes for each loop }
int sum = 0; // Variable initialization for (int i = 0; i < scores.length; i++) { sum + = scores [i]; // Sum one subject at a time }
int count = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= 25) {
count ++; // Count the elements that meet the conditions } }
int[] seq = new int [10];
for (int i = 0; i < seq.length; i++) {
seq[i] = new jaba.util.Random().nextInt(4);
}
for (int i = 0; i < seq.length; i++) {
char[] base = {'A', 'T', 'G', 'C'};
}
System.out.println(base[seq[i]] + " ");
for (data type variable name: array variable name) { processing }
int[] scores = {10, 20, 30, 40, 50};
for (int value : scores) {
System.out.println(value);
}
・ For loops that take out elements one by one ・ It becomes a cleaner form than a normal for statement without the description of loop variables and subscripts.
boolean valid = true;
if (valid == true) {
int[] array = {2. 4. 6}
} // At this point array is out of memory
・ The 3 elements secured by new will continue to remain even after the block ends (garbage) -Just not referenced by any array variable ・ A mechanism that automatically searches for and cleans up such garbage
null int[] array = {1, 3, 5}; array = null; array[0] = 9;
・ Can be assigned only to reference type variables -Do not intentionally refer to an array (= cut off the reference)
NullPointerException
Occurs when using an array variable that stores null
Data type [] [] Array variable name = new Data type [Number of rows] [Number of columns];
int[][] scores = new int[3][3];
Array variable name [row subscript] [column subscript]
System.out.println(scores[1][1]);
-A name that combines processing codes written in multiple sentences into one -Note that the position of defining a method and the position of calling it are not always the same. ➡︎ Development is often done by multiple people -It is desirable that the method name shows the processing content.
[merit] (1) The code is easy to read, making it easier to understand. (2) The range of correction can be limited by dividing into methods for each function (making it easier to find the cause of the error). (3) Since the method can be reused, work efficiency can be improved.
① public static Return value data type Method name (argument list) { (2) Specific processing executed by calling a method }
public static void hello() {
System.out.println ( "Hello"); // method block = execution content } [Two-stage configuration] ① Statement of important matters ② Processing content
Method name (argument list);
public static void main(String[] args) {
System.out.println ("method call"); // main method block hello (); // method call methodA (); // methodA including methodB is called } public static void methodA() { System.out.println("A"); methodB(); } public static void methodB() { System.out.println("B"); } ・ It is not executed only by definition -There is no fixed order of method description (because the main method is the center)
Method name () // pass nothing Method name (value) // pass one Method name (value 1, value 2 ...) // pass multiple
① public static void main(String[] args) {
hello ("Tanaka"); // Definition of arguments (1) hello ("Sato"); hello ("Suzuki"); } public static void hello (String name) {// Define string type variable name System.out.println (name + "san, good evening"); }
② public static void main(String[] args) {
add (100, 200); // Definition of arguments (2) add(10, 20); } public static void add(int x, int y) { int ans = x * y; System.out.println(ans); }
❸ public static void main(String[] args) {
methodC ("Goodbye", 777); } public static void methodC (int x, String y) {// compilation error System.out.println(x + y); }
❹ public static void main(String[] args) {
int a = 7;
int b = 77;
add();
}
public static void add() {
int ans = a + b; // compilation error System.out.println(a + b); } -Be careful about the data type and order defined by the method. -A compile error will occur if each data type of the argument and variable is different. ・ Formal argument: Variable to be received ➡︎ x, y mentioned here -Actual argument: Variable to be passed ➡︎ 100, 200, 10, 20 mentioned here -Depending on the scope, the variable defined in the main method cannot be used in another method. -Local variables: Variables declared in the method ➡︎ main (), add () mentioned here Local variables with the same name in another method are completely different because they are valid only within that method.
public static Return value data type Method name (argument list) {// Return value data type is the same type as the value returned by return Specific processing performed by calling a method return Return value; // Specify the variable name or literal (100, "hello", etc.) for the return value. }
public static int add(int x, int y) {
int ans = x + y;
return ans;
}
-Use "void" when nothing is returned -The return statement has the meaning of "terminating the method" as well as "returning the value". ➡︎ Therefore, if you write the processing code after the return statement, a compile error will occur.
Data type variable name = method name (argument list); // method call takes precedence
① public static void main(String[] args) {
int ans = add (100, 200); // call System.out.println("100 + 200 = " + ans); }
② public static void main(String[] args) {
System.out.println (add (add (100, 200), add (10, 20))); // Use the return value as it is } ・ It is not always necessary to receive the return value as a variable
①public static void main(String[] args) {
System.out.println(add(7, 77));
System.out.println(add(7.7, 77.7));
System.out.println(add("yahoo", "google"));
}
public static int add(int x, int y) {
return x + y;
}
public static double add(double x, double y) {
return x + y;
}
public static String add(String x, String y) {
return x + y;
}
②public static void main(String[] args) {
System.out.println (add ("7 * 77 =" + add (1, 2))); // * is called
System.out.println (add ("7 * 77 * 2 =" + add (1, 2, 3))); // # is called
}
public static int add(int a, int b) {
return a + b; //*
}
public static int add(int a, int b, int c) {
return a + b + c; //#
}
-In principle, the same name cannot be given to the method (even if the processing contents are similar).
➡︎ Mechanism that makes it possible
[exception] (1) When the data type of the formal argument of the method is different (int, double, String mentioned here) (2) When the number of elements of the formal argument of the method is different (a ・ b, a ・ b ・ c mentioned here)
public static void main(String[] args) {
int[] array = {1, 3, 5};
printArray (array); // pass an array } public static void printArray (int [] array) {// Specify array as argument for (int element : array) { System.out.println(element); } } -Pass by value: A call that passes the value itself When using an array, the address of the element is copied instead of the value (1, 3, 5 here) Passing an address as an argument is called "passing by reference" ➡︎ Rewriting at the callee is reflected in the caller
public static void main(String[] args) {
int[] array = makeArray(3);
for (int i : array) {
System.out.println(i);
}
}
public static int[] makeArray(int size) {
int[] newArray = new int[size];
for (int i = 0; i < newArray.length; i++) {
newArray[i] = i;
}
}
String[] args
-Value passed to the program when the program is started -The value is passed to the main method
java program name argument list
java Sample abc def ghi
java Sample 1 2 3
-A method of sharing development (dividing classes) for each file ・ Therefore, the finished product of the program is often a collection of multiple source files.
public class SplitLogic {
public static int tasu(int a, int b) {
return (a + b);
}
public static int hiku(int a, int b) {
return (a - b);
}
}
public class Split {
public static void main(String[] args) {
int a = 7; int b = 1;
int total = SplitLogic.tasu (a, b); // Here int delta = SplitLogic.hiku (a, b); // here System.out.println ("Add" + total + ", subtract" + delta); } }
Since the processing method no longer belongs to the main method, it is necessary to specify the affiliation and call it.
A mechanism that can be classified and managed in groups for each class
package The name of the package to which it belongs;
package splitapp.main;
public class Split {
}
package splitapp.logics;
public class SplitLogic {
}
・ Must be written at the beginning of the source code ・ Lowercase letters are common -There is no parent-child relationship or hierarchical relationship between packages (each independent) -Default package: Does not belong to any package (also an anonymous package) import statement not available
Package name.Class name
package splitapp.main;
public class Split {
int total = splitapp.logics.SplitLogic.tasu (a, b); // here int delta = splitapp.logics.SplitLogic.hiku (a, b); // here }
To call a class in another package, you must specify the package to which it belongs.
import package name.class name;
package splitapp.main;
import splitapp.logics.SplitLogic; // When importing only SplitLogic import splitapp.logics. *; // When importing everything import splitapp.main. *; // When importing everything
//どちらの表記でも構わない int total = SplitLogic.tasu(a, b); int delta = splitapp.logics.SplitLogic.hiku(a, b);
・ FQCN can be omitted ・ Described after package ・ Input reduction function
・ Capacity of the name given ・ Name conflict: Classes with different contents compete for the same name. -The same name can be used for different packages (because it can be distinguished by FQCN) ➡︎ Therefore, it is necessary to avoid collision of package names. A package name that reverses the order of the company's domain is recommended (For java.example.com, com.example.java)
Java API public class Main { public static void main(String[] args) { int[] heights = {170, 150, 160, 180}; java.util.Arrays.sort (heights); // Call the sort method in the Arrays class of the java.util package for (int h : heights) System.out.println(h); } } } -A general term for packages and classes originally built into Java ・ Can be used freely ・ API reference: API manual (https://www.oracle.com/jp/java/technologies/javase/documentation/api-jsp.html)
[Representative package] · Java.lang: Indispensable classes (System, Integer, Math, Object, String, Runtime, etc.) Imported automatically -Java.util: Classes that are convenient for programming -Java.math: Classes related to numbers -Java.net: Classes that communicate -Java.io: Classes that perform sequential processing of data
・ Concept of componentization used when developing software
・ Be careful because what you learn and how you learn it is different from the basic grammar.
➡︎ Learn the idea of to reach the correct answer
, not the correct answer itself
・ Dividing the program into classes for each object that appears in the real world
⬅︎➡︎ Procedural programming (: You must define the procedure to execute line by line)
・ Since responsibility (responsibility for action and information retention)
is written in each class, there is no need to instruct each one.
➡︎ Each has a attribute
and a operation
to perform its responsibilities
[merit]
((1) It is possible to realize program development that is easy for humans to understand)
(② Program change becomes easy)
(③ It is easy to divert a part of the program)
➡︎Easy, fun and good things can be made
➡︎ Because it's just a story of recreating real-world objects and their movements in the virtual world on a PC
.
-Performers of virtual worlds (: computer memory area
) (creating classes)
➡︎ Instantiation
➡︎ In other words, the memory area allocated in the heap
(: that area)
-Since it does not work as it is, prepare a instructor class (including the main method)
separately from the class of each character
.
Class name Variable name = new Class name (); // Instance creation Variable name. Field name = Value; // Assign to field Variable name. Method name (); // Method call
public class Kamisama {
public static void main(String[] args) {
Sword s = new Sword();
s.name = "Chun Chun Seiba"; s.damage = 10;
Hero h1 = new Hero (); // Instance creation --Here the hero is born
h1.name = "Chun Chun Maru"; // Assign to field
h1.hp = 100;
h1.sword = s; --sword instance assigned to s
Hero h2 = new Hero();
h2.name = "Chanchanmaru"; h2 = h1; // Copy h1 to h2--Address information is copied (not the instance itself) h2.hp = 200;
System.out.println ("Brave" + h1.name + "was born.") System.out.println ("Equipped weapon is" + h1.sword.name + "."); --Brave h1 "no" sword "no" name h1.sit (3); // Method call h1.slip(); w.heal(h1); System.out.println ("Mushroom Alien" + m1.suffix + "has appeared."); h1.attack(); h1.run(); } }
-Object-oriented makes it easier to understand the contents of the main method
・ Reference
➡︎ Address information contained in variables
-The JVM is performing reference resolution
or address resolution
(: getting address information from a variable and accessing the address).
・ Independence
➡︎ If the same class has different instances, they should not be affected.
Define based on class diagram (: blueprint)
➡︎ One of UML (Unified Modeling Languages)
public class Hero {// Class declaration String name; // Attribute declaration int hp; Sword sword; --Equipment information
public void attack() {
System.out.println (this.name + "attacked with" + this.sword.name + "."); System.out.println ("damaged 5 to the enemy."); }
public void sleep () {// Declaration of operation--method this.hp = 100; // this keyword System.out.println (this.name + "rested and recovered."); } public void sit (int sec) {// Argument of how many seconds to sit this.hp + = sec; // Recover for a few seconds to sit down System.out.println (this.name + "is" + sec + "sit for a second."); System.out.println ("HP has recovered" + sec + "points recovered."); } public void slip() { this.hp-= 5; // HP decreases by falling System.out.println (this.name + "has fallen."); System.out.println ("5 damage"); } public void run() { System.out.println (this.name + "has escaped."); System.out.println ("Game Over"); System.out.println ("The last HP was" + this.hp + "."); } ---- public class Matango { int hp; int level = 10; // Specify initial value of attribute final int LEVEL = 10; // Constant field (uppercase recommended) char suffix; } ---- public class Sword { String name; int damage; } ---- public class Wizard { String name; int hp;
public void heal (Hero h1) {--When using a method as an argument h1.hp += 10; System.out.println (h1.name + "recovered 10 HP"); } }
-Variables declared in the field
➡︎ class block (name, hp here)
-Constant field
➡︎ Value non-rewritable variable (LEVEL here)
-Do not use static
in object-oriented methods
・ Member
➡︎ A general term for fields and methods
・ Do not omit this
(to eliminate malfunctions)
-You can create instances
and use class type variables for instances
by class definition.
➡︎ Types that can be used additionally
-String is also classified into the same class type
➡︎ Instantiation is possible with String variable name =" string ";
without using the new operator.
・ Has-a relationship
➡︎ One class uses another class as a field
Hero h; // Class type variable name Variable name;
Instance is used by putting it in a class type variable
➡︎ To identify a specific instance as a program
from among multiple instances with the same name that can exist in the virtual world
Method that is automatically executed after instantiation
➡︎ Cannot be called directly
(JVM does it based on the code)
[conditions] ① The method name is the same as the class name (2) There is no return value in the method declaration (including void)
public class class name { name of the class() { Processing content to be automatically executed } }
[Initial value of field]
Numeric type (int, short, long, etc.): 0
char type: \ u0000
boolean type: false
Array type (int [], etc.): null
Class type (String, etc.): null
public class Hero {
String name;
int hp;
Sword sword;
public void attack() {
abridgement
}
public void sleep() {
abridgement
}
public void sit(int sec) {
abridgement
}
public void slip() {
abridgement
}
public void run() {
abridgement
}
public Hero () {// Method that is automatically executed after instance creation
this.hp = 100;
}
}
----
public Hero (String name) {// Receive one character string as an argument * You must set a name for the instance
this.hp = 100;
this.name = name; --Initialize name field with argument value
}
public Hero () {--Create a constructor that doesn't take arguments
this.hp = 100;
this.name = "sample";
}
----
public class Kamisama {
public static void main(String[] args) {
Hero h1 = new Hero ("Pyonpyonmaru"); --Perform at the same time as the argument to be passed to the constructor
Hero h2 = new Hero ();-Since there is no argument, "Sampuru" is called. h2.hp = 200; } } ---- public class Kamisama { public static void main(String[] args) { Hero h1 = new Hero (); --Constructor sets HP100 h1.name = "Pyonpyonmaru"; h1.sword = s;
Hero h2 = new Hero();
h2.name = "Chun Chun Maru"; h2.hp = 200; --Can be changed with new numerical settings
System.out.println ("Brave" + h1.name + "was born."); System.out.println ("HP is" + h1.hp + "."); System.out.println ("Brave" + h2.name + "was born."); System.out.println ("HP is" + h2.hp + "."); } } -You do not have to set the initial value in the main method. -Overloading (overloading) is also possible with the constructor -If there are multiple constructors, the JVM will judge by looking at the arguments (only one works)
[exception]
If no constructor is defined in the class
Default constructor (: no arguments & no processing content)
is automatically added at compile time
this (argument); // Ask the JVM to call another constructor in the same class
public Hero(String name) {
this.hp = 100;
this.name = name;
}
public Hero() {
this ("sample");
}
Must be written at the head
of the constructor
Note that " this.member name "
is completely different from `
Recommended Posts