What is difference between these two code snippets? - java

Below are two codes which first one is compiling and result is infinity loop, but with another one I get a compiler error as "Not a statement". As Math.random() returns double between 0.0 and 1.0 it is very strange for me why both of them do not gives same result.
1st
for(;;Math.random()){
System.out.println("Infinity Loop");
}
2nd
double i = 0.12654;
for(;;i){
System.out.println("Compile error");
}

The for loop requires three statements separated by semi-colons (or, as you illustrate, you can have no statement).
Java supports three types of statements:
Expression statements - those that create objects, call methods or change variables (e.g. Math.random())
Declaration statements - e.g. double i = 0.12654
Control flow statements - i.e. if, else, while, etc
i in the second incarnation isn't any of the above, which is why it fails compilation.

Related

Does the java compiler understand conditions given in if statements? [duplicate]

This question already has answers here:
(Compiler) else if(true) vs else scenario
(8 answers)
Closed 4 years ago.
The following code does not give the compile-error Unreachable statement.
if(true)return;
int x;
For years I believed that it's because the compiler does not pay much attention to the conditions given.
Today I found that the compiler understands the conditions,
int x;
if (true) {
x = 0;
}
int y = x;
because if not this should result in another compile-error variable x might not have been initialized. Which in fact compiles and runs perfectly. So,
Does the java compiler understand conditions given in if statements?
Unreachable Statements is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
For example, a Java compiler will accept the code:
int n = 5;
while (n > 7) k = 2;
even though the value of n is known at compile time and in principle it can be known at compile time that the assignment to k can never be executed.
The rules in this section define two technical terms:
whether a statement is reachable
whether a statement can complete normally
The definitions here allow a statement to complete normally only if it is reachable.
To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."
Source :
Java Language Specification (SE 7 Edition)
Chapter 14 - Blocks and Statements
Section 14.21 - Unreachable Statements

Java / Statements containing multiple '.' operators

In Java, consider the following piece of code:
Vector v = new Vector();
for(int i = 1; i <= 10; i++)
{
v.addElement(Integer.toString(i));
}
System.out.println(v.elementAt(9).toString());
Are Java statements like v.elementAt(9).toString() containing multiple '.' operators perfectly fine enough at all or do they cause any given type of conflict during some given period of time after all?
So far, I have only always kept them as safe enough in parenthesis, by making use of putting away off parenthesis around individual statements, so as not to create with any given type of conflict at all, after all.
(v.elementAt(9)).toString().
So far, I have never created with any given type of ambiguous statements like that during all of my own more than over a decade of programming and coding experience.
v.elementAt(9).toString().
Are Java statements like v.elementAt(i).toString() containing multiple '.' perfectly fine enough at all or do they cause any given type of conflict during some given period of time after all?
They are perfectly fine, with some caveats. If v.elementAt(i) is null, then calling v.elementAt(i).toString() will throw a NullPointerException. If you select i as some value that is either negative or larger than the Vector, I suspect an ArrayIndexOutOfBoundsException will be thrown as well. You can think of this syntax as the composition of functions (left-to-right), which is opposite how it is in mathematics.
In your specific example, this syntax is logically equivalent:
(v.elementAt(i)).toString()

Is an "If statement" the exact same as a "Switch statement" in Java?

Performance aside, I'm wondering if there are certain situations where only an If statement can be used and not a Switch statement and vice versa?
As in, are they completely interchangeable? Could I swap an entire section of code From Switch statements to If statements and vice versa if I so desired or would that break specific programs?
Not that I would want to but just theoretically and out of curiosity as I am new to Coding and have been wondering this.
I couldn't really find the answer I was looking for so I apologize if this is a duplicate.
They are fundamentally different in what they can do - if statements can check any logic you can distil down to a boolean value in some way, while switch statements compare exact values for each case - see the docs for details.
An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
This means if you want to do more complex logic than 'does this value equal this number, enum or string' for each case, you need if statements (or some other way of managing flow) rather than a switch.
A simple example is checking if a number is over 10 but under 9000.
if (value > 10 && value < 9000) {
...
}
Converting this to a switch statement would mean doing something insane like have a case for every possible value over 10 but under 9000)

What is the different in putting most possible true condition in if, else-if or else

