LoginSignup
1
0

基本構文

// クラス宣言
public class MyClass {
    // メンバ変数
    int myVar;

    // コンストラクタ
    public MyClass(int var) {
        this.myVar = var;
    }

    // メソッド
    public void myMethod() {
        System.out.println("Hello, World!");
    }

    // メインメソッド
    public static void main(String[] args) {
        MyClass obj = new MyClass(10);
        obj.myMethod();
        System.out.println("myVar: " + obj.myVar);
    }
}

変数とデータ型

int myInt = 10;          // 整数型
double myDouble = 5.99;  // 浮動小数点型
char myChar = 'A';       // 文字型
boolean myBool = true;   // 論理型
String myString = "Hello"; // 文字列型

演算子

// 算術演算子
int sum = 10 + 5;       // 加算
int diff = 10 - 5;      // 減算
int prod = 10 * 5;      // 乗算
int quot = 10 / 5;      // 除算
int mod = 10 % 5;       // 剰余

// 比較演算子
boolean isEqual = (10 == 5);        // 等しいか
boolean isNotEqual = (10 != 5);     // 等しくないか
boolean isGreater = (10 > 5);       // より大きいか
boolean isLess = (10 < 5);          // より小さいか
boolean isGreaterOrEqual = (10 >= 5); // より大きいかまたは等しいか
boolean isLessOrEqual = (10 <= 5);  // より小さいかまたは等しいか

// 論理演算子
boolean and = (true && false);  // AND
boolean or = (true || false);   // OR
boolean not = !true;            // NOT

制御構文

// if文
if (condition) {
    // 条件が真の場合の処理
} else if (anotherCondition) {
    // 別の条件が真の場合の処理
} else {
    // どちらの条件も偽の場合の処理
}

// switch文
switch (variable) {
    case 1:
        // 変数が1の場合の処理
        break;
    case 2:
        // 変数が2の場合の処理
        break;
    default:
        // それ以外の場合の処理
        break;
}

// while文
while (condition) {
    // 条件が真の間繰り返す処理
}

// do-while文
do {
    // 少なくとも1回は実行される処理
} while (condition);

// for文
for (int i = 0; i < 10; i++) {
    // 10回繰り返される処理
}

// 拡張for文 (for-each)
int[] array = {1, 2, 3, 4, 5};
for (int num : array) {
    // 配列の各要素に対して繰り返される処理
}

配列

int[] myArray = new int[5]; // サイズが5の整数型配列
myArray[0] = 10; // 配列の1番目の要素に値を設定

int[] anotherArray = {1, 2, 3, 4, 5}; // 配列リテラル

// 配列の長さを取得
int length = anotherArray.length;

// 配列のすべての要素を出力
for (int i = 0; i < anotherArray.length; i++) {
    System.out.println(anotherArray[i]);
}

クラスとオブジェクト

// クラス定義
public class Car {
    // フィールド(メンバ変数)
    String color;
    int year;

    // コンストラクタ
    public Car(String c, int y) {
        this.color = c;
        this.year = y;
    }

    // メソッド
    public void displayInfo() {
        System.out.println("Color: " + color + ", Year: " + year);
    }
}

// オブジェクトの生成と使用
public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Red", 2020);
        myCar.displayInfo();
    }
}

継承

// 基本クラス(親クラス)
public class Animal {
    public void eat() {
        System.out.println("This animal eats food.");
    }
}

// 派生クラス(子クラス)
public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog barks.");
    }
}

// 使用例
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();  // 親クラスのメソッド
        myDog.bark(); // 子クラスのメソッド
    }
}

インターフェース

// インターフェース定義
public interface Animal {
    void makeSound();
}

// インターフェースを実装するクラス
public class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow");
    }
}

// 使用例
public class Main {
    public static void main(String[] args) {
        Animal myCat = new Cat();
        myCat.makeSound();
    }
}

例外処理

try {
    // 例外が発生する可能性のあるコード
    int division = 10 / 0;
} catch (ArithmeticException e) {
    // 例外が発生した場合の処理
    System.out.println("Division by zero is not allowed.");
} finally {
    // 例外が発生するかどうかに関わらず実行される処理
    System.out.println("Finally block executed.");
}

コレクション

import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map;

// リスト
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list.get(0)); // Apple
for (String fruit : list) {
    System.out.println(fruit);
}

// セット
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
for (String fruit : set) {
    System.out.println(fruit);
}

// マップ
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println(map.get(1)); // One
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

静的メソッドと静的変数

public class MyClass {
    // 静的変数
    public static int staticVar = 0;

    // 静的メソッド
    public static void staticMethod() {
        System.out.println("Static method called.");
    }

    // メインメソッド
    public static void main(String[] args) {
        MyClass.staticVar = 5;
        System.out.println("Static variable: " + MyClass.staticVar);
        MyClass.staticMethod();
    }
}

パッケージ

// パッケージの宣言
package com.example.myapp;

// クラス定義
public class MyClass {
    public void myMethod() {
        System.out.println("Hello, World!");
    }
}

// 別のパッケージからのインポート
import com.example.myapp.MyClass;

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.myMethod();
    }
}

入出力

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // 標準入力
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");

        // ファイル出力
        try (PrintWriter writer = new PrintWriter(new File("output.txt"))) {
            writer.println("Hello, World!");
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
        }
    }
}

ジェネリクス

public class Box<T> {
    private T content;

    public void setContent(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }

    public static void main(String[] args) {
        Box<String> stringBox = new Box<>();
        stringBox.setContent("Hello");
        System.out.println(stringBox.getContent());

        Box<Integer> intBox = new Box<>();
        intBox.setContent(123);
        System.out.println(intBox.getContent());
    }
}

ラムダ式

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
        list.forEach(fruit -> System.out.println(fruit));
    }
}

ストリームAPI

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Cherry", "Date", "Fig");

        // フィルター
        List<String> filteredList = list.stream()
                                        .filter(fruit -> fruit.startsWith("B"))
                                        .collect(Collectors.toList());

        System.out.println(filteredList);

        // マップ
        List<Integer> lengths = list.stream()
                                    .map(String::length)
                                    .collect(Collectors.toList());

        System.out.println(lengths);
    }
}

アノテーション

// カスタムアノテーション定義
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value();
}

// アノテーションの使用
public class MyClass {
    @MyAnnotation("Test")
    public void myMethod() {
        System.out.println("Annotated method.");
    }

    public static void main(String[] args) throws Exception {
        MyClass obj = new MyClass();
        obj.myMethod();

        MyAnnotation annotation = obj.getClass()
                                     .getMethod("myMethod")
                                     .getAnnotation(MyAnnotation.class);

        System.out.println("Annotation value: " + annotation.value());
    }
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0