java programming basics

Basic syntax

Variable / constant declaration

 String str = null;    //variable
 final String STR = "msg";    //constant
 long l = 1111111111L;    //Long type is declared with L at the end
 float f = 1111.111F;    //Float type is finally declared with F
 double d = 1111.111;    //Decimal point becomes double
 char c = 'c';    //char type is''so
 str = "a\na\ta";    //\n:new line\t:tab

 //Declare int as a reference type
 Integer I = new Integer(32);
 int n = I.intValue();

 //Name of how to declare
 Integer I2 = 2;    // auto boxing
 int i = 1;    // auto unboxing
Mold initial value
Reference type null
boolean false
char \u0000
byte,short,int,long 0
float,double 0.0

operator

Operators have a priority, with the highest priority from the top of the table.

operator Expression join start point(Right is executed from the right side)
++(rear) --(rear) (cast) left
! ++(Before) --(Before) right
new right
* / % left
+ - left
< > <= >= instanceof left
== != left
& ^ | left
&& || left
?: right
*= /= %= right

if

 if (Conditional expression) {
     //processing
 } elseif (Conditional expression) {
     //processing
 } else {
     //processing
 }

By the way, you can omit {}, In that case, the bottom line of the if and else clauses is executed.

switch

 String singou = "red";
 switch (singou) {
     case "red":
            //processing
     break;
     case "yellow":
         //processing
     break;
     case "blue":
         //processing
     break;
     default:
         //processing
 }

default is executed in all cases. If there is no break, everything below it will be executed Available types are byte, short, int, char, enum, String

while dowhile

 while (Conditional expression) {
     //processing
 }

 do {
     //processing
 } while (Conditional expression);

Processing is executed while the conditional expression is true. It is the iron plate that increments the variables used in the conditional expression in the process. The difference between while and dowhile is the location of the decision.

for

 for (int i=0; i<5; i++){
     if (i < 2) {
          continue;    //Next loop
     } else {
          break;       //End of loop
     }
 }

Write for ((1) counter declaration; (2) conditional expression; (3) increase / decrease of counter variable). ①, ②, and ③ can be omitted respectively. for (;;); is not a mistake.

 class Nest {
    public static void main(String[] args) {
        int num[][] = {
                        {0, 1, 2},
                        {3, 4, 5},
                        {6, 7, 8}
                      };
        int i = 0;
        label:
        while(true) {
            int j = 0;
            while(j < 3) {
                System.out.print(num[i][j]);
                j++;
                if(i == 1) break label;
            }
            i++;
        }
    }
}

Class structure

class

 public class Animal {
    //constructor
    Animal(){
        System.out.println("new Animal created");
    }
    //Constructor with arguments
    Animal(String species){
        System.out.println("new " + species + " created");
    }

    void animalMethod() {
        System.out.println("this is animal method!");
    }

    void characteristic() {
        System.out.println("I'm alive!");
    }
}

interface

 //Interface declaration
 interface Breath {
    //Member variables become static final without permission
    String breath = "Breathing!";
    //Interface methods have no body
    void breath(String breath);
}

Next, a child class that implements the Animal class and the interface.

 //Inheritance and interface implementation
 public class Dog extends Animal implements Breath{
    //The constructor is implicitly super()Will be done
    //You can specify a constructor with parent arguments by explicitly specifying it.
    Dog(){
        super("Dog");
    }

    //override
    //Error if you do not override the interface abstract method.
    @Override
    public void breath(String breath) {
        System.out.println(breath);
    }

    //override
    @Override
    public void characteristic() {
        System.out.println("I have 4 legs!");
    }
 }

main function

 public class Main {

    public static void main(String[] args) {

        Dog dog = new Dog();        //①new Dog created

        dog.animalMethod();         //②this is animal method!

        //All interface member variables are static final
        dog.breath(Breath.breath); //③Breathing!

        dog.characteristic();      //④I have 4 legs!

        Animal dogA = new Dog();  //⑤new Dog created

        //dogA.breath();          //⑥

        dogA.characteristic();    //⑦I have 4 legs!
    }
 }

