PrestwoodBoards Knowledgebase: portal.prestwood.com/ASPSuite/kb/

store.prestwood.com

  From the February 2016 Issue of Prestwood eMag
 
Java Language Basics:
Java Logical Operators
 
Posted 2/11/2009 on 2/11/2009
Java Code Snippet:

KB101885

Languages Focus: Logical Operators

Logical operators perform conditional and, or, and not operations. Some languages support both binary logical operators that link two and unary logical operators negate (make opposite) the truth value of its argument. Finally, some languages short circuit logic. For example, with this or that, if this is an expression returning true, then that is never executed.

Java Logical Operators

Java logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This
& boolean logical OR (not short circuited)
| boolean logical OR (not short circuited)
?: Ternary (short for if-then-else)
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
^ Bitwise exclusiv OR

Syntax Example:
//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}

Comments

1 Comments.
Share a thought or comment...
Comment 1 of 1

The logical operators '&' and '~' (bitwise 'and' and 'not') can be useful in rounding numbers. Suppose I have a variable x and I want to round it up to a multiple of 4. This code will do that.

    x = (x + 3) & ~3;

Rounding down to a multiple of 4 is even easier.

    x = x & ~3;

This only works for rounding to a power of 2, however, that is a common requirement and this code is much more efficient for rounding to a power of 2 than using the modulo operator and division.

Posted 2/11/2009
Code Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile
store.prestwood.com
Copyright (C) Prestwood IT Solutions.
All Rights Reserved.
Printed 9/24/2020