How does this equal 105 instead of 15? - java

public class Review {
public static void main(String[] args) {
int x = 10, y = 5;
System.out.println(" " + x + y); // string + x + y
}
}
How does this equal 105 rather then 15?
What makes it different from the below code?
public class Review {
public static void main(String[] args) {
int x = 10, y = 5;
System.out.println(x + y); //Only x + y
}
}

" " + x + y means " " + x then + y
so the first code that you write we can divide into 2 steps:
1. " " + x => " " + 10 => "10"
2. "10" + y => "10" + 5 => "105"
But the second is just a number + number, so we get the number result.
I'm not a native English speaker, and I'm learning, sorry about my bad English, And I hope this is helpful.

The first answer the type is String because of the " " and you are using string concatenation by using the +
With the second one, the + is not being used to concatenate with a String.

When you mix a primitive data type with a String in System.out.println(), the Java compiler assumes that you want every data type to be converted to a String object. Adding brackets around your primitive data types allows you to calculate first before conversion as Jim Garrison suggested: System.out.println(" " + (x + y));

Related

Quotes in Java Equations

Reading Java Headfirst found this example pls if someone can help me understand.
class Scratch {
public static void main(String[] args) {
int x = 0;
int y = 0;
while ( x < 2 ) {
y = y + x;
System.out.print(x + "" + y + " ");
x = x + 1;
}
}
}
I can't wrap my head around whats the function of quotes here in print statement the results vary a lot if you remove them.
The second one adds "Space" but the first somehow adds another integer?!
This is a common Java idiom to convert a number to a string:
int x = 1;
System.out.println(x + "" + x); // prints 11
In Java the + operator is overloaded to mean either addition or string concatenation, depending on the operand types.
What happens here is that x + "" is interpreted as a string concatenation rather than an addition.
x + "" -> 1 + "" -> "1"
"1" + x -> "1" + 1 -> "11"
Now there are some people who say that x + "" should be written as String.valueOf(x). They say that the latter is more efficient. In reality, it depends on how good the JIT compiler is at optimizing string concatenation expressions, and that varies with the Java version.

Java println weird output

I'm getting a weird output from running this simple java program.
The output is: 0 4 2 -6
Why does the x++ print 0, it should be printing 4.
import java.util.*;
import java.io.*;
public class Java1 {
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
}
public static int func(int work, int y) {
int z = work + y;
work++;
y++;
System.out.print(z + " ");
return z + work + y;
}
}
Okay, here is what's going on: First x++ is evaluated, returning 4 (which is later printed) and leaving x at 5. Then x++ is evaluated again, passing 5 to func. Then func is evaluated with 5 and -5 parameters. In here z is 0 (5 + (-5) = 0) which is then printed (BEFORE the println in the main method. func then returns 2 (0 + 6 + (-4)) which is also added to the string. Finally --y results in -6. Now the println in the main method prints its string (4 2 -6).
func(x++, y) is executed first, so 0 comes from System.out.print(z + " "); in func.
System.out.print(z + " ");
is executed before
System.out.println(x++ + " " + func(x++, y) + " " + --y);
So the 0 comes from z, not x.
I have mentioned the flow of points from 0 to 7 in the comments
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
// thus 0]4 6]2 (value returned as z) 7] localvalue of --y as -6
}
//1] x++ makes x as 5 when it is passed to func()
public static int func(int work, int y) {
int z = work + y;
//2] z = 5 + -5 = 0
work++;
//3] work which was x as 5 is now 6
y++;
//4] y will be -4 now
System.out.print(z + " ");
return z + work + y;
//5] z = 0 + 6 + -4 = 2 and is returned to func() caller
}
import java.util.*;
import java.io.IOException;
public class Java1
{
public static void main(String args[])
{
int x = 4;
int y = -5;
System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
}
public static int func(int work, int y)
{
int z = work + y;// 5+-5 = 0
work++; //6
y++; //-4
System.out.print("Z = " + z + " ");//0
return z + work + y; //0 + 6+-4 = 2
}
}
OUTPUT :
Z = 0 x = 4 func = 2 y = -6
Here the func() is executed first and hence the value of variable z is printed as 0 and then the x++ value is printed as 4.

