My Java instructor yesterday gave us a sample test. One line that surprised me was something like
if ( m2++ < 10 ) { ………

iow the first thing done is , in effect m2 = m2 + 1, an ASSIGNMENT.

Whether the instructor ever actually discussed this in the first place
cannot be answered on this site. But other relevant questions can.

First, my ignorance. While I am obviously not an expert ,
neither am I exactly a neophyte virgin. But I must admit
this idea of an assignment statement INSIDE an if statement boolean expression
( as opposed to AFTER the then/else portion ) is a big newsflash to me.
Two questions follow :

1) how common in other languages is this concept nowadays ?

2) On a scale from zero meaning complete ignorance to 10
meaning world’s greatest expert,
how does my complete ignorance of the concept actually rate ?

A third question is more subjective :

could you describe a situation where this facility would be useful or indeed advisable ?

Thanks.

Recommended Answers

All 5 Replies

This kind of thing isn't particularly rare, nor is it reserved for advanced users. One case you see very often is when you read bytes from a Reader while checking for end-of-file (returns -1 for number of bytes read), eg

if (int bytesRead = reader.read(buffer) >= 0) {...

although the while (... version is even more common

I'll take '[not ] particularly rare' to mean 'rare enough', thanks.

And yes, a 'while' version was also shown, but as far as I am concerned it's the very same idea,
so my own mentioning of only the 'if' was enough here.

To be honest - some variant on that read/testEOF combo is in most programs that read from a file. I would really have to classify it as a common standard pattern. It's only "rare" in applets. But don't worry, some of us have been using Java since last century but still keep coming across things we didn't know about it.

Reassuring to know about always 'coming across things we didn't know about it',
but even more so is the knowledge that boolean assignments are NOT
as well known 'a trick of the trade' as, say, a switch/break construct.

actually, they are, but in most cases they can be written in another way, which a lot of developers prefere, since, whether it's known or not, developers with less experience might find the code a bit harder to read, and might have a bit more trouble predicting the flow a piece of code will go through, or the output a piece of code might produce.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.