① is the creation of Dog instance, and the constructor of Dog class is called. ② is the inherited method. ③ is the method overridden in the Dog class of the interface. ④ is the method overridden in the Dog class of the Animal class. ⑤ puts the Dog instance in the Animal type variable. (The reverse is not possible) Since ⑥ is an Animal type, breath is not implemented and cannot be used. ⑦ is an Animal type, but the new one is Dog, and even if it is upcast, it will be Dog's characteristic.

Return value and overload

The method that returns the return value should be prefixed with the type to be returned in the declaration, and the return clause must be written. Overloading is the creation of methods with the same name, with different numbers or types of arguments.

 class Calc {
    int sum(int a, int b) {
        return a + b;
    }
    //Overload
    int sum(int a, int b, int c) {
        return a + b + c;
    }
 }

Abstract classes and interfaces

The abstract class has an is-a relationship with the child class. The interface has a can-do relationship with the child class.

Abstract class interface
Access modifier public, protected public
Variable definition Instance variables,Local variables,Class variables public static finalのClass variables
Inheritance 多重Inheritance不可 多重Inheritance可
Method definition Specific method,Force child to implement with abstract method Method type only,You can write the process in the default method.,Also apply static method.
constructor,Initializer Can be implemented Cannot be implemented
 abstract class Animal {
    String name;
 
    Animal(String name){
        this.name = name;
    }
    //You can write specific processing.
    void sleep(){
        System.out.println("sleeping!");
    }
    //abstract method forces child class to implement
    abstract void speak();
 }
 
 interface Animal2{
    String name = null;
 
    //You can write the process in default
    default void sleep(){
        System.out.println("sleeping!");
    }
    //Ordinary methods force child classes to implement
    void speak();
 }

enum type

 //Treated as one class in enumerated programs
 enum Output {
    OK, NG,
 }
 
 public class Enum {
 
    public static void main(String[] args) {
        Output out;
 
        out = Output.NG;
 
        switch (out) {
        case OK:
            System.out.println("OK!");
            System.out.println(out.ordinal()); // 0
            break;
        case NG:
            System.out.println("NG!");
            System.out.println(out.ordinal()); // 1
            break;
        }
    }
 }

Access modifiers and static

Access modifier

There are four access modifiers for java.

Access modifier Same class Same package Subclass all
public
protected -
Default - -
private - - -

Data can be hidden and encapsulated by combining these. Data hiding: Divide members (attributes and operations) into public and private, and avoid direct access to attributes from the outside. Encapsulation: To have an attribute and the operation to access the attribute together in the object.

 public class Parser {
 
    private String str = null;
 
    public String getStr() {
        return str;
    }
    private void setStr(String param) {
        str = param;
    }
 }

static

By adding static to variables and methods, class fields and class methods can be implemented.

class StaticClass {
 
    //static member
    static String staticStr;
    static String getStaticStr(){
        return staticStr;
    }
    //Instance member
    String instanceStr;
    String getInstatnceStr() {
        return instanceStr;
    }
 
    //static initializer
    static {
        StaticClass.staticStr = "staticStr";
    }
    //Instance initializer
    {
        instanceStr = "instanceStr";
    }
 }
 
 class Main {
 
    public static void main(String[] args) {
 
        //static reference
        StaticClass.staticStr = StaticClass.staticStr + "Main";
        System.out.println(StaticClass.getStaticStr());  //staticStrMain
 
        //Instance reference
        StaticClass stsCls = new StaticClass();
        stsCls.instanceStr = stsCls.instanceStr + "Main";
        System.out.println(stsCls.instanceStr);  //instanceStrMain
    }
 }

The initializer can initialize variables. By the way, the initializer is executed before instantiation, and the constructor is executed after instantiation. Static elements (static members) are retained until the application is stopped, whereas they are retained. Instance members are retained only until the instance is killed.

Generic type and wildcard

Generic type

If you don't know what type will fit until you use it, you can use the generic type. First of all, the generic type of the class.

