Reputation: 21
I want my if statement to print out student or non student based on a boolean variable isStudent but I am not quite sure how it works. When I enter boolean isStudent it automatically initializes the variable false? And when I try to use isStudent == true nothing prints out but if I use isStudent == false it prints out student and non student. Can someone explain why it does that and if I did this right?
public class Test {
public static void main(String[] args) {
boolean isStudent = false;
if(isStudent == false){
System.out.println("Student");
System.out.println("non-student");
}
}
}
Upvotes: 1
Views: 513
Reputation: 613
what you are looking for is called an else statement it would look like this
public class Test {
public static void main(String[] args) {
boolean isStudent = false;
if(isStudent)
{
System.out.println("Student");
}
else
{
System.out.println("non-student");
}
}
}
heres another way without else since you asked but not a preferable way.you make a default string and declare it as a non student and it will only change if it is a student.
public class Test {
public static void main(String[] args) {
boolean isStudent = false;
String student = "non-student";
if(isStudent)
{
student = "Student";
}
System.out.println(student);
}
}
this might help if-else
Upvotes: 3
Reputation: 7393
When you have this code:
if(isStudent == false){
System.out.println("Student");
System.out.println("non-student");
}
Everything inside the curly braces { } is executed if the condition is true. You want an else
statement
if (isStudent){
System.out.println("Student");
} else {
System.out.println("non-student");
}
Upvotes: 5
Reputation: 648
Also instead of using:
if(isStudent == false)
you could also do:
if(!isStudent)
Upvotes: 0
Reputation: 234635
isStudent == false
is no more than a logical negation: it's equivalent to !isStudent
.
The clearest way you can write what you want to do is
if (isStudent /* == true is implicit*/){
System.out.println("Student");
} else /*all other possibilities*/{
System.out.println("non-student");
}
Upvotes: 2
Reputation: 2013
After the below statement, the value of isStudent
is false
.
boolean isStudent = false;
In the next step you are checking if isStudent
is equal to false
.. which is true and the statements inside the block ({...}
) will be executed, which prints the strings..
if(isStudent == false){
Also, default value of boolean variable is false.
Upvotes: 1