Unexpected java charAt output - java

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.

Related

How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?

public String getIDdigits()
{
String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
return idDigits;
}
In this simple method, where IDnum is a 13 digit string consisting of numbers and is a class variable, the given output is never what I expect. For an ID number such as 1234567891234, I would expect to see 14 in the output, but The output is always a three-digit number such as 101. No matter what ID number I use, it always is a 3 digit number starting with 10. I thought the use of empty quotation marks would avoid the issue of taking the Ascii values, but I seem to still be going wrong. Please can someone explain how charAt() works in this sense?
You are taking a char type from a String and then using the + operator, which in this case behaves by adding the ASCII numerical values together.
For example, taking the char '1', and then the char '4' in your code
IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)
The compiler is interpreting this as its ASCII decimal equivalents and adding those
49 + 52 = 101
Thats where your 3 digit number comes from.
Eradicate this with converting them back to string before concatenating them...
String.valueOf(<char>);
or
"" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)
Try this.
public String getIDdigits()
{
String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
return idDigits;
}
When you first adding a empty it's add char like String if you put it in end it first add in number mode(ASCII) and then convert will converts that to String.
You have to be more explicit about the string concatenation and so solve your statement like this :
String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
The result of adding Java chars, shorts, or bytes is an int:

How should I represent a single unicode character in Java?

I would like to represent a single Unicode character in Java. Which primitive or class that is appropriate for this?
Note that I want to be able to store any unicode character, which may be too large for a 2 byte char.
char is indeed 16-bit, a char corresponds to a UTF-16 code unit. Characters that don't fit in a single UTF-16 code unit (Emojis, for instance) require two chars.
If you need to store them individually for some reason, you can use an int for that. It has sufficient room (and then some) for all of the 0x10FFFF code points currently allowed in Unicode. That's what the JDK uses, for instance in Character.codePointAt(CharSequence seq, int index) and String(int[] codePoints, int offset, int count).
Gratuitous conversion example (live on ideone):
String s = "πŸ˜‚";
int emoji = Character.codePointAt(s, 0);
String unumber = "U+" + Integer.toHexString(emoji).toUpperCase();
System.out.println(s + " is code point " + unumber);
String s2 = new String(new int[] { emoji }, 0, 1);
System.out.println("Code point " + unumber + " converted back to string: " + s2);
System.out.println("Successful round-trip? " + s.equals(s2));
which outputs:
πŸ˜‚ is code point U+1F602
Code point U+1F602 converted back to string: πŸ˜‚
Successful round-trip? true
Depends on the definition of a character:
If you mean one single Unicode code point, use int, which can hold every value from U+0000 to U+1FFFFF.
However, in some cases what appears as one character occupies multiple code points. This is especially common with emoji, eg.
skin tone: πŸ™‹πŸ» πŸ™‹πŸΏ
country flags: πŸ‡―πŸ‡΅ πŸ‡ΊπŸ‡Έ
families: πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦, which becomes "πŸ‘¨+πŸ‘©+πŸ‘§+πŸ‘¦" if I replace the zero-width joiners (U+200D) with plus signs.
To store those the most logic way is using a String.

How can a string accept an integer?

Can a variable String accept integer value as well. Or can we concat integer with a string ?
Example:
public class TestString1 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}
I was expecting compilation error over here because String was getting concatenated with an integer.
JLS documentation on String concatination operator(+)-
15.18.1 String Concatenation Operator +
If only one operand expression is of type String, then string
conversion is performed on the other operand to produce a string at
run time. The result is a reference to a String object (newly created,
unless the expression is a compile-time constant expression
(Β§15.28))that is the concatenation of the two operand strings. The
characters of the left-hand operand precede the characters of the
right-hand operand in the newly created string. If an operand of type
String is null, then the string "null" is used instead of that operand
That is why String + int does not produce any error. And it prints 42042
None of the other answers have explained what's actually being executed here.
Your code will be converted to something like:
String str = "420";
// str += 42;
StringBuilder sb = new StringBuilder(str);
sb.append(42); // which internally does something similar to String.valueOf()
str = sb.toString();
System.out.print(str);
Anything that is given in double quotes is String and + is for concatenating string with an any value(int value).
So the integer value will be appended to the string.
Here
String str = "420";
str += 42; // 42 will be appended to 420 and result will be 42042
Adding an int to a String appends the int to the string, thus converting the int into a string.
x=20 y=10
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.

printing an int value right after a String value

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

How to print extended value ascii for a string in java?

I have requirement where i have to print ascii value for a string, when i try printing the values its printing unexpected value,my program looks like below
int s=1161;
String hex=Integer.toHexString(1161);
hex="0"+hex;
char firstByte = (char) (Integer.parseInt(hex.substring(0,2),16));
char secondByte = (char) (Integer.parseInt(hex.substring(2,4),16));
and the output if the program is
first byte-- some rectangle shape
second byte--?
where i'm expecting the ascii code are
first byte-- EOT
second byte--‰
can some one help me how can i achieve this?
You intend to do tbe following in a somewhat convoluted way:
String hex = String.format("%04x", s); // delivering 0489
The first byte is 0x04 = 4, an ASCII control char, Ctrl-D, or EOT.
The second byte is 89, is actually out of the 7bit ASCII range. Depending on the encoding that might be the promil sign, but in Unicode would be the Unicode control character for a tab with justification.
You should try following code...
int s = 1161;
String hex = Integer.toHexString(s);
// hex="0"+hex;
char firstByte = (char) (Integer.parseInt(hex.substring(0, 2), 16));
char secondByte = (char) (Integer.parseInt(hex.substring(2, 3), 16));
System.out.println("First = " + firstByte + ", Second = " + secondByte + ", Hex " + hex);
output
First = H, Second = , Hex 489
Test your functions with more reliable input. Control characters like EOT may be represented by squares or any other kind of placeholder. Anything above 127 is not uniquely defined in ascii, so it might just show up as "?". Seems to me your function works correctly.
See also http://en.wikipedia.org/wiki/Ascii for all well defined ascii symbols.

Categories