//By generalizing the type, it can be used with various types.
//T is custom(Type).. Anything is fine
class GenericSample {
    private T value;
    public void setValue(T val) {
        value = val;
    }
    public T getValue() {
        return value;
    }
}
public class Generics {
    public static void main(String[] args) {
        GenericSample i = new GenericSample<>();
        i.setValue(10);
        System.out.println(i.getValue());  //10
        GenericSample s = new GenericSample<>();
        s.setValue("Hello");
        System.out.println(s.getValue());  //Hello
    }
}

Next is the generic type of constructors and methods.

class MethodConstractorSample {
 
    //Put a formal argument before the constructor
     MethodConstractorSample(T arg) {
        System.out.println(arg);
    }
    //Put a formal argument before the method return value
    //(T can also be used as the return value)
    public static  boolean genericSample(T arg) {
        T t = arg;
        if (t != null) {
            return true;
        } else {
            return false;
        }
    }
}

Wildcard

Wildcard: When using a class or method, use it when you don't know the type until you execute it.

class WildCard {
    //An example where it is fixed to return a List, but you do not know what type of list it is until you execute it.
    public List createList(boolean s) {
        if (s) {
            return new ArrayList();
        } else {
            return new ArrayList();
        }
    }
}

Reference

collection

A collection is a class that determines a type and has consecutive values of that type. There are List, Map, and Set, each of which has its own characteristics. (Classes are under these three, List, Map, Set are interfaces)

List

There is a turn. There are ArrayList and LinkedList. ArrayList: Search is fast. LinkedList: Addition / deletion is quick.

List<Integer> list = new ArrayList<>();
 
list.add(10);
list.add(20);
System.out.println(list.get(1));  //20

Set Do not allow duplicate values. There are HashSet, TreeSet, and LinkedHashSet. HashSet: Out of order. TreeSet: Sorted by value. LinkedHashSet: Sorted in the order they were added.

Set<Integer> hashSet = new HashSet<Integer>();
 
hashSet.add(10);
hashSet.add(20);
hashSet.add(10);
System.out.println(hashSet.size());  //2

Map Has a key and a value.

There are HashMap, TreeMap, and LinedHashMap. HashMap: No order. TreeMap: Sort by key. LinedHashMap: Sort in order of addition.

Map <String, Integer> hashMap = new HashMap<>();
 
hashMap.put("sato", 50);
hashMap.put("ito", 60);
 
System.out.println(hashMap.get("sato"));  //50

for each for (type of contents Variable name of contents: array and collection) All contents of arrays and collections can be processed.

Using the collection above, it looks like this.

for (Integer data : list) {
    System.out.println(data);  //10, 20
}
 
//Map.Entry<K,V>Is the type (interface) of the contents of the map
//hashMap.entrySet()The return type of is Set<Map.Entry<K,​V>>
for (Map.Entry<String, Integer> score : hashMap.entrySet()) {
    System.out.println(score.getKey() + " : " + score.getValue());
    //ito : 60
    //sato : 50
}

Exception handling

Exception handling uses Exception. Raise an exception, catch it, and try to raise your own exception.

public class ExceptionSample {
 
    public static void main(String[] args) {
 
        try {
 
            //NumberFormatException occurs here
            String s = "No.1";
            System.out.println(Integer.parseInt(s));
 
        } catch (ArithmeticException e) {
 
            System.err.println("ArithmeticException: " + e.getMessage());
 
        //NumberFormatException is not a subclass of ArithmeticException
        //Catch in Exception
        } catch (Exception e) {
 
            //GetMessage to get Message
            System.err.println("Exception: " + e.getMessage());
 
        } finally {
            try {
                //Throw MyException
                getErr();
 
            //Catch MyException
            }catch(MyException e){
                System.err.println(e.getMessage());
            }
        }
    }
 
    //If you do not catch it yourself, return Exception to the caller.
    static void getErr() throws MyException {
        throw new MyException("MyException!");
    }
}
 
//The definition of the original Exception is extends
//You can set the message in the constructor.
class MyException extends Exception {
    public MyException(String s) {
        super(s);
    }
}

·output

 Exception: For input string: "No.1"
 MyException!

Lambda expression

A lambda expression is an expression that creates an instance that implements an interface. If you omit the anonymous class that omits the local class, it becomes a lambda expression.

