I was looking at a typical for loop:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
I am happy with the semicolons after int i=1: it is a statement which declares the new variable i. If i++ is also a statement, why doesn't it have a semicolon after?
Another example. I opened the Jshell and put the following:
jshell> int a=1;
a ==> 1
jshell> a++
$2 ==> 1
jshell> a
a ==> 2
jshell> int b=1;
b ==> 1
jshell> b++;
$5 ==> 1
jshell> b
b ==> 2
In other words the command ++ works, independently from whether there is a semicolon or not. I expected not to work without it.
Last example (adapted from a presentation about the difference between = and ==):
jshell> boolean x = false;
x ==> false
jshell> if (x = true) System.out.println("Sorry! This is wrong ...");
Sorry! This is wrong ...
jshell> boolean x = false;
x ==> false
jshell> if (x = true;) System.out.println("Sorry! This is wrong ...");
| Error:
| ')' expected
| if (x = true;) System.out.println("Sorry! This is wrong ...");
| ^
I get the point about the difference between = and ==. My question is why it works in the first half (if (x = true) without ;), and not with a ; (if (x = true;)).
Apologies for the several examples, but I think the question is relatively straightforward: if there are instances where an expression (without ;) works as a command statement (with ;), what is the function of semicolons?
The semicolon does nothing, it is there because a for loop is (amongst others) defined as
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
according to https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html
There are by definition two semicolons between the three parts.
The semiccolon is a separator of stack calls. The inside of if() wants a boolean, not a stack call.
Only inside the {} are statements expected.
The inside of for() expects three stack calls: One defining the loop variable, one defining the breaking clause and one defining what happens after each loop.
Example:
The construct for(;;); is a valid java construct. But you should never use it as the only thing it would do is loop over nothing forever: You don't define a variable, a breaking condition or something that gets executed after each call. During the loop you also just do nothing.
Related
I am learning java and this logic makes me feel confused.
Isn't here i=20(+1)+20(+1)?
Why 41 instead of 42?
jshell> int i = 20
i ==> 20
jshell> i=i++ + i++
i ==> 41
See this code run at Ideone.com.
Effectively, the expression i=i++ + i++; is equal to i=i++ + i;. Why? The latter i++ result value is never used and is not propagated. The result of the postfix addition i++ is used as long as the value i is added later in the expression and the result takes the effect. However, after the latter i++ the result value of i is not used.
If you want to achieve the result of 42, you need to perform the postfix assignment (i++) after the whole result is assigned back to the i variable:
int i = 20;
i = i++ + i;
i++;
System.out.println(i);
I have run this code in compiler and getting the output as 1 but I don't understand how it will be 1. Please explain with answer.
public class Main {
public static void main(String args[]) {
int a = 10;
int b = 2;
System.out.println((a < b) ? a++ : --b);
}
}
The ternary operator ?: will check the condition (a < b), since it is false, it will execute the expression after :, which is --b.
--b will subtract b by 1, and return the value after subtraction, which is 1.
The ternary operator is equivalent to a function that returns a value based on a condition. So let's write that function:
int ternary(int a, int b) {
if(a < b) {
int temp = a;
temp = temp + 1;
return a;
} else {
b = b - 1;
return b;
}
}
int a = 10;
int b = 2;
System.out.println((a < b) ? a++ : --b);
In the above code (a < b) is checking if a is less than b and if its true a++ will be executed, and if it is false (which is the case in this situation) --b will be executed, and as the value of b is initialized as 2 it will equal to 1 after doing --b operation
because as per the turnery operator in java
Expression1 ? Expression2: Expression3;
If Expression1 is evaluated at true, Expression2 will be executed otherwise Expression3
There are several great answers already. This took a bit to edit for formatting, but hopefully useful to illustrate what's happening.
The interesting part of your program is in the println() statement:
System.out.println((a < b) ? a++ : --b)
^^^^^^^^^^^^^^^^^^^
The whole thing inside the () is an expression with several things going on. At a high level, there is a boolean condition (a < b) followed by two other expressions: first is a++, second is --b. Below is a breakdown.
(a < b) ? a++ : --b
----- --- ---
^ ^ ^
| | |__ second expression, used if condition is "false"
| |
| |__ first expression, used if condition is "true"
|
|__ this is the boolean condition to check; whatever is inside must return either true or false
This is how the entire expression is evaluated:
Is the boolean condtion true or false? To answer that, we need to know: what does a < b evaluate to? Since a = 10, and b = 2, we can substitute the values (10 for a, 2 for b). So the question becomes: what does 10 < 2 evaluate to? Since 10 is not less than 2, the result of the boolean condition is false.
Which of the of two expressions should we go to? Since the result from #1 was false, we skip the first expression (a++), and go to the second one (--b).
What is --b? That's a fancy way of saying: b = b - 1 and also use the new value of b as the result of the expression. Since b = 2, it's equivalent to: b = 2 - 1, and use the new b value (1) as the result of the expression. So this expression evaluates to "1", and that's what is printed out. This part is tricky though. A variation would be b-- instead of --b – if you did that, it would mean: set the new value of b to the result of "2 - 1" (so, new value is "1" like with --b), but: for the expression result, use the old value. So --b ends up printing "1" in your example, and b-- would end up printing "2".
I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}
This question already has answers here:
If without else ternary operator
(10 answers)
Closed 6 years ago.
Is it possible to use a shorthand for ternary assignment expressions of the type
boolean x = false;
// ... code ...
a = x ? b : a; // Assigning a to a is pointless
a += x ? 1 : 0; // Adding 0 to a is pointless
I'm thinking something along the lines of
a = x ? b; // Assign b to a if x is true
a += x ? 1; // Add 1 to a if x is true
Not that it saves a lot of typing, I'm just curious if something like this exists. I just recently discovered the null coalesce operator in PHP 7, which does something kind of similar. To me it looks much cleaner than
if( x ) a = b;
if( x ) a += 1;
since these are assignments, and using a ternary expression looks more natural when reading from left to right. The supposed duplicate question isn't about assignments specifically, which in my opinion are a special use case of the ternary operator.
Unfortunately this is not supported by Java.
From the official oracle doc:
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson).
This operator is also known as the ternary operator because it uses three operands.
In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Because someCondition is true, this program prints "1" to the screen.
Use the ?: operator instead of an if-then-else statement if it makes your code more readable;
for example, when the expressions are compact and without side-effects (such as assignments).
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 5 years ago.
boolean r = false ; int s = 0 ;
while (r == false) ;
{
s = getInt() ;
if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ;
else r = true ;
}
The text never displays itself even when a 3 or a 123 is entered and the loop never terminates. Whats wrong here?
You have a semicolon after the condition. When you use braces to specify a block for your while you don't use a semicolon.
Remove the ';' after while.
Others have pointed out the bug, but your code is scary in other ways that will eventually trip you up:
if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ;
else r = true ;
That's bad because you can easily intend more than one statement to run in the case of the if or else clause. Use curly braces and avoid placing conditional statements on a single line:
if (!(s>=0 && s<=2))
{
System.out.println ("try again not a valid response");
}
else
{
r = true;
}
It's easier to read and far less likely to introduce hard-to-see bugs.
while(r == false)
should be
while(!r)
Despite what everyone else said about the semicolon, that is what I think is wrong with it :)
+1 to Daniel DiPaolo. I thought I'd post a separate answer to provide clarification of why this is the case.
While loops in Java can be written in one of two ways. If there is just one line to the body of the loop, you can write them in a short-hand fashion:
while (true)
System.out.println("While loop");
This will print out "While loop" on the console until the program ends. The other option is to specify a loop body between braces, as you have done above:
int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
This will print out "i = 0", "i = 1", ..., "i = 9" each on a separate line.
What the code you posted does is confuse the two. In the short-hand while loop, the Java parser expects to find a statement between the while loop condition and the semi-colon. Because it does not find a statement here, the while loop runs, but does nothing; it has no body. Furthermore, because the loop has no body, there is no opportunity for your variable r to assume a new value; the condition always evaluates to true and the loop never exits.
If you were to negate the condition in the while loop in your example, i.e.,
boolean r = false ; int s = 0 ;
while (r != false) ;
{
s = getInt() ;
if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ;
else r = true ;
}
(note I left the erroneous semicolon in there), you would find that your intended loop body would execute precisely once, as the loop would never run.
In addition to other comments, you should also change the if to
if (s < 0 || s > 2)
It's much more understandable this way.
Unrelated answer, I really really recommend you to follow Sun's style guidelines.
boolean r = false ;
int s = 0 ;
while (r == false) {
s = getInt() ;
if (!(s>=0 && s<=2)) {
System.out.println ("try again not a valid response") ;
} else {
r = true ;
}
}
You could get rid of the r variable and the if/else condition if you evaluate the result in the loop it self.
int s = 0;
while( ( s = getInt() ) < 0 || s > 2 ) {
System.out.println( "Try again, not a valid response");
}