Beginners Programs :

Java Program To Check Any Spaces In a String | Java Programs

Check String for Spaces in Java Program – In this specific article, we will be dealing with the code here to check whether a given string has a white space using Java language with suitable examples and sample output.

  • The problem here is to check whether a user-defined string has a whitespace present.
  • Our constraint here is the inability to return a positive result if the only white space present is the last character in a string.
  • The input here is a user-defined string with either space present or absent.
  • The output is a boolean value of true or false printed out which helps determine the presence of whitespaces in java string.

Output – 1:

Solution:

  1. In the main method, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java.
  2. Scanner class is part of the java.util package and hence the import statement, in the beginning, is stated to import the functionality of the specified class while the Java program is used to find space in a string.
  3. The next line prints a statement to the console instructing the user to enter a string.
  4. The .nextLine() method is called by the Scanner object sc. This method reads a line of user input of a string value and stores it to the string variable s.
  5. Within the print statement in the last line, the hasSpace method is called and string is passed in as the argument.
  1. In this method, the loop iterates over all the characters of the string (since i<str.length()) unless it finds a white-space midway and ends the method implementation.
  2. The parameter string str represents the string input by the user and is passed in as the argument from the main method.
  3. As the loop iterates, the conditional statement checks certain conditions using OR operator ( || ) and AND operator ( && ).
  4. If the first character of the string i.e. the character at index 0 is a white-space, the condition is satisfied OR if the character at any index is a white-space AND the character following it at index i+1 is not a space, the condition is satisfied.
  5. The boolean value true is returned and printed out if the condition is satisfied and value false is returned and printed out otherwise.
  • Here, the input hello world has a white-space at index 5, and hence the conditional statement in the method hasSpace is satisfied and returns and prints the boolean value true.

Output – 2:

  • Here, the input ” “ has no whitespaces, and hence the conditional statement in the method hasSpace is not satisfied and returns and prints the boolean value false.