and thank you for your time,
For the following code (a method for a class), I am not sure what the (char) is supposed to do. B arg 1 has a char and at the end I also get a char.
So, does the (char) work like a cast or? If it's more commonly used I would like to learn more about it, so I would appreciate if you could tell me where to look specifically.
static B calculer(B arg1, int arg2) {
arg1.b = (char)(arg1.b + arg2);
}
Java characters are numbers behind the scenes where the character actually holds the Unicode codepoint. The Java char is an unsigned 16-bit number (UTF-16). So you can treat them like numbers in many ways. What this does is add arg2 to the Unicode value of arg.b.
For example if arg.b is 'a' (codepoint is decimal 97) and arg1 is 10 on return of the method arg.b will now be 'k' (codepoint is decimal 107).
Because Java promotes data types during numerical operations, after adding an int to a char the result of the expression is an int not a char. The char gets promoted to an int. So the cast is needed to turn the result back in to a char for the assignment.
It casts (arg1.b + arg2) to a char.
When there are multiple data types that can be interpreted, you cast it to the one you want.
For instance, if I was to try to display the number 97 as a char instead of just the int 97 that it would normally be interpreted as, I would cast is as such:
System.out.println( (char)97 ); // will display 'a', instead of 97
I could display a as 97 by casting it to an int as well.
In your case, it will interpret (arg1.b + arg2) as a char, instead of what it normally would be.
Example:
I wrote this code (where 'a' represents arg1.b and 5 represents arg2:
char x = (char)('a' + 5);
System.out.println(x); // displayed 'f'
It displayed 'f' because it added 'a' and 5 together, which it interpreted as 97 + 5 (97 is the ASCHII value of 'a', or the int value of it essentially), and then would be left with (char)(102) which would then be interpreted as 'f' (the char value of 102).
it's called casting. What casting does is transforms some other data type (like int) into a character. I think this is Java code? So you want to learn a little bit more about java characters and the way it handles this kind of situations.
Related
This question already has answers here:
Java: Subtract '0' from char to get an int... why does this work?
(10 answers)
How does subtracting the character '0' from a char change it into an int?
(4 answers)
Closed 8 years ago.
I’m learning Java through "introduction to Java programming 9th edition" by Daniel Liang at chapter 9 "strings" I’ve encountered this piece of code :
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F')
return 10 + ch - 'A';
else
return ch - '0';
}
Can someone explain what just happened in here? How is possible to add/subtract chars from integers and what's the meaning behind it?
From the Docs
The char data type is a single 16-bit Unicode character.
A char is represented by its code point value:
min '\u0000' (or 0)
max: '\uffff' (or 65,535)
You can see all of the English alphabetic code points on an ASCII table.
Note that 0 == \u0000 and 65,535 == \uffff, as well as everything in between. They are corresponding values.
A char is actually just stored as a number (its code point value). We have syntax to represent characters like char c = 'A';, but it's equivalent to char c = 65; and 'A' == 65 is true.
So in your code, the chars are being represented by their decimal values to do arithmetic (whole numbers from 0 to 65,535).
For example, the char 'A' is represented by its code point 65 (decimal value in ASCII table):
System.out.print('A'); // prints A
System.out.print((int)('A')); // prints 65 because you casted it to an int
As a note, a short is a 16-bit signed integer, so even though a char is also 16-bits, the maximum integer value of a char (65,535) exceeds the maximum integer value of a short (32,767). Therefore, a cast to (short) from a char cannot always work. And the minimum integer value of a char is 0, whereas the minimum integer value of a short is -32,768.
For your code, let's say that the char was 'D'. Note that 'D' == 68 since its code point is 68.
return 10 + ch - 'A';
This returns 10 + 68 - 65, so it will return 13.
Now let's say the char was 'Q' == 81.
if (ch >= 'A' && ch <= 'F')
This is false since 'Q' > 'F' (81 > 70), so it would go into the else block and execute:
return ch - '0';
This returns 81 - 48 so it will return 33.
Your function returns an int type, but if it were to instead return a char or have the int casted to a char afterward, then the value 33 returned would represent the '!' character, since 33 is its code point value. Look up the character in ASCII table or Unicode table to verify that '!' == 33 (compare decimal values).
This is because char is a primitive type which can be used as a numerical value. Every character in a string is encoded as a specific number (not entirely true in all cases, but good enough for a basic understanding of the matter) and Java allows you to use chars in such a way.
It probably allows this mostly for historical reasons, this is how it worked in C and they probably motivated it with "performance" or something like that.
If you think it's weird then don't worry, I think so too
The other answer is incorrect actually. ASCII is a specific encoding (an encoding is some specification that says "1 = A, 2 = B, ... , 255 = Space") and that is not the one used in Java. A Java char is two bytes wide and is interpreted through the unicode character encoding.
Chars are in turn stored as integers(ASCII value) so that you can perform add and sub on integers which will return ASCII value of a char
Regardless of how Java actually stores the char datatype, what's certain is this, the character 'A' subtracted from the character 'A' would be represented as the null character, \0. In memory, this means every bit is 0. The size in memory a char takes up in memory may vary from language to language, but as far as I know, the null character is the same in all the languages, every bit is equal to 0.
As an int value, a piece of memory with every bit equal to 0 represents the integer value of 0.
And as it turns out, when you do "character math", subtracting any alphabetical character from any other alphabetical character (of the same case) results in bits being flipped in such a way that, if you were to interpret them as an int, would represent the distance between these characters. Additionally, subtracting the char '0' from any other numeric char will result in int value of the char you subtracted from, for basically the same reason.
'A' - 'A' = '\0'
'a' - 'a' = '\0'
'0' - '0' = '\0'
I have to say that this was found by a mistake, as I was trying to convert a String to an Integer, but I didn't realize that it is a Character type instead of Integer.
But somehow, the Integer.valueOf can still run with a Character parameter although this was not mentioned in JDK documentation?
System.out.println(Integer.valueOf("2")); // >>> 2
System.out.println(Integer.valueOf('2')); // >>> 50
While it works fine for String argument of "2", it doesn't provide the expected result for Character argument of '2'. Why does this happen?
I am trying to understand if I miss anything? Why does it return 50 instead of 2?
Thanks
OK, I checked the ASCII table, it is returning 50 because the index for Character '2' is 50.
The ASCII representation should give you a clue about why you are getting this behaviour.
Remember that the Integer and Character classes are wrappers for the int and char primitive types. The reason why Integer.valueOf() works with a Character is that there is an implicit cast to Integer. When you cast a Character to Integer, the Integer will hold the ASCII code for that Character. The same thing happens with primitive types. For example
Character yourChar = new Character('2');
Integer yourInt = Integer.valueOf(yourChar); //Implicit casting
char biz = '2';
int baz = (int)biz; //Explicit casting to int
System.out.println(baz);
System.out.println(yourInt);
Here, the value of both yourInt and baz will be 50, because that is the ASCII code for '2'. The implicit and explicit casting do the same thing.
If you actually want to convert a char which holds a digit to the correct integer, use Character.getNumericValue(). E.g.
char myChar = '2';
int myInt = Character.getNumericValue(myChar);
Now myInt holds the value 2.
As far as best-practices go, using this type of implicit conversion isn't a good idea. It doesn't make it obvious what you are trying to do.
Integer.valueOf(char)) gives the ASCII value.
Integer.valueOf('2'); // >>> 50
If you want to get numeric value then,
Character.getNumericValue('2')); // >>> 2
public class MyClass
{
public static void main(String args[])
{
String a = "(4 + 4i)";
String b = "(2 + 3i)";
int g = 1;
int c = a.charAt( g ); // sets c to 52
System.out.println( c ); // prints 52
System.out.println( (double) a.charAt( g ) ); // prints 52.0
System.out.println( a.charAt( g ) ); // prints 4
System.out.println( 2 * a.charAt( g ) ); // prints 104
}
}
I was trying to write code to multiply imaginary numbers which is why I have "i" in the strings. So I thought take first and and convert to int or double. This gave me 52 which baffled me. However when I printed directly to console, it worked but only without the double. This is useless because I need to use it elsewhere. So what is going on here? Would it better to try to parse parts of strings a and to int or double and are there alternatives to manipulating numbers within strings without using parse? And are there methods that can deal with imaginary numbers i.e. "e^pi * i = 1"?
A String is a sequence of symbols, such as letters, punctuation, and digits, called characters. Each character is associated with a number. One common way to do this is with what is called the ASCII characters. In this case, you see that the character '4' is represented by the number 52.
With this in mind, let's look at some of your code:
int c = a.charAt( g );
This line silently converts the character to its numerical value. By "numerical value" I mean the number that represents the character, not the value of the digit itself. In this case, the character '4' has the numerical value 52.
System.out.println( a.charAt( g ) ); // prints 4
This prints out the character '4', not the int 4. It is extremely important that you learn the difference between the digit characters and their integer values.
In order to get the number 4 so that you can perform arithmetic operations, you must parse the String. The function Integer.valueOf() will help a lot with this.
You should also learn about classes and objects. For example, you can create a Complex class which will allow you to use complex numbers as a single entity with its own operations.
To get the numerical values that you want, you need to use Integer.valueOf() or Double.valueOf() depending on whether you want an int or a double:
int c = Integer.valueOf(a.charAt(g))
You will need to use more sophisticated parsing methods if you want to allow numbers with multiple digits or decimal points.
You get 52 because the ascii value of '4' is 52.
System.out.println("(4 + 4i)".charAt(1) == '4'); // '4' == '4'
System.out.println((int) '4'); // <-- 52
If you want to convert a char to its' int value, you need to check that it is in the expected range and then parse it. You can subtract '0' from the value, or use Character.digit - like
char c = '4';
if (c >= '0' && c <= '9') {
System.out.println((int) (c - '0'));
System.out.println(Character.digit(c, 10));
}
And, finally, System#out is a PrintStream, that is what provides the overloaded methods to write int (or char, or String, or double, etc).
Can some one explain what runner.children[c-'a']
means in the following code.
public boolean search(String word) {
TrieNode runner = root;
for(char c : word.toCharArray()) {
if(runner.children[c-'a'] == null) {
return false;
} else {
runner = runner.children[c-'a'];
}
}
return runner.isEndOfWord;
}
Every char has a numeric value, check out the ASCII table for more information.
So assume that the variable c contains character b, and subtract character a from that, you will get 1 for your answer.
That's just subtraction. You can subtract characters as though they were numbers. You end up with the result of subtracting their character codes. 'c' - 'a' (for example) equals 2, since 'a' is 2 less than 'c'.
- is the subtraction operator.
§15.18.2 The type of each of the operands of the binary - operator must be a type that is convertible to a primitive numeric type
§5.6.2 Widening primitive conversion is applied to convert either or both operands … both operands are converted to type int.
Binary numeric promotion is performed on the operands of certain operators: … addition and subtraction operators for numeric types + and - …
In other words, both c and 'a' are of type char (a UTF-16 code unit, which has a range from Character.MIN_VALUE to Character.MAX_VALUE). Due to subtraction, they are widened to type int, subtracted, resulting in a value of type int.
Think of characters on a number line. Subtraction is the distance from one character to the other. With a constant reference to 'a', the distances for 'a', 'b', … 'z' are 0, 1, … 25. This makes sense only over certain short segments of the UTF-16 number line.
Arrays are 0-based so shifting the scale like this allows characters to be used to index an array without having a large used portion with elements corresponding to unused characters.
(Note: Some people are saying ASCII because they think it's easier to understand a simpler, wrong thing on the way to learning the right thing. 🤷)
In this case children[] is probably the size of the amount of letters from a-z.
What is going on above is that they take the ascii value of the char c, and subtracting the ascii code of 'a'. Effectively resulting in getting the index of the char c in the alphabet (0-Index assumed)
Let c = 'b'
[c-'a'] = 98 - 97 = 1 (Ascii of b - Ascii of a)
With c = 'd'
[c-'a'] = 100 - 97 = 3
It is minus sign and not hyphen. In java char takes 2 bytes of space. char is representation of bits ranging from 00000000 to 11111111, most significant bit is read as signed bit. You can easily read it as a number also by assiging a char to an int variable ( as int can accept 4 bytes so 2 bytes of char can easily fit ).
char charA = ''A'; // represents 65
char charB = `B`; // represents 66
int diff = charB - charA; // this will represent 66-65 i.e. 1
Index of the array is positve int and hence it can also accept values like
anyTypeArray[charB - charA] //represents the 2nd element (index starts from 0 for arrays in java).
anyTypeArray['C' - charA] // represents the 3rd element of the array
Also I liked answer above https://stackoverflow.com/a/47106997/504133 and would like to add its link to extend my answer.
This question is hard to be asked on Google even though is so simple.
Basically I wrote this :
public static void main(String[] args) {
char cipher[] = {'a','b','c','c','d','t','w'};
System.out.println(cipher[0]+cipher[2]);
}
}
and the println result was : 196 instead of ac. Of course when I did
System.out.println(cipher[0]+""+cipher[2]);
It showed me ac as intended.
So my question is just what is this 196 ?
Thanks!
So my question is just what is this 196 ?
It's the UTF-16 code unit for 'a' (which is 97) followed by the UTF-16 code unit for 'c' (which is 99).
Other than for string concatenation, operands of the addition operator undergo binary numeric promotion (JLS 5.6.2) so you're actually performing addition of int values. Your code is equivalent to:
System.out.println((int) cipher[0] + (int) cipher[2]);
196 is the ASCII value of 'a' + the ASCII value of 'c'.
When you add chars together, without any other hints, Java interprets them as numbers.
In Java, a char is essentially an unsigned 16-bit integer with their integer value corresponding to their Unicode value. 196 is the sum of the integer representations of 'a' ja 'c'.
The result 196 is the ASCII value de 'a' (ASCII 97) + 'c' (ASCII 99).