JavaのisBlank・isEmptyついてサンプルコードで解説
今回はisBlank・isEmptyについて説明します。
isBlankとは
文字列が空、または空白文字だけで構成されているかを確認して該当する場合はtrueを返すメソッドです。
サンプルコード
下記のコードで考えます。
public class Main {
public static void main(String[] args) {
String text1 = "";
String text2 = " ";
String text3 = " ";
String text4 = "abc";
System.out.println(text1.isBlank());
System.out.println(text2.isBlank());
System.out.println(text3.isBlank());
System.out.println(text4.isBlank());
}
}結果は下記になります。
true(文字列が空文字)
true(文字列が空白文字)
true(文字列が空白文字)
false(文字列がabc)isEmptyとは
文字列の長さが0かどうかを確認して該当する場合はtrueを返すメソッドです。
サンプルコード
下記のコードで考えます。
public class Main {
public static void main(String[] args) {
String text1 = "";
String text2 = " ";
String text3 = "abc";
System.out.println(text1.isEmpty());
System.out.println(text2.isEmpty());
System.out.println(text3.isEmpty());
}
}結果は下記になります。
true(文字列の長さは0)
false(文字列の長さは1)
false(文字列の長さは3)