Java or/and Logic

Rashmi Patidar Oct 12, 2023
Java or/and Logic

In Java language, and (&&)/ or(||) are categorized as logical operators. The operators are used to evaluate two or more conditions altogether and return output in Boolean format. The and(&&) operator evaluates two conditions based on the first condition. If and only if the first condition is true, then the second condition is checked. So the & operator only returns true when the first condition returns a true value, else it always returns a false value. On the other hand, the or(||) operator returns false if both the conditions return false, else it always evaluates to true.

Below is the sample code block to illustrate the working of logical operators.

import java.util.Scanner;

public class LogicalOperators {
  public static void main(String[] args) {
    System.out.println("Enter a string : ");
    Scanner s = new Scanner(System.in);
    String input = s.nextLine();
    if (input == null || input.isEmpty()) {
      System.out.println("Input String is null or empty");
    }
    if (input != null && !input.isEmpty()) {
      System.out.println("Input String is: " + input);
    }
  }
}

In the above code block, first, a Scanner class is instantiated. The constructor takes an instance of InputStream and internally converts bytes to characters. The usage of the scanner object is to take input from the user through the console. The method nextLine() takes the string until a line break comes. The user input gets stored in a variable that is the input variable.

Now the input variable is checked if it is null or the input variable is empty. The condition results in true if any of the conditions are true.

The condition is applied to check if the variable is not null and not empty. If it results true, then the input string is printed in the console output.

See the output of the above program.

Enter a string : 

Input String is null or empty

First, an enter is hit instead of a well-defined string. In the second case, a well-defined string gets entered, which gets printed in the new line.

Enter a string : 
Hi
Input String is: Hi
Rashmi Patidar avatar Rashmi Patidar avatar

Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.

LinkedIn

Related Article - Java Logic