Javaを使ってみよう

[vagrant@localhost java_lessons]$ sudo yum -y install java-1.8.0-openjdk-devel
$ java -version
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Javaが動作する原理を理解しよう

はじめてのJavaプログラム

public class MyApp {

  public static void main(String[] args) {
      System.out.println("Hello World");
    }
 
}
$ javac MyApp.java
$ ls
MyApp.class  MyApp.java
$ java MyApp
Hello World

変数を使ってみよう

public class MyApp {

  public static void main(String[] args) {
    String msg;
    msg = "Hello World Again!";
      System.out.println(msg);
    }

}
$ java MyApp
Hello World Again!

さまざまなデータ型を使おう

データの演算をしてみよう

public class MyApp {

  public static void main(String[] args) {
    int i;
    i = 10 / 3;
    System.out.println(i); // 3
    i = 10 % 3;
    System.out.println(i); // 1
    int x = 5;
    x++;
    System.out.println(x); // 6
    x--;
    System.out.println(x); // 5
    }

}
$ java MyApp
3
1
6
5
public class MyApp {

  public static void main(String[] args) {
    int x = 5;
    // x = x + 12;
    x += 12;
    System.out.println(x);
    }

}
$ java MyApp
17
public class MyApp {

  public static void main(String[] args) {
    String s;
    s = "hello " + "world";
    System.out.println(s);
    }

}
$ java MyApp
hello world

データ型とメモリの関係を理解しよう

基本データ型と参照型を理解しよう

public class MyApp {

  public static void main(String[] args) {
    int x = 10;
    int y = x;
    y = 5;
    System.out.println(x);
    System.out.println(y);
  }

}
$ java MyApp
10
5
public class MyApp {

  public static void main(String[] args) {
    int[] a = {3, 5, 7};
    int[] b = a;
    b[1] = 8;
    System.out.println(a[1]);
    System.out.println(b[1]);
  }

}
$ java MyApp
8
8
public class MyApp {

  public static void main(String[] args) {
    String s = "hello";
    String t = s;
    t = "world";
    System.out.println(s);
    System.out.println(t);
  }

}
$ java MyApp
hello
world

コンストラクタを使ってみよう

class User {
  String name;

  // constructor
  User(String name) {
    this.name = name;
  }

  void sayHi() {
    System.out.println("hi! " + this.name);
  }
}

public class MyApp {

  public static void main(String[] args) {
    User tom;
    tom = new User("Tom");
    System.out.println(tom.name);
    tom.sayHi();
  }

}
$ java MyApp
Tom
hi! Tom
class User {
  String name;

  // constructor
  User(String name) {
    this.name = name;
  }

  User() {
    this.name = "Me!";
  }

  void sayHi() {
    System.out.println("hi! " + this.name);
  }
}

public class MyApp {

  public static void main(String[] args) {
    User tom;
    tom = new User();
    System.out.println(tom.name);
    tom.sayHi();
  }

}
$ java MyApp
Me!
hi! Me!
class User {
  String name;

  // constructor
  User(String name) {
    this.name = name;
  }

  User() {
    this("Me!");
  }

  void sayHi() {
    System.out.println("hi! " + this.name);
  }
}

public class MyApp {

  public static void main(String[] args) {
    User tom;
    tom = new User();
    System.out.println(tom.name);
    tom.sayHi();
  }

}
$ java MyApp
Me!
hi! Me!

パッケージとアクセス権を理解しよう

パッケージを使ってみよう

/home/vagrant/java_lessons
|--com
|  |--yujidev
|  |  |--myapp
|  |  |  |--MyApp.java
|  |  |  |--model
|  |  |  |  |--AdminUser.java
|  |  |  |  |--User.java
package com.yujidev.myapp;
import com.yujidev.myapp.model.User;
import com.yujidev.myapp.model.AdminUser;
// import com.yujidev.myapp.model.*;

public class MyApp {

  public static void main(String[] args) {
    User tom = new User("tom");
    // System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob");
    // System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }

}
package com.yujidev.myapp.model;

public class AdminUser extends User {

  public AdminUser(String name) {
    super(name);
  }

  public void sayHello() {
    System.out.println("hello! " + this.name);
  }

  @Override
  public void sayHi() {
    System.out.println("[admin] hi! " + this.name);
  }
}
package com.yujidev.myapp.model;

public class User {
  protected String name;

  public User(String name) {
    this.name = name;
  }

  public void sayHi() {
    System.out.println("hi! " + this.name);
  }
}

パッケージをコンパイルしてみよう

$ javac com/yujidev/myapp/MyApp.java
$ java com.yujidev.myapp.MyApp
hi! tom
[admin] hi! bob
hello! bob

イニシャライザを使ってみよう

// static

class User {
  private String name;
  private static int count; // クラス変数

  static {
    User.count = 0;
    System.out.println("Static initializer");
  }

  {
    System.out.println("Instance initializer");
  }

  public User(String name) {
    this.name = name;
    User.count++;
    System.out.println("Constructor");
  }

