--package and import declarations apply to all classes in the same file
--The package declaration must be at the beginning of the source code (only comments can be written before the package)
--The java.lang package is a collection of basic classes and does not require an import declaration
--Using "\ *" does not import classes that belong to subpackages
ʻImport test. *Will import
test.MyClass1 but not
test.sub.MyClass2`
--Classes belonging to the default package (anonymous package) can only be accessed from classes belonging to an anonymous package. In the first place, import cannot be written and a compile error occurs.
--When accessing static fields and methods
import static jp.co.xxx.Sample.num
import static jp.co.xxx.Sample.print
You can omit the modifier if you set
** ʻimport static** instead of
static import`
--The entry point signature has the following format
- public static void main (String[] xxx)
- public static void main (String... xxx)
Any of.
--The main method is ** OK even if overloaded ** Of course, the signatures need to be different
--javac command (compile) has ** extension **, java command (execute) has ** no extension **
javac Main.java
java Main
--Primitive type
Data type | value |
---|---|
boolean | 1 bit |
char | 16 bit Unicode characters |
byte | 8 bit |
short | 16 bit |
int | 32 bit |
long | 64 bit |
float | 32 bit |
double | 64 bit |
Byte is 8 bits and I can remember twice from there int --long with float --double Note that there are positive and negative (Example: 0b11111111 (= 255) is not entered in byte (-128 to 127))
--Numeric literal defaults to ** int and double **
--Integer literal
Base number | Notation |
---|---|
Decimal number | 123 |
Hexadecimal | 0x1A8 |
8 base | 0123 |
Binary number | 0b011 |
--Numerical notation using "\ _" Do not use before or after the beginning / end / symbol ("." "L" "F" "0x" ...) Continuous is OK
--Char type --Character literals enclosed in single quotes --Unicode numbers starting with "\ u" in single quotes (character literals) --Numerical literals from 0 to 65535
Any of String literals (double quotes) are not allowed
--Only "\ _" and "$" can be used as identifiers. Numbers from the second letter
--The only literal that represents null is "null" ** "NULL" is not possible **
println (null)
prints "null"
--The relationship between class and instance is the relationship between copy source and copy.
--The assignment operator (= or + =) is only assigned after the operand has been evaluated.
int a = 3;
int b = a += 5; // a = 8, b = 8
--"-" Also works as a unary operator
int a = 10 * - 10; // a = -100
--For numerical literal compatibility, explicit cast is required when the range is large → small. However, for integer literals, it is OK if it is within the range.
byte a = 0b10000000; //int → byte is OK if it is out of range, but it is out of range, so a compile error
short b = 128 + 128; //Since it is within the range of short, int → short, but OK
int c = 2 * 3L; //Since long → int, compile error
float d = 10.0; //Since double → float, compile error (10).0f is OK)
--Boolean and numeric types are not compatible in Java
boolean a = 1; //Compile error
byte b = true; //Compile error
--Relational operator: - == - != - >, <, >=, <= --Cannot be used for anything other than numerical values - instanceOf
--instanceOf determines if an instance can be handled with the specified type
interface A {}
class B implements A {}
---
B b = new B();
System.out.println(b instanceOf B); // true
System.out.println(b instanceOf A); // true
false && x++ == 1; // false, x++Ignore
false & x++ == 1; // false, x++Be done
true || x++ == 1; // true, x++Ignore
true || x++ == 1; // true, x++Be done
--The priority of operators is -(), ++,-is the highest priority -** \ *, / and% are in the same row **
-"==": Identity "equals ()": Equivalence
--The equlas method of the Object class is the same, so it is assumed to be overridden. ** Receives Object class as an argument **, so if you change the argument type, it will not be overridden.
--If the same string literal appears in the code, the reference to the same instance will be reused. Mechanism called "constant pool" For string literals, a String instance is created in the constant memory space instead of the instance memory space. Explicitly new
String a = "test"; //Reference to a String instance created in constant memory space
String b = "test"; //Reference to a String instance created in constant memory space
System.out.println(a == b) //true, not only "equivalent" but also "same"
String c = new String("test"); // //Reference to String instance created in memory space for instance
System.out.println(a == c) // false
System.out.println(a.equlas(c)) // true
--The else if statement cannot break a line between "else" and "if"
if (Conditional expression A) hoge();
else
if (Conditional expression B) fuga();
else bar();
//This is equivalent to
if (Conditional expression A) hoge();
else {
if (Conditional expression B) fuga();
else bar();
}
--The condition of the switch statement is entered --Integer type less than or equal to int type and its wrapper --Characters, strings --Enumeration type
only ** boolean and long are not **
--Only ** constants ** can be entered in the case value of switch statements, that is, --Literal --final Declared variables
** Variables are not allowed in any of **
--It is customary to write the default in a switch statement at the end, it doesn't matter anywhere Writing the default first does not change "when it does not apply to any case" Not all default cases
--Array type variable declaration can be done with 0 elements
int[] a = new int[0]; //You can also create an array object with 0 elements
int[] b = new int[3];
ArrayList<Integer> c = new ArrayList<>();
System.out.println(a); // [I@677327b6
System.out.println(b); // [I@14ae5a5 * Unlike ArrayList, the contents are not displayed even if you println.
System.out.println(c); // []
--[] in the array type variable declaration can be after either the data type or the variable name.
//Both can be compiled
int[] a;
int b[];
int[][] c[];
--The number of elements cannot be specified when declaring an array type variable Array variables are references to array instances and are separate from array instantiation
int[3] a; //Compile error
int b[3]; //Compile error
int c[] = new int[3]; // OK. int[3]An array instance of is created and a reference to it is set in c
--The number of elements must be specified to create an array instance Variable is OK ** In the case of a multidimensional array, only the first dimension cannot be omitted **
int[] a = new int[3 * 5]; // ok
int x = 5;
int[] b = new int[x]; // ok
int[] c = new int[3.5]; //Compile error
int[] d = new int[]; //Compile error
int[][][] e = new int[3][4][5]; // ok
int[][][] f = new int[3][][]; // ok
int[][][] g = new int[][][5]; //Compile error
--The default element when creating an array instance is fixed --Numeric type: 0 - boolean:false --Reference type: null
--The contents of the array can be initialized with the array initialization operator {}
int[] a = {2, 3}; // ok
int[] b = new int[]{2, 3}; // ok
int[] c = new int[2]{2, 3}; //Compile error When using the initialization operator, do not specify the number of elements
int[] d = {}; //Ok without elements
int[] e;
e = {}; //Compile error Initialization operator can only be used when declaring array type variables
--Array type variables can be implicitly type converted to parent class array type variables (upcast)
Child[] c = new Child[]{new Child(), new Child()}
Parent[] p = c; // ok
--The array can be copied with the clone () method However, it is duplicated up to the first dimension In the case of a multidimensional array, the same instance is referenced in the second and subsequent dimensions.
--The array can also be copied using the arraycpy () method.
arraycpy(src, srcStartIndex, dst, dstStartIndex, numOfElements)
--The while statement does not cause a compile error even without processing
--Example: while (true); // Infinite loop
--Multiple variables can be declared in the initialization expression of the for statement, but only the same type Only initialization / update expressions can be used for multiple documents There is always one conditional expression
for (int i = 0, j = 10; true; i++, j++) {}// ok
for (int i = 0, long j = 10; true; i++) {}//Compile error
for (int i = 0; true, i < 10; i++) {} //Compile error
--In the for statement, even if the conditional expression is omitted, it is ok Infinite loop unless break is used
-** Since the reference variable is copied in the extended for statement **, changing the reference destination does not affect the original array.
Sample[] array = {new Sample(1), new Sample(2), new Sample(3)};
System.out.println(array[0].getValue()); // 1
for (Sample s : array){
s = new Sample(4);
System.out.println(s.getValue()); // 4
}
System.out.println(array[0].getValue()); // 1
// s.setValue(4)If so, the original array will also be affected.
--The extended for statement can only process one by one in the forward direction.
--By using a label, you can freely specify where to transfer control of continue and break (originally only the latest). Labels can be placed everywhere
--Variadic arguments
--Three periods after the argument type
- void sample (int... num){ System.out.println(num[0]); }
--Variadic arguments can only be used at the last argument
--Static fields and methods are placed in the "static area" when loading class files The definition of the other part is placed in the "heap area" and is read every time an instance is created. So static fields can be used without an instance
--Non-static method fields cannot be accessed from static methods
--Overload needs to have a separate signature Signature = method name + argument type / order ** You can't change the access modifier, argument name, and return type **
--Constructor restrictions --Align method name and class name -** Return type cannot be described ** -** If you write a return value, it will be interpreted as just a method, not a constructor ** --Can only be used with new -** Any access modifier is acceptable (private is also possible) **
--Initialization block ({} directly under the class) is executed before the constructor
-** Default constructor is not generated when you explicitly write a constructor ** Note that if you write a constructor with arguments, the default constructor without arguments will not be generated.
--In a subclass, ** the constructor of the super class must always be called at the beginning of its own constructor ** If not specified, super () will be inserted at the beginning of the code Therefore, if there is no super () in the parent class, a compile error will occur.
--Use this () to call another constructor This must be called first
--Access modifier
Modifier | Description |
---|---|
public | All OK |
protected | Only subclasses or classes in the same package |
None | Only classes in the same package |
private | Only from within the class |
--The following two are not carried over to the subclass --Constructor --private field methods
--Interface features --Cannot be instantiated -** Method is public only, even if omitted public ** --I can't have an implementation ({} cannot be described) -** Fields can be limited to the following ** --final (= constant without change) --static (= can be used without instantiation) --Implementation (realization) is implements, multiple realization is possible --You can create an interface that inherits the interface with extends --The concrete class must implement all the abstract methods of the interface Abstract classes don't have to
--Characteristics of abstract class --Cannot be instantiated --Ainoko of interface and concrete class That is, it has both abstract and concrete methods and can also define ** fields ** --A concrete class that inherits from an abstract class must implement all abstract methods --Abstract methods of abstract classes do not have to be public
--Override rules --The return value is the same or a subclass (= covariant return value) --Same signature -** Access modifiers are the same or looser ** --The abstract method of interface is public, so all concrete classes must also be public.
--A subclass has both a superclass and an instance of the subclass, and is apparently considered as one instance. --Therefore, in the subclass constructor, the superclass constructor must also be called first. --If a field with the same name is defined in the superclass and subclass, both are held separately. (However, the overridden method is considered as one instance) --When you refer to a field with the same name, which one to use depends on the type of the declared variable. --When referenced from a method, use the field of the class in which the method is declared.
class Parent {
String val = "P";
public String getVal1(){
return val;
}
public String getVal2(){
return val;
}
}
class Child extends Parent {
String val = "C";
public String getVal2(){
return val;
}
}
class Main {
public static void main (String args[]){
Parent p = new Parent();
Parent c = new Child();
System.out.println(p.val); // P
System.out.println(c.val); //Since it is declared as Parent, P
System.out.println(p.getVal1()); // P
System.out.println(c.getVal1()); //Since it is a method declared in Parent, P
System.out.println(p.getVal2()); // P
System.out.println(c.getVal2()); //C because it has been overridden
}
}
--About realization
interface A { public void abst(); }
class B { public void abst(); }
class C extends B implements A{ } // ok.Considered to implement the abstract method of A
--Methods and fields defined only in subclasses cannot be called when they are treated as parent classes.
--Cast = "Guarantee for compatibility with compiler"
--If you write a cast to an incompatible one, you will get an ** error ** at compile time.
--(String) 1 // Compile error
--Compile error even if you cast between classes that are not inherited
--When casting between classes that have an inheritance relationship
--Upcast (cast from subclass to superclass) is implicit and no problem
Because the compiler can decide for itself by extends
-** Downcast must be specified in the cast expression **
I can't see what type of instance I'm casting
If you can't cast (you were trying to cast an instance of a superclass to a subclass)
** Error at runtime **
class Parent {}
class Child extends Parent{ }
class Main{
public static void main(String args[]){
Parent c = new Child();
Parent p = new Parent();
Child c_ = (Child) c; // ok
Child p_ = (Child) p; //Compiles, but at runtime ClassCastException
}
}
--Local variables must not have names in the same scope Fields and local variables can be worn. Add this to distinguish
int num = 10;
if (num < 11){
int num = 20; //Compile error
int value = 100; //OK because the scope is different
}
int value = 200;
--Local variables must be explicitly initialized by the programmer
--try-catch-finally syntax ――The order cannot be changed - try --Required ・ Only one - catch --Can be omitted / Multiple descriptions are possible - finally --Omitted ・ Only one --Neither catch nor finally can be omitted
--Even if you return in catch, return after the finally statement is executed.
--If you are returning in both the catch and finally statements, it will be overwritten with finally return. Since it is an image that has a variable dedicated to return, rewriting the variable returned by finally will not be overwritten.
public static int sample1(){
try {
throw new Exception();
} catch (Exception e){
return 0;
} finally {
return 1;
}
}
public static int sample2(){
int val;
try {
throw new Exception();
} catch (Exception e){
val = 0;
return val;
} finally {
val = 1;
}
}
public static void main (String args[]){
System.out.println(sample1()); // 1
System.out.println(sample2()); // 0
}
--If an Exception occurs --Process with try catch --Declare throws in a method
You have to do one of the following. The above also applies to those who use the throws declared method ** The main method also requires one of the above two **
Error
RunTimeException --Out of range system - ArrayIndexOutOfBoundsException --Out-of-range access in arrays - IndexOutOfBoundsException --Out-of-range access in ArrayList - StringIndexOutOfBoundsException --Out-of-range access with string.charAt () --Illegal system - IllegalArgumentException --The argument preconditions are not observed - IllegalStateException ――I'm not ready --Other - ClassCastException - NumberFormatException - NullPointerException - SecurityException
String --String is immutable Once initialized, the field cannot be rewritten
--String is a subclass of CharSequence
--Basic methods of String
- replaceAll(".", "hoge")
--Replacement with regular expression
- replace("src", "dst")
--Simple replacement (all when multiple appear)
- charAt(index)
- indexOf("abc")
--If not -1
- subString(start, end)
subString(start)
- trim()
--Space, \ t (tab character), \ n \ r (newline)
--Only before and after the character string, do not remove it in the character string
- startsWith("a")
- endsWith("a")
- split("\\w\\s")
--Split by regular expression
-\ w: Word constituent characters
-\ s: Whitespace character
-\ d: Numbers
--Uppercase letters are reversed
- concat("a")
--Concatenation of strings
String a = "30" + 5; // 305
String b = "30" + 5 + 8; // = "305" + 8 = "3058"
String c = 5 + 8 + "30"; // = 13 + "30" = "1330"
String d = "hoge" + null; // = "hogenull"
--StringBuilder has a 16-character buffer by default --You can specify a buffer in the constructor
StringBuilder sb = new StringBuilder("abc");
System.out.println(sb.capacity()); // 3 + 16 = 19
StringBuilder sb2 = new StringBuilder(5);
System.out.println(sb2.capacity()); // 5
--StringBuilder methods - append(x) --x can contain all primitive types 10 is "10", true is "true" - insert(index, "hoge") - delete(start, end) - deleteCharAt(index) - reverse() - replace(start, end, "hoge") - subString(start, end) - String - subSequence(start, end) - CharSequence - toString() --Returns an internal string
Integer.parseInt("123")
--From strings to primitivesInteger.valueOf("123")
--From strings to wrapper classes
--These are case insensitive--Lambda expression --An interface that has only one method that needs to be implemented is called a "functional interface". --You can implement a method with a lambda expression
//Functional interface
interface Algorithm1 {
void perform(String name);
}
interface Algorithm2 {
String perform(String name);
}
---
Algorithm1 a = (String name) -> { System.out.println(name); }
Algorithm1 b = (name) -> { System.out.println(name); } //Argument type is optional
Algorithm1 c = name -> System.out.println(name); //If there is only one argument()Optional, if there is only one method{}Optional
Algorithm2 d = name -> { return "hello " + name + " !"; }
Algorithm2 e = name -> "hello " + name + " !"; //I need a return value{}When omitting, return cannot be described
Algorithm2 e = name -> return "hello " + name + " !"; //Compile error
--A variable with the same name as the local variable declared in the method cannot be used as the argument name of the lambda expression (same scope)
--To access a local variable declared outside a lambda expression from inside the lambda expression Must be a virtually final variable (a variable that never changes)
--Standard functional interface
- Consumer
DateTime
LocalDate --immutable for mutable Clendar --The moon begins 1
LocalDate.of(2018, 12, 24)
LocalDate.parse("2015-01-01")
--The basic format is yyyy-MM-dd
--DataTimeException for non-existent dates
LocalDate.of(2017, 1, 32) // DateTimeException
LocalTime
24hours
plusHours(10)
LocalDateTime --Combined LocalDate and LocalTime
Duration --Handling the time difference
Duration d = Duration.between(start, end)
Period --Handling date differences
Period p = Period.between(start, end)
Period p = localDate.until(target)
DateTimeFormatter -** ISO_DATE_TIME ** is the most standard?
localDateTime.format( DateTimeFormatter.ISO_DATE_TIME ) // 2018-08-31T00:00:00
ArrayList
add(element)
add(index, element)
set(index, element)
remove(element)
-** find and delete equal elements with equals () **
--Delete only the first one
--The elements behind it move up
--Apparently, if you call remove while reading in a loop,
ConcurrentModificationException is thrown except when removing at the end of the loop
If you don't like it, use iterator
--removeIf (lambda expression)
--The generics of List and ArrayList impose constraints and do not have to be (it becomes an Object type List).
tips --Compal error if there is an unreachable code
//Subclass Exception comes after
try {} catch (Exception e) {} catch (IOException e) { /** cannot reach **/ };
//Write the process after continue
for (int i : list){
if ( flg ) {
continue;
hoge(); // cannot reach
}
}
//Post-return processing
void sample(){
return;
hoge(); // cannot reach
}
Recommended Posts