Java
 Computer >> コンピューター >  >> プログラミング >> Java

文字列が空かヌルかをチェックするJavaプログラム


この記事では、文字列が空かnullかを確認する方法を理解します。文字列は、1つ以上の文字を含み、二重引用符(“”)で囲まれたデータ型です。

以下は同じのデモンストレーションです-

入力がであると仮定します −

Input string: null

必要な出力は

The string is a null string

アルゴリズム

Step 1 - START
Step 2 - Declare a string namely input_string.
Step 3 - Define the values.
Step 4 - Using an if-loop, compute input_string == null. If true, the string is null, else the string is not null.
Step 5 - Display the result
Step 6 - Stop

例1

ここでは、「main」関数の下ですべての操作をバインドします。

public class Demo {
   public static void main(String[] args) {
      String input_string = null;
      System.out.println("The string is defined as: " +input_string);
      if (input_string == null) {
         System.out.println("\nThe string is a null string");
      }
      else if(input_string.isEmpty()){
         System.out.println("\nThe string is an empty string");
      } else {
         System.out.println("\nThe string is neither empty nor null string");
      }
   }
}

出力

The string is defined as: null

The string is a null string

例2

ここでは、操作をオブジェクト指向プログラミングを示す関数にカプセル化します。

public class Demo {
   static void isNullEmpty(String input_string) {
      if (input_string == null) {
         System.out.println("\nThe string is a null string");
      }
      else if(input_string.isEmpty()){
         System.out.println("\nThe string is an empty string");
      } else {
         System.out.println("\nThe string is neither empty nor null string");
      }
   }
   public static void main(String[] args) {
      String input_string = null;
      System.out.println("The string is defined as: " +input_string);
      isNullEmpty(input_string);
   }
}

出力

The string is defined as: null

The string is a null string

  1. 回文をチェックするJavaプログラム

    回文数は、逆にしたときに同じままの数です。たとえば、121、313、525などです。 例 回文をチェックする例を見てみましょう- public class Palindrome {    public static void main(String[] args) {       int a = 525, revVal = 0, remainder, val;       val = a;       System.out.println("Number to be che

  2. 文字列が空かどうかをチェックするPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 文字列を入力したら、文字列が空かどうかを確認する必要があります。 Python文字列は本質的に不変であるため、操作を実行するときは、文字列を処理するときに注意が必要です。 ここでは、上記の問題ステートメントを解決するための2つのアプローチについて説明します- len()メソッドを使用します。 等式演算子を使用します。 アプローチ1:len()メソッドを使用する 例 test_str1 = "" test_str2 = "@@@" if(l