Local class

public static void main(String[] args) {
 
    //Local class:Declare a class in a method
    class Local implements Runnable {
        public void run() {
            System.out.println("Hello LocalClass!");
        }
    }
    Runnable runner = new Local();
    runner.run(); // Hello LocalClass!
}

Anonymous class

public static void main(String[] args) {
 
    //Anonymous class:Omit local class declaration that implements the interface
    // new Runnable(){}Create an anonymous class instance that looks like a Runnable instance
    Runnable runner2 = new Runnable() {
        public void run() {
            System.out.println("Hello NoNameClass!");
        }
    };
    runner2.run(); // Hello NoNameClass!
}

Lambda expression

public static void main(String[] args) {
 
    //Lambda expression:Omit anonymous class
    // ()Is run()Arguments of
    // ->{}Is the implementation of the run method
    //Guess the interface type by the type of the assignment destination
    Runnable runner3 = () -> {
        System.out.println("Hello Lambda!");
    };
    runner3.run(); // Hello Lambda!
 
    //Pass an anonymous class instance to the method method and later find it Runnable from the arguments
    method(() -> {
        System.out.println("Hello Lambda!");
    });
}

public static void method(Runnable r) {
    r.run();
}

In other words, the lambda expression is roughly correct if you think that the method is generated by ()-> {}. Specifically, the content of {} is the implementation content and the content of () has the method of the argument, Creating an anonymous class instance of some kind of interface type.

Since you don't know which method in (), you can use the abstract method for only one interface.

Functional interface

An interface with one abstract method. Perfect for lambda expressions.

// Function<Argument type T,Return value R>Interface method is R apply(T)
Function<Integer, String> asterisker = (i) -> {
    System.out.println("Function");
    return "*" + i;
};
String result = asterisker.apply(10);
System.out.println(result); // *10
//BiFunction has two arguments
 
// Consumer<Argument type>Method is void accept(T)
Consumer<String> buyer = (goods) -> {
    System.out.println(goods + "I bought");
};
buyer.accept("rice ball"); // rice ballを購入しました。
//BiConsumer has 2 arguments
 
//Predicate<Argument type>Method is boolean test(T)
Predicate<String> checker = (s) -> {
    return s.equals("Java");
};
boolean result2 = checker.test("Java");
System.out.println(result2); // true

STREAMAPI

A convenient functional interface group that can be used in the Collection class.

List<Integer> list = new ArrayList<>();
list.add(-1);
list.add(0);
list.add(1);
list.add(3);
list.add(2); 
 
    //Collection.stream()Return value:Stream
list.stream()                                           //Stream instance generation based on collection
    //filter(Predicate<T>)Return value:Stream
    .filter((i) -> { return i > 0; })                   //Returns a Stream excluding those that do not meet the conditions.
    //sorted(Comparator<T>)Return value:Stream
    .sorted((i1, i2) -> { return i1 - i2; })            //Argument 1-Argument 2 in ascending order Argument 2- Argument 1で降順
    //map(Function<T, R>)Return value:Stream
    .map((i) -> { return "*" + i + "*"; })              //Perform foreach in the middle end processing.
    //forEach(Consumer<T>)Return value:void
    .forEach((i) -> { System.out.print(i + " "); });    //Apply Consumer to all elements
    //*1* *2* *3*

Omission of lambda expression

If certain conditions are met, various omissions can be made.

//Uninflected word
Predicate javaChecker = (String s) -> { return s.equals("Java"); };
//Type omitted when there is one argument
Predicate javaChecker = (       s) -> { return s.equals("Java"); };
//When the type is omitted()Also omitted
Predicate javaChecker =         s  -> { return s.equals("Java"); };
//When there is only one line and no return{}abridgement
Consumer buyer =         goods     ->   System.out.println(goods + "I bought");
//return too{}Simultaneously omitted with
Predicate javaChecker =         s  ->          s.equals("Java");

Reference

