I have the following code:
Integer b = 4;
System.out.println(b+++10);
Why does System.out.println evaluate that expression? If you look at Java's source code you will not find the code that evaluates this expression.
Also, why does b+++ work? I thought that there could only be two + after a variable.
Thanks in advance.
If you put the code in Netbeans, and format it (Alt-Shift-F) you will see this:
Integer b = 4;
System.out.println(b++ + 10);
So the result is 4 + 10 which is 14. The value of b is 5 after the command.
Let me quote #Rup here for your first question:
It's not really println that's evaluating it - if you assigned it to a variable and printed that you'd get the same result.
To add onto that, it's Java that's evaluating that expression. If you put that into any other function it would work as well. It's part of Java — it's called "nested expressions."
For your other question see #user000001's answer, and there was also a discussion in the comments that added onto that (I have edited it to make it more clearer):
It's not clear at all normally the result is 15. b has been incremented.
In other words why Integer b = 4; System.out.println(b++ ); gives 4 even though b has been incremented. – BenMansourNizar
#BenMansourNizar This is because you are using the postfix operator (see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html.) With b++ the value is first used, and then incremented. If you use ++b, the value will be incremented before being used. – user000001 Jun 2 '13 at 17:58
Thanks a lot, user0000001 :) - BenMansourNizar
I hope you and other people find this information helpful, I really just quoted a bunch of stuff and commented on it :P
Related
I am using the Xtend templates to write a small program. I try using the IF statement, but every time I execute it it prints the variable in the console, which I dont want it to.
«IF x==y»
The jump value is «database.get(2)»
«jump_var_letter = String.charAt(1)»
«old_jump_ahd=database.get(2) »
«ENDIF»
Here the database is an array of integers and String is an array of letters. Here I just want it to print the value found at database.get(2) i.e 5. The last two expressions befor the ENDIF is meant for assignning a few values( which need not be printed)
The jump value is 5
Instead I get
The jump value is 5
D
5
Could somebody please tell me how I could stop printing the other two values.
Thank you in advance for your help..
After looking for sometime on the net I found that you could prevent the printing of the expreesions in between by using block expressions and then returning a null expression. (Although this method is not encouraged, I found that it provides me the result I wanted). So the expression I posted could be written as:
«IF x==y»
The jump value is «database.get(2)»
«{jump_var_letter = String.charAt(1); "" }»
«{old_jump_ahd=database.get(2); ""} »
«ENDIF»
This prints
The jump value is 5.
I have the following piece of code called Code1.
http://pastebin.com/tc0Vd8xh
When I run this, the sketch does not work.
However when I replace "i=+50" for "i = i + 50" the code works.
My question is why the "i=+50" bit does not work?
As far as I know "i=+50" is proper Java and Processing is based on Java.
I tried to Google about "i=+50" but Google does not process non-alphanumeric characters.
So I came here and I searched in previous questions before asking here. Anyone, any idea why "i=+50" does not work?
The statement i=+50 is the assignment of positive 50 to i. That is why it compiles, but doesn't add 50 to i on each loop. As #RoelHarbers and #ByoTic mentioned, you actually want i += 50
You're using =+, which is not a java operator (or an operator in any other language I know of)
The proper syntax is:
i+=50
Because it's i+=50 and not i=+50.
i =+ 50 is not going to do what you want, it is going to initialize i with 50. Instead, use i+=50, this going to add the 50 to whatever value that i holds.
I wanted to increment an integer by adding another one , but i wrote "=+" instead of "+=" . and i saw that it compiles but it does not do anything . or does it ?
a=3
b=5
a=+b
print a >>> 5
What is the reason ?
since =+ is not any operator (but += is).
So a=+b is equals "a = +b" and b = +b that will be a = b in the end.
may be you are looking for a += b which equals a = a + b
Think of the operation
a=3;
b=5;
a=-b;
That seems perfectly reasonable so it would be strange to disallow +b, I also very very occationally use this as a piece of self documentation (much like I sometimes put in +0), meaningless but harmless to the program but may have some meaning to a human observer
The string called "code" doesn't seem to read. Why is that and how do I fix it?
My code (the snippet that causes problems):
String code;
for(int z = 0; z<x;z= z+0) // Repeat once for every character in the input string remaining
{
for(int y=0;y<2;y++) //Repeat twice
{
c = (char)(r.nextInt(26) + 'a'); //Generate a random character (lowercase)
ca = Character.toString(c);
temp = code;
code = temp + ca; //Add a random character to the encoded string
}
My error report:
--------------------Configuration: <Default>--------------------
H:\Java\Compiler.java:66: variable code might not have been initialized
temp = code;
^
1 error
Process completed.
(I am using JCreator 5.00, Java 7.)
(Yes, the error report looks stupid, but it Stack Overflow reads it as coding.)
What value would code have if x is zero? The answer is it would have no value at all (not even null). You could just initialize it to an empty string if you like:
String code = "";
Java requires that every variable is initialized before its value is used. In this example, there is a fairly obvious case in which the variable is used before it is assigned. The Java Language Spec (JLS) doesn't allow this. (If it did, the behaviour of programs would be unpredictable, including ... potentially ... JVM crashes.)
In other cases, the compiler complains when in fact the variable in question is always initialized (or so it seems). Rather than "understanding" your code, or trying to derive a logical proof of initialization, the compiler follows a specified procedure for deciding if the variable is definitely assigned. This procedure is conservative in nature, and the answer it gives is either "it is initialized" or "it might not be initialized". Hence the wording of the compilation error message.
Here is an example in which the compiler will complain, even though it is "obvious" that the variable is initialized before use:
boolean panic;
for (int i = 0; i < 10; i += 2) {
if (i % 2 == 1 && panic) { // compilation error here
System.out.println("Panic!!");
}
}
The definite assignment rules (specified in the JLS) say that panic is NOT definitely initialized at the point indicated. It is a simple matter for a person who understands the basics of formal methods to prove that i % 2 == 1 will always be false. However, the compiler can't. (And even if it could, the code is still in error given JLS rules.)
You've created a reference, but you've never initialized it. Initialize code by changing the first line to
String code = ""
Edit: Zavior pointed out that you can pull an initialized string from the cache rather than allocate space for a new one.
But why are you assigning temp to code and then code to temp plus something else? It can be set to code = code + ca.
In the following line of code:
x = x.times(x).plus(y);
in what order are these expressions going to be executed?
Will it be like:
x = (x + y)*x
or x = (x^2) + y,
or something else and why?
Links to documentation about the specific subject will be highly appreciated as I had no luck with my search. Apparently I don't know where to look at and what to look for.
Thank you.
These are methods; the fact that they are called "plus" and "times" doesn't mean that they'll necessarily follow the behaviour of the built-in + and * operators.
So x.times(x) will be executed first. This will return a reference to an object, on which plus(y) will then be executed. The return value of this will then be assigned to x. It's equivalent to:
tmp = x.times(x);
x = tmp.plus(y);
Here's a link to a documentation which most likely contains the required answer (probably at 15.7). It's highly technical and verbose but not inaccessible to most people (I believe).
However, it seems that you're just starting programming, so you'll be better off reading other answers here, and programming more to get an intuitive feel (not exactly a 'feel', as it's systematic and rigourous) of the order of operations etc...
Don't be afraid to write "throw-away" code (which you can incidentally save too) to find out things you don't know if you don't know where else to look for the answer. You can always google more intensively or dive through the language specs at a latter date. You'll learn faster this way. :)
One simple way to find out is to write something like this:
class Number{
private int number;
public Number(int x){
number = x;
}
public Number times(Number x){
System.Out.PrintLn("times");
return number * x;
}
public Number plus(Number x){
System.Out.PrintLn("plus");
return number + x;
}
}
Method chains get executed from left to right, with each method using the result from the previous method, so it will be x = (x^2) + y.
What you're referring to in the algebraic expressions is operator precedence - evaluating multiplications before addition, for example. The Java compiler knows about these rules for expressions, and will generate code to evaluate them as you expect.
For method calling, there are no "special rules". When given x = x.times(x).plus(y); the compiler only knows that to evaluate x.times(x).plus(y), it first needs to know what x is, so it can call times on it. Likewise, it then needs to know what x.times(x) is so it can call the plus method on that result. Hence, this type of statement is parsed left to right : (x * x) + y.
Some languages allow the creation of functions that are "infix" with user supplied precedence. (such as Haskell : See http://www.haskell.org/tutorial/functions.html, section "Fixity declarations"). Java is, alas, not one of them.
It's going to be executed in left-to-right order, as
x = (x.times(x)).plus(y)
The other way:
x = x.(times(x).plus(y))
doesn't even make sense to me. You would have to rewrite it as
x = x.times(x.plus(y))
to make sense of it, but the fact that the second x is contained within times() while the y is outside it rules out that interpretation.
The reason the documentation doesn't say anything about this is probably that such expressions follow the normal rules for how a statement like a.b().c().d() is evaluated: from left to right. We start with a and call the function b() on it. Then, we call c() on the result of that call, and we call d() on the result of c(). Hence, x.times(x).plus(y) will first perform the multiplication, then the addition.