Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

underlying value of boolean "false", "true"

 
tod murphey
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello again,
Based on the answer to this question... it appears that '1' represents false, does this seem correct?
1. class X {
2. public static void main(String[] args) {
3. boolean[] b = new boolean[1];
4. flip(b);
5. System.out.println(b[0]);
6. }
7.
8. static boolean flip(boolean[] b) { return (b[0] = !b[0]); }
9. }

 
sunilkumar ssuparasmul
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
i cannot understand what r u trying to say?
it prints "true " only which is obviously the result.
bcos ! converts the value of boolean expression.
HTH
sunils./
------------------
"Winners don't do different things
They do things differently"
 
Cherry Mathew
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
when u create an array it will be given default values and bolean is given default value fale that is the reason why u r getiing false .
please dont confuse the new operator used with a constructor u r just alloting space for the array it means that ur array contains 1 element
it will return true from the method bcoz asingnment is done first
Cherry
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Just to give you a full explanation of your example.
boolean[] b = new boolean[1];
Creates an array of boolean values. Java automatically initializes array so the result is that we have a one element array that is initialized to 'false'.
flip(b);
Java passes by value, therefore passing arrays to methods allow us to change any of the values. The flip method performs unary operator '!' which alters the 'false' to 'true'.
System.out.println(b[0]);
Gives use the expected result of 'true'.
This example shows that you can use arrays if you need to alter primitive values in methods and have the changed result returned to the calling method. For example if arrays were not used:
boolean b = false;
The flip method change would not be reflected at all because it would be passed a copy of b instead of b so changing it would have no effect on b!
Knowledge is good,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic