exception
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);
}
}
wrapper class
public class MyApp {
public static void main(String[] args){
// Integer i = new Integer(32);
// int n = i.intValue();
Integer i = 32; // auto boxing 参照型
int n = i; // auto unboxing
System.out.println();
}
}
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("What's up");
}
}
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('.');
}
}
}
無名クラス
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('.');
}
}
}
ラムダ式
new Thread(()-> {
for (int i = 0; i < 500; i++){
System.out.print('*');
}
}).start();
for (int i = 0; i < 500; i++){
System.out.print('.');
}
String
public class MyApp {
public static void main(String[] args){
String s = "abcdef";
System.out.println(s.length());
System.out.println(s.substring(2, 5));
System.out.println(s.replaceAll("ab", "AB"));
String s1 = "ab";
String s2 = "ab";
if(s1.equals(s2)){
System.out.println("same!");
}
if(s1 == s2){
System.out.println("same!same!");
}
String ss1 = new String("abc");
String ss2 = new String("abc");
if(ss1 == ss2){
System.out.println("same!same!same!");
}
}
}
printf
public class MyApp {
public static void main(String[] args){
int score = 50;
double height = 165.8;
String name ="hpscript";
System.out.printf("name: %-10s, score: %10d, height: %5.2f\n", name, score, height);
String s = String.format("name: %10s, score: %-10d, height: %5.2f\n", name, score, height);
System.out.println(s);
}
}
random
import java.util.Random;
public class MyApp {
public static void main(String[] args){
double d = 53.234;
System.out.println(Math.ceil(d));
System.out.println(Math.floor(d));
System.out.println(Math.round(d));
System.out.println(Math.PI);
Random r = new Random();
System.out.println(r.nextDouble()); // 0 - 1
System.out.println(r.nextInt(100));
System.out.println(r.nextBoolean());
}
}