Example:
System.out.println("the investment doubled after "+year+" years.");
Can someone please explain why the int variable year is inside quotations and pluses?
Adding some spacing around the operators may make this statement clearer:
System.out.println("the investment doubled after " + year + " years.");
This statement prints the result of a concatination of three strings, achieved by the two + operators:
"the investment doubled after "
The implicit conversion of the int variable year to a string
" years."
It is like this. And + is used for String concatenation. In this year is converted into String from int implicitly.
"the investment doubled after " + year + " years."
^-------inside quotes-------^ ^-----^Inside quotes
Your variable year is not inside quotes, it's actually outside of quotes. It is in between of + sign because you are concatenating it.
Here you are using the public void println(String x); method. Which means the integer will concatenated to the string when you append the years to the string, that is the reason we are using the + operator.
Related
required output:
Code: 123 Title: BookA Fees(SGD): $20.00
Loan Duration: 3 wks
return String.format("%-20s%-20s%\n", "Code: " + code, "Title: " + title, "%.2f\nFees(SGD): $" + fees, "Lesson Duration: " + lessonDuration + "wks");
it only returns only the first 3 (code, title, fees) but not loan duration. also where do i put in %.2f for fees so that it will always be of 2 decimal place?
Your question asks about "Loan Duration", but your example code uses "Lesson Duration". That could be your problem.
That %.2f should work for setting two decimal places. How is it behaving?
When you use String.format, you usually just pass your variables in and use the correct percent signs for your variables' types. For instance, if you want to format an integer, you use %d: String.format("Here is an integer: %d", myInt). For strings, you use %s, and for doubles, you use %f (with .2 to indicate the number of decimal places as you've already found out. You put all of your formatting in the first string parameter. All you have to do then is this:
String code = "123";
String title = "BookA";
double fees = 20.943;
int lessonDuration = 3;
String str = String.format("Code: %s\nTitle: %s\nFees(SGD): $%.2f\nLesson Duration: %d wks",
code,
title,
fees,
lessonDuration);
You should go read this article here so you understand formatting in Java and don't fail your test.
The code is
String veggie = "eggplant";
int length = veggie.length();
char zeroeth = veggie.charAt(0);
char third = veggie.charAt(4);
String caps = veggie.toUpperCase();
System.out.println(veggie + " " + caps);
System.out.println(zeroeth + " " + third + " " + length);
System.out.println(zeroeth + third + length);
The output reads:
eggplant EGGPLANT
e 1 8
217
This doesn't make sense to me. Referencing a charAt outputs numbers instead of characters. I was expecting it to output the characters. What did I do wrong?
The second line should actually be:
e l 8
(note that the second value is a lower-case L, not a 1) which probably doesn't violate your expections. Although your variable is confusingly called third despite it being the fifth character in the string.
That just leaves the third line. The type of the expression
zeroeth + third + length
is int... you're performing an arithmetic addition. There's no implicit conversion to String involved, so instead, there's binary numeric promotion from each operand to int. It's effectively:
System.out.println((int) zeroeth + (int) third + (int) length);
It's summing the UTF-16 code units involved in 'e', 'l' and 8 (the length).
If you want string conversions to be involved, then you could use:
System.out.println(String.valueOf(zeroeth) + third + length);
Only the first addition needs to be a string concatenation... after that, it flows due to associativity. (i.e. x + y + z is (x + y) + z; if the type of x + y is String, then the second addition also becomes a string concatention.)
The compiler interprets all variables as values rather than a string.
Try System.out.println("" + zeroeth + third + length);
This line is doing integer arithmetic:
System.out.println(zeroeth + third + length);
In other words, it is adding the unicode values of each character (i.e. e is 101, l is 108, 8 is 8). To do String concatenation, you can add an empty String to the front:
System.out.println("" + zeroeth + third + length);
Since it is evaluated left-to-right, it will first do String concatenation (not addition). It will continue to do this for third and length. Adding "" at the end won't work, because addition will occur first.
You can use the method of the wrapper class Character to display the string values of char variables:
System.out.println(Character.toString(zeroeth) + Character.toString(third) + length);
This way, you always work with String values and there are no possibilities for the numeric values of the chars to be displayed or added and you don't need to concatenate with empty strings ("") to convert the char variables to String values.
This question already has answers here:
What is the precedence of the + (plus) operator in Java?
(4 answers)
Closed 9 years ago.
Why do i get 10 2030 as the out put? I cant figure out why it doesnt output it as 10 50 ?
public class Testing1 {
public static void main (String args[]){
int num1=10,num2=20,num3=30;
System.out.println(num1+" "+num2+num3);
}
}
Operator precedence
System.out.println(num1+" "+(num2+num3));
While evaluation expressions,
Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence.When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from **left to right**; assignment operators are evaluated right to left.
System.out.println(num1+" "+num2+num3);
--------------------10-----------------num1
--------------------10 -----------------num1+" "
--------------------10 20-----------------num1+" "+num2
--------------------10 2030-----------------num1+" "+num2+num3
So, now you come to know that why you got that output.
Let see how the below statement gives you desired output:
System.out.println(num1+" "+(num2+num3));
Again based on the precedence, parentheses have the high precedence than +. So
(num2+num3)
evaluates first and the rest is same.
This does not work because the expression is interpreted from left to right taking into account operator precedence
Walk through it.
System.out.println(num1+" "+num2+num3);
First you take your num1 and concat a space onto it, you now have "10".
Second you concat num2 onto that string, you have "10 20".
Third you concat num3 onto that, you have "10 2030".
In fact, what you are doing is this:
String s = num1 + " ";
s += num2;
s += num3;
Use this:
System.out.println(num1 + " " +(num2 + num3));
If you're writing (num1 + " " + num2 + num3) Java will make a String from num1 add the String " " to it, add the String made from num2 to it and then add the String made from num3 to it.
The plus first gets evaluated as String concatenation and not the math + sign.
make it System.out.println(num1+" "+ (num2+num3));
When you introduce any string when performing operations, then the concatenation happens instead of actual operation.
So if you do System.out.println(num1+num2+ " " +num3);. You will get the output as 30 30 This is because your operations are performed before string concatenation is introduced in it. and hence the operation result is produced.
Keep in mind that all operands will be treated as string AFTER the first concatenation has occurred.
Before the concatenation, all operations will be evaluated.
The reason for that output is that the + in this context (num1 + " " happens first) is treated as a concatenation operator and the rest is then concatenated too. The other answers suggest parentheses to ensure the num2 and num3 are added first before the string evaluation.
Beacause Precedence wise i.e left to right:
num1+" " will be evaluated making a string of 10
num2+num3 will simply be appended to that string because of + operator in-between
num1+" " and num2+num3 forming 10 2030
try this way
System.out.println(num1+" "+(num2+num3));
For more about precedence and their associativity : http://www.cis.upenn.edu/~palsetia/java/precedenceTable.html
I have the following example code:
int pay = 80;
int bonus = 65;
System.out.println(pay + bonus + " " + bonus + pay);
could someone please explain to me why I get the following output:
145 6580
Your code is interpreting the expression from left to right.
pay + bonus is interpreted as a mathematical function, so it adds the values to make 145. The + here is a plus operator.
The moment you concatenate the " ", Java converts the expression into a String. The + here is a concatenate operator.
Performing + pay converts pay to a String and concatenates it, because the expression is a String.
Also doing + bonus converts bonus to a String and concatenates it, also because of the previous expression.
Because, this is operator overloading issue. Here, First + is plus operator and last + is concat operator.
System.out.println(pay + bonus + " " + bonus + pay);
| |
(plus) (concat)
First it adds the two variables and at last it concatinates as string because the integers are converted into strings
For concatenation, imagine a and b are integers:
"" + a + b
This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) for concatenation
bonus and pay are both ints, and therefore going to be combined into a single int result.
You need to insert an empty string between them.
first is plus operator and last is concat operator
The 1st pay and bonus in the println returns an integer. So it computes pay+bonus and returns it as an integer before printing it out.
However, after the "". The + operation then becomes a concatenation of strings and everything after that is returned as a concatenated string. Hence, ("" + bonus + pay) would be returned as "6580".
before " ",pay and bonus as integer, added result is 145.
after " ",bonus and pay as String,result is "6580"
As the others are saying the compiler is first adding the integer values and then printing the result, after " " the total value is changed to String type and after that + operator is functioning as a concat action. To not get that output, you can do this:
System.out.println(String.valueOf(pay) + String.valueOf(bonus) + " " + String.valueOf(bonus) + String.valueOf(pay));
what is surrounded by " " is referred to as a 'literal print' and gets printed exactly. The "+" sign is the concatenator operator and concatenates the string with the value that is stored in the variables. pay and bonus are declared as int, but is automatically converted to a String for the purpose of printing out.
You can print an arithmetic expression within a System.out.print statement. Use parentheses around the arithmetic expression to avoid unexpected problems.
System.out.println("ex" + 3 + 4); // becomes answer 34
System.out.println("ex" + (3 + 4)); // becomes answer 7
I'm pretty new to Java programming and couldn't find an answer to my problem anywhere. Basically, I have successfully created a program that builds a chart of Celsius to Fahrenheit conversions and Fahrenheit to Celsius conversions, however my looped print statements are not lined up correctly after the number 9 similar this:
9.0 48.2 40.0 4.44
10.0 50.0 41.0 5.0
I was required to use two separate methods to calculate the conversions and then call them within the main method. Here is the main method with the println statement that I am reffering to:
public static void main(String[]args){
double celsius = 1;
double fahrenheit = 32;
while(celsius <= 50 && fahrenheit <= 120){
double toFarhenheit = celsiusToFahrenheit(celsius);
double toCelsius = fahrenheitToCelsius(fahrenheit);
DecimalFormat fardec = new DecimalFormat("#.##");
toFarhenheit = Double.valueOf(fardec.format(toFarhenheit));
DecimalFormat celsdec = new DecimalFormat("#.##");
toCelsius = Double.valueOf(celsdec.format(toCelsius));
System.out.println(celsius + " " + toFarhenheit + " " + fahrenheit +
" " +toCelsius);
celsius++;
fahrenheit++;
}
}
To make a long story short, is there anyway to use a printf with this kind of long print statement so that the numbers will line up with one another?
In the past I have used printf %3d and %5d and the like to line integers up, however, I couldn't get this to work at all with this particular print statement.
Any ideas and/or help would be much appreciated.
Use System.out.printf(...) and a format String to output your data in regular columns. Avoid using \t as it is unreliable. For example please look here.
Eventually your code would look like:
System.out.printf(formatString, celsius, toFarhenheit, fahrenheit, toCelsius);
Where the formatString is a String that uses printf format specifiers and width constants that would allow for pretty output. I'll let you experiment with format Strings. It would also end with "%n" so that it becomes in effect a println with formatting.
Adding to what Hovercraft Full Of Eels said, using System.out.printf without "\t" is a better solution.
For example, you should be able to do something like this:
String myformat = "%0$10s";
Explanation of the format:
%0s identifies your output as a string
$10 tells it to ensure that a minimum of 10 characters are written to the output. Hence, you'll have a fixed width.
See http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax for some more details
[haven't used java in a while so someone do correct me if I'm off]
Use \t to format them as this spaces them out evenly.
System.out.println(celsius + "\t" + toFarhenheit + "\t" + fahrenheit +
"\t" +toCelsius);
Using "\t" or using printf is probably not going to help you out as what ever space is being added takes into consideration the 2 string literals. For Eg. 9.0 is 3 chars long and 10.0 is 4 chars long.. so in this case spaces applied are correct but your string literals itself are of different length.
Try changing the code like below, use one more hash.
DecimalFormat fardec = new DecimalFormat("##.##");