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
Related
I have the following code delay = (delay>200) ? delay : 200;
Java issues a warning message Can be replaced with 'Math.max' call for this.
Here I see that Math.max(a, b) is actually the same as (a > b) ? a : b so ternary operator is not worse than Math.max
So why Java issues this warning message if there are no advantages replacing the ternary operator by Math.max method call?
I doubt that this is a real compiler warning, probably some IDE inspection/warning.
Nonetheless, you are correct, there are no hard technical reasons to prefer one over the other.
But: from the point of a human reader, using Math.max() has one major advantage: it is easier to read and understand. That simple.
Besides: do not duplicate code unless you have to.
Always remember: you write your code for your human readers. Compilers accept anything that is syntactically correct. But for your human readers, there is a difference between a condition and an assignment vs a very telling "take the maximum of two numbers".
Math.max(a, b) is more readable than the tenary statement because:
the value 200 does not need to be repeated.
there is no need to write and understand >
In general, the ternary is more powerful because it lets you do things like this:
delay = (delay>200) ? 200 : delay;
delay = (delay<200) ? delay : 200;
delay = (delay>200) ? delay: 300;
The reader of your code needs to understand which of those things you are actually doing. It takes time to parse it and understand it is a simple max().
The max shows your intention more clearly.
In addition to the existing answers, there can be a performance advantage if the lower limit (in your case, 200) is not a constant but a derived value:
delay = (delay > readLimitFromFile()) ? delay : readLimitFromFile();
This could end up doing 2 expensive disk-read operations, when one operation would be sufficient. Using Math.max:
delay = Math.max(delay, readLimitFromFile());
would use only one disk-read operation.
I had this question on a homework assignment (don't worry, already done):
[Using your favorite imperative language, give an example of
each of ...] An error that the compiler can neither catch nor easily generate code to
catch (this should be a violation of the language definition, not just a
program bug)
From "Programming Language Pragmatics" (3rd ed) Michael L. Scott
My answer, call main from main by passing in the same arguments (in C and Java), inspired by this. But I personally felt like that would just be a semantic error.
To me this question's asking how to producing an error that is neither syntactic nor semantic, and frankly, I can't really think of situation where it wouldn't fall in either.
Would it be code that is susceptible to exploitation, like buffer overflows (and maybe other exploitation I've never heard about)? Some sort of pit fall from the structure of the language (IDK, but lazy evaluation/weak type checking)? I'd like a simple example in Java/C++/C, but other examples are welcome.
Undefined behaviour springs to mind. A statement invoking UB is neither syntactically nor semantically incorrect, but rather the result of the code cannot be predicted and is considered erroneous.
An example of this would be (from the Wikipedia page) an attempt to modify a string-constant:
char * str = "Hello world!";
str[0] = 'h'; // undefined-behaviour here
Not all UB-statements are so easily identified though. Consider for example the possibility of signed-integer overflow in this case, if the user enters a number that is too big:
// get number from user
char input[100];
fgets(input, sizeof input, stdin);
int number = strtol(input, NULL, 10);
// print its square: possible integer-overflow if number * number > INT_MAX
printf("%i^2 = %i\n", number, number * number);
Here there may not necessarily be signed-integer overflow. And it is impossible to detect it at compile- or link-time since it involves user-input.
Statements invoking undefined behavior1 are semantically as well as syntactically correct but make programs behave erratically.
a[i++] = i; // Syntax (symbolic representation) and semantic (meaning) both are correct. But invokes UB.
Another example is using a pointer without initializing it.
Logical errors are also neither semantic nor syntactic.
1. Undefined behavior: Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.
Here's an example for C++. Suppose we have a function:
int incsum(int &a, int &b) {
return ++a + ++b;
}
Then the following code has undefined behavior because it modifies an object twice with no intervening sequence point:
int i = 0;
incsum(i, i);
If the call to incsum is in a different TU from the definition of the function, then it's impossible to catch the error at compile time, because neither bit of code is inherently wrong on its own. It could be detected at link time by a sufficiently intelligent linker.
You can generate as many examples as you like of this kind, where code in one TU has behavior that's conditionally undefined for certain input values passed by another TU. I went for one that's slightly obscure, you could just as easily use an invalid pointer dereference or a signed integer arithmetic overflow.
You can argue how easy it is to generate code to catch this -- I wouldn't say it's very easy, but a compiler could notice that ++a + ++b is invalid if a and b alias the same object, and add the equivalent of assert (&a != &b); at that line. So detection code can be generated by local analysis.
I'm trying to use equalsIgnoreCase() in a while loop to try and check if something other than what was intended to be written was written by using the NOT (!) operator. For example:
String temp="A";
boolean x =(!temp.equalsIgnoreCase("a")) ;
See, this works with a while loop. If it's not A, it will keep looping but this next line does not
boolean x =(!temp.equalsIgnoreCase("a") || !temp.equalsIgnoreCase("b")) ;
This does not seem to work anymore. This returns true, no matter what you type, even if it is a or b. So when I use the whole line of code to check for any of the letters that are not suppose to be used:
while (!temp.equalsIgnoreCase("A") || !(temp.equalsIgnoreCase("B")) ||!temp.equalsIgnoreCase("D")|| !temp.equalsIgnoreCase("P") || !temp.equalsIgnoreCase("S"))
{ ***Do Code***}
it loops whatever you put in, even if it will equal one of the letters.
When there is more than one !temp.equalsIngnoreCase, the code does't work with OR (||).
The only way I can get it to work is if I change the OR to AND
while (!temp.equalsIgnoreCase("A") && !(temp.equalsIgnoreCase("B")) && !temp.equalsIgnoreCase("D")&& !temp.equalsIgnoreCase("P") && !temp.equalsIgnoreCase("S"))
Even though I seem to have found a solution, I still don't understand why OR doesn't work but AND does. I removed the NOT to see if everything works, and it seems to loop perfectly when one of the letters is entered.
it loops whatever you put in, even if it will equal one of the letters.
Yes, of course it does.
You're asking it to keep going while it isn't A or it isn't B. Well nothing can be both A and B... if the value is equal to B then it won't be equal to A so the first operand will keep the loop going. If the value is equal to A then it won't be equal to B so the second operand will keep the loop going.
Your solution of changing to AND is correct - you want the value to not be A and not be B (i.e. it's neither A nor B).
Alternatively, you could use OR internally, but put a NOT around the whole thing:
while (! (temp.equalsIgnoredCase("A") || temp.equalsIgnoreCase("B") || ...))
I still don't understand why OR doesn't work but AND does
The expression using || will always be true at any given value of temp. Because, temp cannot be both a and b at the same time. If it is a, then the 2nd part of || will be true, and if it is equal to b or any other value, the first part will be true, thus making the entire expression true in both the cases.
With &&, your while will only be true, if temp is neither of a nor b.
Alternatively, if you are going to test temp against many values, you can change your while condition to look simpler:
while (!"ABDPS".contains(temp.toUpperCase())) {
}
its a foul logic. the code
(!temp.equalsIgnoreCase("A") || !(temp.equalsIgnoreCase("B")) ||!temp.equalsIgnoreCase("D")|| !temp.equalsIgnoreCase("P") || !temp.equalsIgnoreCase("S"))
means
if char is not A, or not B, or not D, or not P, or not S. It will always evaluate to true, since is char is A, it will neither be B,D,S nor P. so is for the others.
if you want it to be OR logic, it should be:
(!(temp.equalsIgnoreCase("A") || (temp.equalsIgnoreCase("B")) ||temp.equalsIgnoreCase("D")|| temp.equalsIgnoreCase("P") || temp.equalsIgnoreCase("S")))
which means, not when the char is either of A, B, D,S or P
This is all about logic.
A OR B means that is is true when A is true or B is true or both are true.
In your special case it is only possible that one of your equalsIgnorecase() can ever work, so you wrote something like a tautology which means an endless loop.
You can read about boole algebra here: http://en.wikipedia.org/wiki/Boolean_algebra_%28structure%29
Kind of some theory but it explains what you need to know when you write boolean expressions.
Hope this helps :)
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
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.