I am always afraid of this code

G

gk

I am always afraid of this


public class Static
{
static
{
int x = 5;
}

static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}

public static void myMethod()
{ System.out.println(x );
y = x++ + ++x;

System.out.println(x );
}
}


ohh...horrible of ++ and ++ operator ......

+x means ...i understand...first increment and then its used in the
next statement

x+ means .....first utilized and then increment in the next statement


but still ...its pathetic to predict the output .....my headache.
 
P

Patricia Shanahan

gk said:
I am always afraid of this


public class Static
{
static
{
int x = 5;
}

static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}

public static void myMethod()
{ System.out.println(x );
y = x++ + ++x;

System.out.println(x );
}
}


ohh...horrible of ++ and ++ operator ......

+x means ...i understand...first increment and then its used in the
next statement

In Java, ++x is an operation that increments x by one, and whose result
is the incremented value.
x+ means .....first utilized and then increment in the next statement

Similarly, x++ is an operation that increments x by one, and whose
result is the value of x before the increment.

The result will not appear to be used until after x++ has been
completely executed.
but still ...its pathetic to predict the output .....my headache.

The output can be predicted by working through each expression, in the
light of the JLS. However, as the JLS says,

"Code is usually clearer when each expression contains at most one side
effect, as its outermost operation, and when code does not depend on
exactly which exception arises as a consequence of the left-to-right
evaluation of expressions."

"y = x++ + ++x;" has three side effects. Not good code.

Patricia
 
T

Tor Iver Wilhelmsen

gk said:
I am always afraid of this


public class Static
{
static
{
int x = 5;

This is a method variable in the static initializer that masks the
static field. Just so you know.
}

static int x,y;

These are initialized to 0.
ohh...horrible of ++ and ++ operator ......

Yes, but at least the precedence and consequence are specified in the
JLS - in C, you would have no idea since it's not defined. Unless the
standards have been updated, but even then you have no guarantee a
given compiler follows the standard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top