Boolean variable - java

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");
}
}

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");
}
}

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.

Related

Java - how to handle this "might not be initialised" error?

Is there a feature that lets me check on which path the variable for which I'm getting a "might not be initialised" error is supposedly not initialised? Preferably either native to Java or built into Intellij?
EDIT: managed to reduce my code to a minimal failing example
class MyFailure{
public static void main (String[] args) throws java.lang.Exception{
String test;
boolean abort = false;
while(!abort){
if(false){
abort = true;
continue;
}
test = "stupid";
if(test.equals("stupid")) break;
}
if(!abort){
System.out.println(test);
}
}
}
Main.java:21: error: variable test might not have been initialized
Suppose the while loop reads from a server socket until the buffered value satisfies a certain condition and the if(false) is in fact a check whether the client closed the connection, how would you suggest I handle this?
For the code in your question there is a fairly straightforward solution: use the variable inside the loop where Java too can see it has a value:
public static void main (String[] args) throws java.lang.Exception{
boolean abort = false;
while (!abort){
if (false) {
abort = true;
continue;
}
String test = "stupid";
if (test.equals("stupid")) {
System.out.println(test);
break;
}
}
}
Whether this will work in your real-life code I cannot tell. Consider extracting a method for dealing with the value obtained from the socket and call it from where the System.out.println() is in the example.
Edit: For what it’s worth, the following version compiles too. You may still think that the use of the value (the println) is so deeply nested it reduces readability:
public static void main (String[] args) {
if (! isFalse()) {
String test;
do {
test = "stupid";
} while (! isFalse() && ! test.equals("stupid"));
if (! isFalse()) { // connection still open, so not aborted
System.out.println(test);
}
}
}
private static boolean isFalse() {
return false;
}
As mentioned in the comments I do sometimes — hesitatingly — resort to initializing the variable in question with a nonsensical/bogus value in the declaration so that if that value ever gets used because of a programming error, I will discover. In your example I might use null:
String test = null;
And after the loop:
assert test != null;
so I will catch if it didn’t get a proper value. It’s not a solution I’m happy with, but it happens that I cannot find anything better.

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

Can a function end its caller's function?

Let's say we have the following two methods:
public static void repeat(){
while (1){
otherFunc();
}
}
public static void otherFunc(){
if (something){
//Here
}
}
Is there a way for, in the place of //Here, to cause a break or return in the repeat function?
Initially, I thought definitely not, because of the issue of scope. Also, if it was intended to be used like that, otherFunc could return a boolean and be placed in an if-statement to end the while-loop or the method.
However, I could not find anything to prove that it cannot have that behavior.
Is this possible?
Although I wrote this in Java, it would also be helpful to know if this stays true in C-languages also.
if can you change the code, do it like this:
public static void repeat()
{
while (otherFunc()) ;
}
public static boolean otherFunc()
{
if (something){
return true;
}
//more stuff...
return false;
}
In C you can use longjmp and setjmp functions but it is little bit tricky. More reading also on wikipedia http://en.wikipedia.org/wiki/Setjmp.h

Java compiler/eclipse not reconizing dead code

So I recently came accros this. I was creating an if-else-statement with as it's condition a final boolean variable. Eclipse immediatly told me that the else part of the code was unreachable and therefore dead code. This was my code(compacted).
public static void main(String[] args){
final boolean state = true;
if(state == true){
System.out.println("A");
}else{
System.out.println("B");
}
}
Then I though what would happen if the code stayed the same but the variable wasn't final anymore? So I tried that and this was what happened, nothing no warnings or errors. The code:
public static void main(String[] args){
boolean state = true;
if(state == true){
System.out.println("A");
}else{
System.out.println("B");
}
}
Now I'm wondering, why is the first case detected and flagged and the second case not?
Thank you in advance.
Try this as an alternative.
public class Test061 {
public static void main(String[] args){
int a = 0;
if(1 == (a+1)){
System.out.println("A");
}else{
System.out.println("B");
}
}
}
There are still no warnings. Why?
Because the compiler does not execute your code. It only can issue a warning when it sees some "constants" or "constant expressions". Apparently when you put final the compiler then knows that this value cannot change. While if you use "real variables" or "variable expressions", it doesn't know because it doesn't execute your code (to see what the value of state or (a+1) is at this line). So in the latter case, you get no warnings. Hope this makes more sense now.
Think of it this way: the compiler does some code analysis. The first basic pattern is detected by this analysis, while the second pattern is not (probably as it's not that basic).
final means that something cannot be changed, so likely it was flagged because it can never and will never reach that else statement.
On a side note, you never have to do if(Boolean == true) you can just do if(Boolean)
The compiler does some optimization for final variable as shown below and in that case compiler knows that else part will never reached because final variable can't be changed later.
if (true) {
System.out.println("A");
} else {
System.out.println("B");
}
Read more JLS §4.12.4. final Variables
Find more possibilities for Unreachable code compiler error
First example:
When we use final keyword with a variable and assign a value to the variable, then that value can't change again. final boolean state = true; It can't have a value of "false".
Second example:
Here the variable state is not final. It has the possibility to get a value of "false".
So the different behavior is because of the final keyword.

How do you use an object reference as a while loop condition in Java?

I am new to Java and encountered a program with a 'while' loop that had the condition being an object reference/call. I traced the code thoroughly and did not see any terminating conditions for the object (it would make sense if the object in the while loop condition had a termination condition that the 'while' loop implementation caused).
NOTE: this involves 'inner'/'nested' classes, so I am not even entirely sure that that is the reason this works. How can a loop be satisfied by this manner of syntax? I will try to frame my question in the pseudocode below:
class DemoClass {
demoClassfoo() {
InnerClassdemo object2 = this.new InnerDemoClass;
// Here is where my confusion is. I always thought that the
// while loop had to terminate with a logical statement being
// satisfied: like it is calling an object?
while(object2.innerClassfoo()) {
IMPLEMENTATIONS;
}
}
class InnerDemoClass {
innerDemoClassfoo() {
IMPLEMENTATION;
}
}
public static void main(String[] args) {
DemoClass object = new DemoClass();
}
}
This works since the method innerClassfoo returns a booleanvalue, thus satisfying the while condition. By the way, the code should look like this:
class InnerDemoClass{
boolean innerDemoClassfoo(){
//implementation goes here
//make sure to ALWAYS return the value
boolean result = ...
return result;
}
}

Categories

Resources