0

I thought the default value of boolean is false? Why does it print the true statement instead? My output is goodbye


public class Test {

public static void main (String [] args) {

if(false)
    System.out.print("hello");

else System.out.print("goodbye");
}
}
2
  • 4
    This has nothing to do with the default value of a boolean variable. The else branch executes if the expression inside the () evaluates to false, which it does in your code. What did you expect it to output? And can you explain why did you expect it to output that? Commented Apr 21, 2019 at 10:05
  • What default vale? What true statement? What happens? What did you expect? Commented Apr 21, 2019 at 11:55

2 Answers 2

1

Your code doesn't use the default value of boolean value. You always print System.out.print("goodbye");, because this section is true. To achieve this, use the following code


public class Test {
    static boolean defaultValue;
public static void main(String[] args) {
System.out.println("Default value is "+defaultValue); if(defaultValue) System.out.println("hello"); else System.out.println("goodbye"); } }

Sign up to request clarification or add additional context in comments.

Comments

0

What sweeper told you in a comment is correct. You seem to be under a wrong impression regarding the syntax I think. Take the following piece of code you gave as an example.

if (false) {
    System.out.print("hello");
}

The code inside the if block will never run because the expression false will always evaluate to the boolean value false. You are asking Java to do the following: 'hey run this code if what I put inside the brackets evaluates to true but what you put inside the brackets will always evaluate to false. Thats why java will always run the code inside the else block in your example.

I hope this clears thing up a bit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.