Precedence in Strings in Java [duplicate]

This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed 7 years ago.
what is the explanation of this precedence in strings in java?
public class PrecedenceInStrings {
public static void main(String[] args){
int x = 3;
int y = 5;
String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";
System.out.println(s6 + "\n" + s7 + "\n" + s8);
}
}
output:
8total
total 35
35total
Java compiler processes operators + in your expressions left to right. When it comes to the first + in
x + y + "total"
it sees ints on both sides, so it performs an addition. When Java compiler processes the second +, it sees an int and a String, and interprets the operator as string concatenation.
In your second and third expressions the left-hand side of the + operator is a string, so all operators get interpreted as concatenations.
If you want to force a specific order of operations, use parentheses. For example, if you would like to get the total in your third example, parenthesize the addition, like this:
String s8 = " " + (x + y) + "total";

Equations in Java - output is either 0 or incorrect value [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I am new to Java and am trying to make a program run to solve and display
the output of the equations. I have tried changing the places of the
parenthesis, and putting equations in other parts of the code but I either get 0
as the output or wrong answers. Any words of wisdom would be greatly
appreciated.
import java.util.*;
import static java.lang.Math.*;
public class JFirstTest
{
public static void main(String[] args)
{
// Declare variables and equations
int W, X, Y, Z;
W = 10;
X = 20;
Y = 30;
Z = 40;
int FormulaOne = (W + X) / (Y + Z);
int FormulaTwo = (X + ( Y / W)) / Z;
int FormulaThree = X * (W - Y)/ (X * Y - Z);
// System.out.println formulas
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaOne = " + FormulaOne);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaTwo = " + FormulaTwo);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaThree = " + FormulaThree);
System.out.println("\n");
Update: This has been marked as Duplicate, however, I did searches before I
posted this question and the answers eluded me...Also changed int to double
and now it works fine.
Dividing integer by integer will result in integer, and round down (truncate). So, dividing smaller number by larger will result in zero, so you may want to consider changing type of variables to float / double.
Think of it this way... if an int (integer) is a whole number, then if you divide, for example, 10 by 20, then your program is just going to give you back 0 because 0.5 is not an integer (so it rounds down).
What primitive data type would you use to account for any decimals?
Answer: Double

Rounding int to 1 decimal place?

So in the following set of code I don't understand why "%.1f" will not round y to 1 decimal, I get the following when running the program:
123 F = Exception in thread "main"
java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
at java.util.Formatter.format(Formatter.java:2488)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Check03A.main(Check03A.java:17)
I also tried Math.round(y * 10) / 10 but it gives me for example 29.0 instead of 28.9
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Check03A
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
int y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y + " C");
}
}
The problem is here:
print.printf(x + " F = " + "%.1f", y + " C");
There are two arguments to this method:
x + " F = " + "%.1f" (the format string),
y + "C" (the argument)
Condensing the first argument, the statement becomes:
print.printf(x + "F = %.1f", y + "C");
The problem: y + "C". Why? Well, one argument of the + operator is a String; therefore, this + becomes a string concatenation operator and what the argument will ultimately be is String.valueOf(y) + "C".
But the format specification in the format string is%.1f, which expects a float or double, or their boxed equivalents. It does not know how to handle a String argument.
Hence the error.
There is also the problem that you are doing an integer division, but this is not the topic of this question. Provided that all numeric problems are solved, your printing statement will ultimately be:
print.printf("%.1f F = %.1f C", x, y);
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
//change it
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y).print(" C");
}
Make y as float if you want to use %f
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y ).print("C");

Categories

Resources