#Comparing `int` Values As `booleans`

1 messages · Page 1 of 1 (latest)

rose cobalt
#

I'm constantly switching from C++ to Java bc I like both. Can someone explain me why java doesn't accept numbers as conditionals? Example:

C++

int val {1};
if (val) {} // FINE.

Java:

int val = 1;
if (val) {} //error

Even that needs to be verbose peepo_sad

Java:

[...]
int val = 1;
if (val == 1) {} // fine

Why is that? I'm not talking about business decisions, but why Java can't treat ints as booleans? What is happening in background?

grave radishBOT
#

<@&987246399047479336> please have a look, thanks.

grave radishBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

rose cobalt
#

Like, look at this... booleans are ints in background and I don't understand that

graceful surge
#

ints aren't booleans.

rose cobalt
#

You're right. It's the inverse

#

Same argument..

graceful surge
#

booleans aren't ints.

rose cobalt
#

Well, may not be in java

#

Everithing != 0 is true

graceful surge
#

Why not also != 0.1?

#

Or some arbitrary precision? Also why not negative numbers?

#

Who decides these things? I think you'll find you've reached a higher level once you stop caring about such tiny, irrelevant details.

rose cobalt
#
if (4897) {
  //this will run
}
if (1) {
  //this will run
}
if (0) {
  //this wont
}
graceful surge
#

None of these will run in Java.

#

It's better to be explicit than implicit, which is most likely why this rule was implemented.

#

That's the why. I would suggest moving on now...

rose cobalt
graceful surge
#

What about -0?

#

What about a NaN representation?

rose cobalt
graceful surge
#

Floating points can certainly be used in ifs in C, etc., can't they?

rose cobalt
graceful surge
#

It's not, I just said, it's explicit.

#

But wouldn't you expect it to run?

clear bridge
#

it's because you're confusing an int of value 1 (32 bits) with a boolean that is a single bit

rose cobalt
#

And there's no -0 in any place

graceful surge
#

Doesn't IEEE 754 allow for a -0 representation?

#

That's different from 0, right? So something is set.

rose cobalt
graceful surge
#

Haha.

rose cobalt
#

No twos complement

graceful surge
#

In IEEE 754 decimal floating-point formats, a negative zero is represented by an exponent being any valid exponent in the range for the format, the true significand being zero, and the sign bit being one

clear bridge
#