Thread thread can run processing at the same time (asynchronous processing) Inherit the Thread class and write the process in the run method, or It can be implemented by passing a Runnable interface type instance to the Thread constructor.

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 300; i++) {
            System.out.print('^');
        }
    }
}
 
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 300; i++) {
            System.out.print('*');
        }
    }
}
 
public class Threads {
 
    public static void main(String[] args) {
 
        //Patterns that use raw Thread
        MyThread mt = new MyThread();
        mt.start();
 
        //Pattern that overrides the run method of the Runnable class
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
 
        //Pattern to pass Runnable type instance directly to constructor in lambda notation
        new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.print('=');
            }
        }).start();
    }    //^^^^^^^^^*******^^^^^========...
}

Suspension / delay

sleep: Downstream from the expression waits at a fixed time. join: The downstream thread waits for the specified thread to complete.

    public static void main(String[] args) throws Exception {
 
        new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.print('^');
            }
        }).start();
 
        //Stop for 3 seconds
        Thread.sleep(3000);
 
        Thread t = new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.print('=');
            }
        });
        t.start();
 
        // *Wait until you finish writing.
        t.join();
 
        new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.print('*');
            }
        }).start();
    }  //^^^...***...===...

Reference

Date It seems to be good to use LocalDateTime. Date class and Calendar class are old.

public static void main(String[] args) {
 
    //LocalDateTime basics
    LocalDateTime d = LocalDateTime.now();
    System.out.println(d.getYear());
    System.out.println(d.getMonth());
    System.out.println(d.getDayOfMonth());
    System.out.println(d.getHour());
    System.out.println(d.getMinute());
    System.out.println(d.getSecond());
    System.out.println(d.getNano());
 
    //Specify a specific date and time
    d = LocalDateTime.of(2015, 12, 15, 23, 30, 59);
    System.out.println(d.plusDays(20));       //2016-01-04T23:30:59
    System.out.println(d.minusDays(20));      //2015-11-25T23:30:59
    System.out.println(d.withDayOfMonth(20)); //2015-12-20T23:30:59
 
    //Truncation of time
    LocalDateTime.of(2015, 12, 15, 23, 30, 59).truncatedTo(ChronoUnit.HOURS); // 2015-12-15T23:00
 
    //12:00 on the 1st of next month
    d =
        LocalDateTime.now()
        .plusMonths(1)
        .withDayOfMonth(1)
        .withHour(12)
        .truncatedTo(ChronoUnit.HOURS);
 
    //Convert to string
    DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    d = LocalDateTime.parse("2015/12/15 23:30:59", f);
    System.out.println(d.format(f));    //2015/12/15 23:30:59
    f = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    System.out.println(d.format(f));    //2015/12/15
}

Reference Reference

Servlet

I made a working app. https://github.com/kikusan-16/servlet-learning

If you import it into Eclipse, README describes how to demo it easily.

Recommended Posts

java programming basics
Java programming basics practice-array
Java basics
Java basics
Java basics
Java programming basics practice-for statement
Java programming basics practice-switch statement
Java JAR basics
Object-oriented (Java) basics
java Generic Programming
Java concurrency basics
Constraint programming in Java
Java programming (class method)
Java Network Basics (Communication)
Java programming (class structure)
All about Java programming
java competitive programming memo
Muscle Java Basics Day 1
Java Programming Thread Runnable
Amazing Java programming (let's stop)
Basics of character operation (java)
Java programming (variables and data)
Java Development Basics-Practice ③ Advanced Programming-
Java
Summary of Java language basics
Getting Started with Java Basics
Java Development Basics ~ Exercise (Array) ~
Java
[Java11] Stream Usage Summary -Basics-
[Java basics] What is Class?
[Java] Basic terms in programming
Competitive programming private cheat sheet (Java)
Java Functional Programming Exercise Book --zipWith-
Introduction to Functional Programming (Java, Javascript)
Summary of object-oriented programming using Java
Java Performance Chapter 5 Garbage Collection Basics
Collection of programming selection tasks to make and remember (Java basics)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Rails basics
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Ruby basics
Java array
[Java] ArrayDeque
Ruby basics
java (override)
java (method)
Java Day 2018
Java string
java (array)
Object-oriented programming
Java static