Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #38712

Re: value of Math.abs(a), int a=null;

From Eric Sosman <esosman@comcast-dot-net.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: value of Math.abs(a), int a=null;
Date 2019-01-22 11:32 -0500
Organization A noiseless patient Spider
Message-ID <q27gjr$v3t$1@dont-email.me> (permalink)
References <80e0e6bf-ef5a-4f3f-adf4-b5de4c6696ef@googlegroups.com>

Show all headers | View raw


On 1/22/2019 11:09 AM, Akshay Goel wrote:
> Hi all,
> 
> In below code, how is the if statement working?
> 
> 
> 
> Integer closest = null;
> 		for(int i = 0; i < n; i++) {
> 			int current = in.nextInt();
> 			if(closest == null || Math.abs(closest) > Math.abs(current)
> 					|| Math.abs(closest) == Math.abs(current) && closest < current) closest = current;
> 		}
> 		System.out.println(closest);

     It tests a combination of three conditions, one of which is
itself a compound expression of two conditions.  The combination
is true if

	closest is still `null'
OR
	|closest| > |current| (closest known to be non-`null')
OR
	the compound expression is true (see below)

     The compound expression has two conditions, and is true if

	|closest| == |current| (closest known to be non-`null')
     AND
	closest < current (closest known to be non-`null')

     Both the || and the && operators evaluate their operands in left-
to-right order, stopping as soon as the outcome is known.  For example,
if closest is `null' no further evaluations or tests are made, since
the first test has come up `true' and therefore the total outcome is
`true' no matter how the remaining conditions turn out.  That's why
the "known to be" remarks above hold: If closest is `null' their
conditions are never evaluated, hence if they're evaluated it must
be the case that closest is non-`null'.

-- 
esosman@comcast-dot-net.invalid
Seven hundred twenty-nine days to go.

Back to comp.lang.java.programmer | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

value of Math.abs(a), int a=null; Akshay Goel <goelakshay001@gmail.com> - 2019-01-22 08:09 -0800
  Re: value of Math.abs(a), int a=null; Arne Vajhøj <arne@vajhoej.dk> - 2019-01-22 11:20 -0500
  Re: value of Math.abs(a), int a=null; Eric Sosman <esosman@comcast-dot-net.invalid> - 2019-01-22 11:32 -0500

csiph-web