If you want to use the bit value, you have to use bitwise e.g. ```
int val = 0;
val |= 1; // true
val ^= 1; //false

graceful surge
#

Seems like something is set.

#

It's not 0x0.

rose cobalt
#

Well, it's not 🤷‍♂️

graceful surge
#

So now you see, you had to check that, and that might have been, essentially, logic-wise, unexpected behavior.

rose cobalt
#

We can check in any binary calc in google

graceful surge
#

Do you think everyone knows that -0 will/will not run?

#

I'm talking about -0.0f, of course.

#

(For clarity's sake.)

graceful surge
#

Are you familiar with IEEE 754?

rose cobalt
#

Not that much

graceful surge
#

You should look into it. Floating points also work in ifs, and they are governed by that standard.

#

I'm talking about C and C++ here.

rose cobalt
#

I just know that any -0.0 -0.0f -0.0000000 wont run because the mantissa is the same, the exp is the same and theres no sign bit

graceful surge
#

There is a sign bit, unless you're not looking at it?

#

Why aren't we?

rose cobalt
#

Well, I should look I guess

graceful surge
#

Lol.

#

So now you have to know exactly which parts of the bit representation of a floating point number are looked at in an if.

rose cobalt
#

Containing or not, it wont run.. That's what I'm talking about and don't like about Java 🤷‍♂️

graceful surge
#

That sounds ridiculous to me. It sounds like the kind of unpredictability I'd rather avoid.

#

Just be explicit, why is that so hard?

#

Do you think it's easier writing implicit, short, hard to read code? Maybe the first time.

clear bridge
graceful surge
#

Yeah, that's one way to earn the magician title.

rose cobalt
#

Not that explicit.. That annoys me

lets say I'd want an array of 'bits'

int[] myarr = new int[64];
[...] filling the bits with 1s

for... i..... {
  if (myarr[i]) {} // nonono, gotta be explicit
  if (myarr[i] == 1) {} // yeeey
}
grave radishBOT
graceful surge
#

There's another, oft-quoted reason, which is that it prevents you from doing stuff like if (x = 0), which has side effects.

clear bridge
#

stop crying over needing to add 3 extra characters 😐

rose cobalt
#

My opinion won't change anything I know, I just wish to know why it's done like that.. Not about business/language decicions. How integers cannot be treated as booleans too.

graceful surge
#

I've named two reasons now.

clear bridge
#

because they're different types

rose cobalt
clear bridge
#

you can probably do it in something like groovy where everything is dynamic

#

but Java is strongly typed and is strict

graceful surge
#

Does C++ even have the boolean type?

rose cobalt
rose cobalt
graceful surge
#

Yeah, so no true boolean type, that's the thing.

clear bridge
#

in Java

rose cobalt
rose cobalt
clear bridge
#

part of the point is to have a clear distinction between the 2 primitives

#

otherwise you might aswell have char true_ = '1';

#

or String true_ = "1"

rose cobalt
#

This is true booleans

int insert(some element) {
  if (inserted) {
    return 1;
  }
  return 0;
}
clear bridge
#

you'd be making the actual boolean type redundent and reduce readability

#

if this was java

rose cobalt
foggy seal
#

i didnt read the entire discussion, but it's a design decision, for code readability. even in c++ decaying stuff to boolean is generally considered an antistyle

#

in most situations at least

clear bridge
rose cobalt
#

'booleans' are in the end just 1s and 0s

foggy seal
#

there are a few idiomatic things that are okay to use, such as if (optional), if (smart_ptr) , but thats about it

rose cobalt
#

The original topic

clear bridge
#

Remember, what I mentioned about bits @rose cobalt , you'd be using 32 bits instead of 1 bit if we used int's to hold booleans

#

you already have a cost (if the java compiler allowed it)

foggy seal
#

its a design decision. using ints as boolean creates unreadable and confusing code. even in c/c++ people avoid it

rose cobalt
#

Since I can't access individual bits directly in any language

clear bridge
#

you can via bitwise operations

#

kinda* (you can set)

foggy seal
#

it would be easy to add it in java. but they don't on purpose

#

whether u personally like that or not is another story of course

rose cobalt
#

I was just curious about why java doesn't allow me to do this @ Zabuzard ... It's like booleans and ints were completely different things

foggy seal
#

bc its bad design

#

hence they didn't allow it

#

even in c/c++ u will get complains if u do that

rose cobalt
#

So it's a business decision.. I'm just curious to know how they differenciate these two types in background... As they both are primitives..

rose cobalt
foggy seal
#

it creates unreadable and easy-to-get-wrong code. it easily creates bugs

foggy seal
scarlet mauve
# rose cobalt I'm constantly switching from `C++` to `Java` bc I like both. Can someone explai...

the reason is design decision
by allowing boolean evaluation of things that aren't booleans you drastically reduce readability and increase chance of bugs
since now if you compare something, you can't know if it is a boolean or if it is something else, and more often that not, you want to use ints as ints, not as booleans, and so if you try to put an int in an int, it should be a compile time error so you must explicitly tell java that you want to compare them

rose cobalt
#

I'll take a deeper look after

foggy seal
#

its a vm, it's never simple in a vm. since it does a lot of optimization

#

for example memory padding and alignment

scarlet mauve
foggy seal
#

shorts are often increased to ints to increase performance, for example

scarlet mauve
#

so booleans in local variables are just syntax sugar

rose cobalt
#

Makes a lot of sense

rose cobalt
rose cobalt
#

Okay guys

#

I think I got my answers

#

Very interesting topic

foggy seal
#

its just one of many many things that happen in the background

#

in the vm

#

there is a big gap between ur code and what it actually results in

#

unlike non-vm code

rose cobalt
scarlet mauve
#
public class Tmp {
    public static void main(String[] args) {
        boolean foo = Boolean.parseBoolean(args[0]);
        if(foo) {
            System.out.println("test");
        }
    }
}

This compiles to

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: (0x0009) ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=2, args_size=1
         0: aload_0
         1: iconst_0
         2: aaload
         3: invokestatic  #7                  // Method java/lang/Boolean.parseBoolean:(Ljava/lang/String;)Z
         6: istore_1
         7: iload_1
         8: ifeq          19
        11: getstatic     #13                 // Field java/lang/System.out:Ljava/io/PrintStream;
        14: ldc           #19                 // String test
        16: invokevirtual #21                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        19: return
      LineNumberTable:
        line 3: 0
        line 4: 7
        line 5: 11
        line 7: 19
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      20     0  args   [Ljava/lang/String;
            7      13     1   foo   Z
rose cobalt
#

Comparing int Values As booleans

scarlet mauve
rose cobalt
#

Hmmmm, now I get

scarlet mauve
#

@rose cobalt anyway, just to say that between the language and what's behind it, there can be huge differences
and java not allowing int in ifs is a design decision so you don't shoot yourself in the foot
but note that not everything works like that, there are many places, even in java where you have hidden conversions or things like that, that can make you shoot yourself in the foot

rose cobalt
rose cobalt
#

Nice to know more in depth about it

scarlet mauve
rose cobalt
#

You say boxed types like Integer.. Double etc.. right?

scarlet mauve
#

yes

rose cobalt
#

All right

#

Thanks a lot

scarlet mauve
#

and strings conversions

#

ie "foo" + 5

rose cobalt
#

Yea, that could lead me to problems

scarlet mauve
#

like a few days ago, I had a problem like that :

#

"some string " + someObject.stream().map(...)
instead of
"some string " + someObject.stream().map(...).toList()

#

(in my case it wasn't a stream, but something similar where you must call the terminal operation)

#

this code not only compiles but also show no warning

rose cobalt
#

Dangerous

#

But it's more predictable than other implicit conversions

scarlet mauve
#

and since java appends automatically, there is no way to prevent that

rose cobalt
#

Strings + something = String

scarlet mauve
#

hopefully, since it was my class, I managed to override toString causing an exception so at least I have a runtime check

#

...at the cost of causing havoc in some debuggers -_-

scarlet mauve
#

no it's not nice -_-

rose cobalt
#

'0' == 0peepo_christ

scarlet mauve
rose cobalt
scarlet mauve
rose cobalt
scarlet mauve
rose cobalt
#

yeah

#

but if it's working, were fine animesmile

scarlet mauve
#

anyway, the design lesson is that you must put some hard limits to what users can do

#

and the least limits you put, even if it makes sense, the more problems you have

#

ie the whole c language

rose cobalt
#

all right

#

thanks