graph LR
byte-->short
short-->int
char-->int
int-->long
long-->float
float-->double
/*Variable declaration*/
boolean varA; //Declaration only
varA = true; //Substitution only
Class varI //Declaration only(Reference type)
varI = new Class() //Substitution only(Reference type)
/*Constant declaration*/
static final data_type varJ = valA; // (static + )final modifier
/*Declaration*/
data_typeA[] arrayA = new data_typeA[index_max_value];
data_typeB[] arrayB = {valA, valB, valC, valD, valE};
data_typeC[] arrayC = new data_typeC[] {valF, valG, valH};
data_typeD arrayD[]; //In the variable name[]Can be attached
// X arrayD = {valI, valJ, varl}
arrayD = new data_typeD[]{valI, valJ, varl}
data_type[][] arrayE; //2D array → date_type[] arrayE[]It may be.
arrayE = new date_typeE[i][]; //The second subscript can be omitted. The first is not possible.
/*arrays class*/
Arrays.toString(arrayD); // "[valI, valJ, vall]"
Arrays.sort(arrayD); // {vall, valJ, valI}
/* List(interface) */
// X List<data_typeA> listA = new List<>();
List<data_typeA> listA = new ArrayList<>();
List<data_typeB> listB = new LinkedList<>();
List<data_typeC> listC = new CopyOnWriteArrayList<>();
List<data_typeD> listD = Arrays.asList(valA, valB); //Reading only
listD.add(valD); //Add to the end
listD.add(indexA, valE); //Insert in the middle
listD.set(indexA, valF); //Replacement
listD.get(indexA); //Get value
listD.indexOf(valF); //Get position
listD.size(); //Get the number of elements
listD.contains(valF); //Confirmation of existence
listD.remove(valF); //Delete
/* ---Below is the implementation class of List------------------------------- */
/* ArrayList ..Strong in search*/
//If you want to use a method that exists only in ArrayList, declare it below.(The same applies below)
ArrayList<data_typeE> listE = new ArrayList<>();
ArrayList listF = (ArrayList<data_typeE>)listE.clone(); //copy
/* LinkedList ..add to/Strong against deletion*/
LinkedList<data_typeG> listG = new LinkedList<>();
listG.push(); //Add to the beginning
listG.pop(); //Delete from the beginning
/* CopyOnWriteArrayList ..No synchronization required/Strong against multithreading*/
CopyOnWriteArrayList<data_typeH> listH = new CopyOnWriteArrayList<>();
/* Map(interface) */
// X Map<Integer, data_typeA> mapA = new Map<>();
Map<Integer, data_typeA> mapA = new HashMap<>();
Map<Integer, data_typeB> mapB = new LinkedHashMap<>();
Map<Integer, data_typeC> mapC = new ConcurrentHashMap<>();
Map<Integer, data_typeD> mapD = new TreeMap<>();
mapA.put(keyA, valA); //Add to the end
mapA.put(keyA, valB); //Replacement
mapA.get(keyA); //Get value
mapA.size(); //Get the number of elements
mapA.containsKey(keyA); //Key search
mapA.containsValue(valB); //Search for value
mapA.remove(keyA); //Delete
/* ---Map implementation class below------------------------------- */
/* HashMap ...Strong in search*/
HashMap<Integer, data_typeE> mapE = new HashMap<>();
/* LinkedHashMap ..Keep the order of insertion*/
LinkedHashMap<Integer, data_typeF> mapF = new LinkedHashMap<>();
/* ConcurrentHashMap ..No synchronization required/Strong against multithreading*/
ConcurrentHashMap<Integer, data_typeG> mapG = new ConcurrentHashMap<>();
/* TreeMap ..Subset that is conscious of the size of the key*/
TreeMap<Integer, data_typeH> mapH = new TreeMap<>();
// X Set<data_typeA> setA = new Set<>();
Set<data_typeA> setA = new HashSet<>();
Set<data_typeB> setB = new LinkedHashSet<>();
Set<data_typeC> setC = new TreeSet<>();
Set<data_typeD> setD = new HashSet<>(ListA); // List->Set
setD.add(valA); //Add value/Overwrite
setD.remove(valB); //Delete value
setD.size(); //Get the number of elements
setD.contains(valC); //Search for value
/* ---Implementation class of Set below------------------------------- */
/* HashSet ..Strong in search*/
HashSet<data_typeA> setA = new HashSet<>();
/* LinkedHashSet ..add to/Strong against deletion*/
LinkedHashSet<data_typeB> setB = new LinkedHashSet<>();
/* TreeSet ..Subset that is conscious of the size of the key*/
TreeSet<data_typeC> setC = new TreeSet<>();
Queue<data_typeA> queueA = new ArrayBlockingQueue<>(intA);
queueA.offer(valA); //add to
queueA.peek(); //output
queueA.poll(); //output/Delete
//LinkedList is an implementation of List and Deque
Deque<data_typeA> dequeA = new LinkedList<>();
dequeA.offerFirst(valA); //Add value to the beginning
dequeA.offerLast(valB); //Add value to the end
dequeA.peekFirst(valC); //Output of first value
dequeA.peekLast(valD); //Output of trailing value
dequeA.pollFirst(valE); //Output of first value/Delete
dequeA.pollLast(valF); //Output of trailing value/Delete
Reference: [Java] Stack queue memo
if (conditionA){
statementA //Statement, processing
} else if (conditionB) {
statementB //Statement, processing
} else if (!conditionC) {
statementC //Statement, processing
} else {
statementD //Statement, processing
}
/* {}abridgement...Only one line can be written in the nest*/
if (conditionA)
statementA //Statement, processing
else
statementB //Statement, processing
switch (varA) {
case valA: // varA =For valA
statementA //Statement, processing
//break statement...End of code block execution
break;
case valB:
case valC: // varA = valB,For valC
statementB //Statement, processing
break;
case default // varA = valA,valB,Other than valC
statementC //Statement, processing
break;
/*There is no limit to the order of cases. default can be at the beginning(not recommended) */
}
/*Repeat the sentence a specified number of times*/
for (data_type varA = valA; varA <= valB; valC++) {
statementA //Statement, processing
}
/* for(int a, int b, a < 3, a++, method()){like
Multiple initial values and update values can be defined. The updated value can also be called a method) */
/*Repeat from array collection*/
for (data_type varB : collectionA) {
statementB //Statement, processing
}
/*Combination of for Each and lambda expression(Output the elements of collectionB) */
collectionB.forEach(varC -> System.out.println(varC));
/*Repeat while conditional expression is True*/
while (conditionA) {
statementA //Statement, processing
}
do {
statementB //Statement, processing
} while (conditionB);
/*When repeating until the conditional expression becomes True*/
while (!conditionC){
statementC //Statement, processing
}
do {
statementD //Statement, processing
} while (conditionD);
X: //label
while (conditionA) {
switch(varA){
case valA: // statementA,Go through B
statementA //Statement, processing
case valB: //Only statement B passes
statementB //Statement, processing
/*break statement...End of code block execution*/
break;
case valC:
break X; //1st line "X:Jump to(Exit While)
default:
statementC //Statement, processing
/*continue statement...Move execution control to the next iteration*/
continue;
}
}
/* try ...Target processing*/
try{
statementA
/* catch ...Exception handling*/
} catch (xxxException e){
e.printStackTrace(); //Exception message(Basic this)
e.getClass().getName(); //Exception class name only
e.getMessage(); //Exception detail message only
StackTraceElement[] ste = e.getStackTrace(); //List of exceptions
/* finally ... try/After catch(try/Even if there is a return in catch)A process that must be performed.*/
} finally{
statementB //Statement, processing
}
// try-catch-The order of finally cannot be changed. try-catch, try-Optional such as finally.
/*throw phrase...Forced generation of exceptions*/
throw new ExceptionClassA();
/*throws clause...Pass the error to the caller*/
public class Main throws Exception { //If you attach it to main, there will be some exceptions
class | Overview | Occurrence timing |
---|---|---|
Error | Errors that cannot be dealt with by the program, such as problems in the execution environment | runtime(Non-inspection item) |
Exception - RuntimeException | Exception that can be prevented if the program is written correctly | runtime(Non-inspection item) |
Exception -Other than those above | Exception that cannot be prevented even if the program is written correctly. throws required | At compile time(Inspection item) |
package scope1.packageA; //Package declaration
import scopeB.libC; //Import libC from another package B
import static scopeC.libD.methodA; //Static import methodA method of libD of another package C
public class ClassA{
/*Method called at the beginning*/
//Other argument patterns for main(String... args), (String args[])
public static void main(String[] args){
ClassB instanceA = new ClassB("naiyo");
System.out.println(instanceA.getMethodA());
}
}
private class ClassB{
private data_type _fieldA;
/*static initializer...Static access, instantiation, etc.
First run when the class is loaded for the first time*/
static {
//Initialization process etc.
}
/*Initialization block...First run every time an instance is created*/
{
//Initialization process, etc.
}
/*constructor...First run every time an instance is created*/
Class2(){
this._fieldA = "";
}
/*The order is static initializer->Initialization block->constructor*/
/*Setter*/
data_type setMethodA(data_type varB){
this._fieldA = varB; //Argument and field name are the same
}
/*Getter*/
data_type getMethodA(){
return this._fieldA;
}
}
/*Access modifier*/
private class1{} //Only accessible from the same class
protected class class1{} //Only from the same class and subclass
class class1{} //Only from the same package
public class class1{} //From all classes
/*Other modifiers*/
abstract //Abstract class, abstract method
static //name of the class.Can be called by a member,Inaccessible to non-static members
final //Will not be overwritten(constant)
synchronized //Perform exclusive control for multiple processes
native //Native class, native method
strictfp //Operate floating point numbers according to IEEE754
transient //Excluded from serialization
volatile //Suppress field value cache
const //Multilingual constant modifier, not used in Java
/*Annotation*/
@Deprecated //Clarified as deprecated
@Override //Clarify that you are overwriting
@SuppressWarning //Suppress warning display
/*Order*/
@Annotation
public protected private
abstract static final synchronized native strictfp
/*Parent class*/
protected class ClassA{
protected data_type fieldA;
protected Class1(data_type varA){ //Parent class constructor
this.fieldA = varA;
}
protected void methodA(data_type varB){ //Parent class method
statementA
}
}
/*Child class*/
public class ClassB extends ClassA{
public ClassB(data_type varC){ //Child class constructor
super(varC); //Call the constructor of the parent class
}
@Override //Override modifier(As mentioned above)
public void methodA(data_type var2){
statementB //Statement, processing
}
}
/*Abstract class*/
protected abstract class ClassA{
protected data_type fieldA;
public Class1(data_type varA){
this.fieldA = varA
}
//Prerequisite method to be overridden(Abstract method)
public abstract void methodA(data_type varB);
}
/*Child class*/
protected abstract class ClassB{
@Override
public abstract void methodA(data_type varB){
statementA //Statement, processing
}
}
/*interface*/
public interface InterfaceA{
/*Basically, the types are listed as follows.*/
data_type CONST_A = "CONST_A"; //public static final is optional
data_type methodA(data_type varA);
/* ----Added from Java 8 below. Personally deprecated(Because it's complicated) ---- */
//default method...Something like a regular method of an abstract class
default void methodB(data_type varB){
statementA //Statement, processing
}
//static method...Can be called without an instance
public static methodC(data_type varC){
statementB //Statement, processing
}
}
/*Child class*/
public class ClassB extends InterfaceA{
public static void main(String[] args){
@Override
public static methodB(data_type varB){
// X ClassB.methodC
// X @Override methodC
InterfaceA.methodC(Interface1.CONST_A);
}
}
public class GenericClassA<TYPE>{
private TYPE _fieldA;
GenericClassA(TYPE varA){
this._fieldA = varA;
}
TYPE setMethodA(TYPE varB){
this._fieldA = varB;
}
TYPE getMethodA(){
return this._fieldA;
}
}
/*Generic method*/
public class ClassA{
public static <TYPE> ArrayList<TYPE> GenericMethodA(TYPE val1){
}
}
public class ClassA{
/*static member class... */
static class MemberClassA{}
/*Non-static member class... */
class MemberClassB{}
public static void main(String[] args) {
/*Local class... */
class LocalClassC{
public void localMethod(){}
}
LocalClassC localClassC = new LocalClassC();
localClassC.localMethod();
/*Anonymous class...Can be defined and instantiated at the same time*/
//Anonymous class that inherits from ArrayList type
List<data_typeC> list = new ArrayList<data_typeC>() {
public data_typeC method3() {
statements //Statement, processing
}
};
}
}
public class ClassB{
public static void main(String[] args){
//static member class call
ClassA.MemberClassA cAcA = new ClassA.MemberClassA();
//Non-static member class call
ClassA cA = new ClassA();
ClassA.MemberClassB cAcB = cA.new MemberClassB();
}
}
module-info.java
module moduleA{ // module-info.Described in a file called java.
export moduleA.lib; //Publish the library in this module
requires moduleB; //Describe the modules required by this module
}
Reference: Learn Module System / Java Modules
public enum EnumA{
/*Basic*/
elmA, elmB;
/*application-Add members, variables and methods*/
elmC(0), elmD(1);
private final int fieldA;
private setElmA(int varA){
this.fieldA = varA;
}
public int getVal(){
return fieldA;
}
public void outVal(){ // values() ..List of all enum elements
for (Enum2 enums : values()) {
System.out.println(enums.getVal()); // 0, 1
}
}
}
/* (args) -> { statements //Statement, processing} */
//In one case args-> statements
Collections.sort(listA, (a,b) -> {return b - a;});
/*Static method(class::method)*/
// list.forEach(i -> String.toString(i)));
list.forEach(String::toString);
/*Member method(this::method) */
// list.forEach(i -> this.toString(i)));
list.forEach(this::toString);
/*Generic method(class::<type> method) */
// list.forEach(i -> ClassA<typeA> methodA(i);));
list.forEach(ClassA::<typeA> methodA);
/*Instance method(object::method) */
// list.forEach(i -> System.out.print(i));
list.forEach(System.out::print);
/*constructor(class::new) */
ClassA instanceA = classA::new;
@FunctionalInterface
public interface FuncInterfaceA {
public data_typeA method(data_typeA varA);
}
/*Major standard functional interface*/
// Function.apply()Convert value
Function<String, Integer> func = x -> x.length();
System.out.println(func.apply("mojisu")); // 6
// Predicate.test()Make a judgment
Predicate<Integer> condA = i -> i != 0 ;
Predicate<Integer> condB = i -> i % 2 == 0 ;
condA.test(2); // true
condA.negate().test(1); // false (negate..denial)
condA.or(condB).test(1); // true (or judgment)
condA.and(condB).test(1); // false (and judgment)
// Supplier.get()Returns a value with no arguments
Supplier nowTime = () -> LocalDateTime.now();
System.out.println(nowTime.get()); // 2020-01-22 12:34:56
// Consumer.accept()Process based on arguments
Consumer<String> printA = str -> {
System.out.println("printA: " + str);
}
Consumer<String> printA = str -> {
System.out.println("printB: " + str);
}
Consumer<String> printAll = printA.andThen(printB); //Join
printAll.accept("" + System.currentTimeMillis());
Reference: Understanding Java 8 lambda expressions / [Java functional interface](http://www.ne.jp/asahi/hishidama/home/ tech / java / functionalinterface.html)
//Generate Stream
Stream<data_typeA> streamA = listA.stream(); // stream()Put on
IntStream intStreamA = IntStream.range(1,5); //Create Stream from numbers
//Intermediate operation
streamA.filter(p -> p.length() > 5); //Narrow down
streamA.map(p -> "[" + p + "]"); //replace
//Termination operation
List<data_typeB> listB = streamA.collect(Collectors.toList()); //conversion
//output
listB.forEach(System.out::println);
/*One liner*/
listA.stream()
.filter(p -> p.length() > 5)
.map(p -> "[" + p + "]")
.collect(Collectors.toList())
.forEach(System.out::println);
Method | Processing content | Example |
---|---|---|
map | Replace element with another value | .map(s-> s.getMethod()) |
flatmap | Combine Streams of elements | .flatmap(s -> s2.stream()) |
filter | Narrow down matching elements | .filter(s -> s.equals(1) |
limit | Narrow down to the specified number | .limit(2) |
distinct | Narrow down to unique elements | .distinct() |
sorted | Sort elements | .sorted((s1,s2) -> s2-s1) |
range | Make a sequence without including the trailing value | IntStream.range(1,5) |
rangeClosed | Make a sequence including the last value | IntStream.rangeClosed(1,5) |
Method | Processing content | Example |
---|---|---|
forEach | Iterate | .forEach(System.out::println); |
collect | Create results | .collect(Collectors.toList()); |
toArray | Convert to an array | .toArray(String[]::new); |
reduce | Aggregate values | .reduce((val1,val2) -> val1.add(val2)); |
toList | Return as List | .collect(Collectors.toList()); |
toSet | Return as Set | .collect(Collectors.toSet()); |
joining | Combine with delimiter | .collect(Collectors.joining(",")); |
groupingBy | Group elements | .collect(Collectors.groupingBy(s -> s.length())); |
Recommended Posts