Is there is any difference to put most probable condition in if, else-if or else condition
Ex :
int[] a = {2,4,6,9,10,0,30,0,31,66}
int firstCase = 0, secondCase = 0, thirdCase = 0;
for( int i=0;i<10;i++ ){
int m = a[i] % 5;
if(m < 3) {
firstCase++;
} else if(m == 3) {
secondCase++;
} else {
thirdCase++;
}
}
What is the difference of the execution time with input
int[] a = {3,6,8,7,0,0,0,0,0,0}
Is there is any different to put most possible true condition in if, else-if or else condition
Actually, the answer with Java is that "it depends".
You see, when you run Java code, the JVM starts out by using the using the interpreter while gathering statistics. One of the statistics that may be recorded is which of the paths in a branch instruction is most often taken. These statistics could then used by the JIT compiler to influence code reordering, where this does not alter the compiled code's semantics.
So if you were to execute your code, with two different datasets (i.e. "mostly zero" and "mostly non-zero"), it is possible that the JIT compiler would compile the code differently.
Whether it can actually make this optimization depends on whether it can figure out that the reordering is valid. For example, can it deduce that the conditions being tested are mutually exclusive?
So how does this affect the complexity? Well ... lets do the sums for your simplified example, assuming that the JIT compiler doesn't do anything "smart". And assume that we are not just dealing with arrays of length 10 (which renders the discussion of complexity moot).
Consider this:
For each zero, the loop does one test and one increment - say 2 operations.
For each non-zero element, the loop does two tests and one increment - say 3 operations.
So that is roughly 2*N operations for N elements when all zero versus 3*N operations ehen all non-zero. But both are O(N) ... so the Big O complexity is not affected.
(OK I left some stuff out ... but you get the picture. One of the cases is going to be faster, but the complexity is not affected.)
There's a bit more to this than you're being told.
'if' versus 'else': If a condition and its converse are not equally likely, you should handle the more likely condition in the 'else' block, not the 'if' block. The 'if' block requires a conditional jump which isn't taken and a final branch around the 'else' block; the 'else' block requires a condition branch which is taken and no final branch at all.
'if' versus 'else if' versus 'else': Obviously you should handle the most common case in the 'if' block, to avoid the second test. The same considerations as at (1) determine that the more common case as between the final 'else if' and the final 'else' should be handled in the final 'else' block.
Having said all that, unless the tests are non-trivial, or the contents of all these blocks are utterly trivial, it it is rather unlikely that any of it will make a discernible difference.
There is no difference if you only have an if-else, since the condition will always be evaluated and it does not matter whether it is almost always true or false. However, if you have an if in the else part (the else if), it is much better to put the most possible true condition in the first if. Therefore, most of the time you won't need to evaluate the condition inside the else, increasing performance.
If most conditions are true in if then the execution time will be less .Because in the first if condition only it satisfied.
If most conditions are true in if-else then the execution time will be less then last and more than first scenarios .
If most conditions are true in else then the execution time will be more.Because it checkes first 2 conditions.
Sure it is.
if ... else if ... checks are going in order in which they were coded. So, if you will place most possible condition in the end of this conditions checking queue - such code will work slightly slower.
But it all depenends how these conditions are built (how complex they are).
Most Possible condition should go to the if and then if else and so on.
It's good to write the most common condition in the very first level so that if that condition is true or false will be treated first in less time.
If you put the most frequent condition in middle (else..if) or in last (else), then it will take time to reach to that condition statement because it needs to check every condition statement.

Equivalent boolean statements have different results

I am confused about how && operator is working
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
Above statement is coming as true
while
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
is evluaated as false.Only difference between the 2 statements are braces.
As an additional input i have checked it with debugger and
StringUtils.isNotEmpty(cartModification.getStatusCode() =true
cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)=true
I just added extra parenthesis in the second part and it was evaluated as true, Data is same as i have pointed out in question.
Since the commentbox isn't really approriate for this one:
How about trying this in a single run.
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
System.out.println("First try is true");
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
System.out.println("Second try is true");
No matter what, you should either get no or two lines (since both statements are the same).
Note it's possible that just one line is printed, this means that any call on getStatusCode() invokes a change on any value used in at least one of the conditions.

Categories

Resources