  public static void getInfo() { // クラスメソッド
    System.out.println("# of instances: " + User.count);
  }

}

public class MyApp {

  public static void main(String[] args) {
    User.getInfo(); // 0
    User tom = new User("tom");
    User.getInfo(); // 1
    User bob = new User("bob");
    User.getInfo(); // 2
  }

}
$ java MyApp
Static initializer
# of instances: 0
Instance initializer
Constructor
# of instances: 1
Instance initializer
Constructor
# of instances: 2

列挙型を作ってみよう

enum Result {
  SUCCESS, // 0
  ERROR, // 1
}

public class MyApp {

  public static void main(String[] args) {
    Result res;

    res = Result.ERROR;

    switch (res) {
      case SUCCESS:
        System.out.println("OK!");
        System.out.println(res.ordinal()); // 0
        break;
      case ERROR:
        System.out.println("NG!");
        System.out.println(res.ordinal()); // 1
        break;
    }

  }

}
$ java MyApp
NG!
1

例外処理を扱ってみよう

// 例外

class MyException extends Exception {
  public MyException(String s) {
    super(s);
  }
}

public class MyApp {

  public static void div(int a, int b) {
    try {
      if (b < 0) {
        throw new MyException("not minus!");
      }
      System.out.println(a / b);
    } catch (ArithmeticException e) {
      System.err.println(e.getMessage());
    } catch (MyException e) {
      System.err.println(e.getMessage());
    } finally {
      System.out.println(" -- end -- ");
    }
  }

  public static void main(String[] args) {
    div(3, 0);
    div(5, -2);
  }

}
$ java MyApp
/ by zero
 -- end --
not minus!
-- end --

ラッパークラスを使ってみよう

/*
Wrapper Class
int -> Integer
double -> Double
*/

public class MyApp {

  public static void main(String[] args) {
    // Integer i = new Integer(32);
    // int n = i.intValue();

    Integer i = 32; // auto boxing
    i = null;
    int n = i; // auto unboxing

  }

}
$ java MyApp
Exception in thread "main" java.lang.NullPointerException
	at MyApp.main(MyApp.java:15)

ジェネリクスを使ってみよう

// generics

class MyData<T> {
  public void getThree(T x) {
    System.out.println(x);
    System.out.println(x);
    System.out.println(x);
  }
}

public class MyApp {

  public static void main(String[] args) {
    MyData<Integer> i = new MyData<>();
    i.getThree(32);
    MyData<String> s = new MyData<>();
    s.getThree("hello");
  }

}
$ java MyApp
32
32
32
hello
hello
hello

スレッド処理を実装してみよう

// Thread

class MyRunnable implements Runnable {
  @Override
  public void run() {
    for (int i = 0; i < 500; i++) {
      System.out.print('*');
    }
  }
}

public class MyApp {

  public static void main(String[] args) {
    MyRunnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();

    for (int i = 0; i < 500; i++) {
      System.out.print('.');
    }
  }

}

$ java MyApp

.............................................................................................................................*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************.......................................................................................................................................................................................................................................................................................................................................................................................*******************************************************************************************************************

無名クラス、ラムダ式を使おう

// Thread

public class MyApp {

  public static void main(String[] args) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i < 500; i++) {
          System.out.print('*');
        }
      }
    }).start();

    for (int i = 0; i < 500; i++) {
      System.out.print('.');
    }
  }

}

$ java MyApp

............................................................................................................................................................................................................................***********************************************************************************************************************************************************************************************************************************************************************************........................................................................................................................................................................................................................................................................................*********************************************************************************************************************************************************************************************************************************
// Thread

public class MyApp {

  public static void main(String[] args) {
    // new Thread(new Runnable() {
    //   @Override
    //   public void run() {
    //     for (int i = 0; i < 500; i++) {
    //       System.out.print('*');
    //     }
    //   }
    // }).start();

    // ラムダ式
    // (引数) -> {処理}
    new Thread(() -> {
      for (int i = 0; i < 500; i++) {
        System.out.print('*');
      }
    }).start();

    for (int i = 0; i < 500; i++) {
      System.out.print('.');
    }
  }

}

$ java MyApp

................................................................................................................................................................................................................................................................................................................................********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************....................................................................................................................................................................................

Stream APIを使ってみよう

$ java MyApp
(12)
(30)
(9)

LocalDateTimeクラスを使ってみよう

import java.time.*;
import java.time.format.DateTimeFormatter;

public class MyApp {

  public static void main(String[] args) {
    LocalDateTime d = LocalDateTime.now();
    // LocalDateTime d = LocalDateTime.of(2016, 1, 1, 10, 10, 10);
    // LocalDateTime d = LocalDateTime.parse("2016-01-01T10:10:10");

    System.out.println(d.getYear());
    System.out.println(d.getMonth());
    System.out.println(d.getMonth().getValue());

    System.out.println(d.plusMonths(2).minusDays(3));

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy!MM!dd!");
    System.out.println(d.format(dtf));

  }

}
$ java MyApp
2017
MAY
5
2017-07-01T09:41:32.517
2017!05!04!

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS