I'm moving from C to Java now and I was following some tutorials regarding Strings. At one point in the tutorials they showed instantiating a new string from a character array then printing the string. I was following along, but I wanted to print both the character array and the string so I tried this:
class Whatever {
public static void main(String args[]) {
char[] hello = { 'h', 'e', 'l', 'l', 'o', '.'};
String hello_str = new String(hello);
System.out.println(hello + " " + hello_str);
}
}
My output was something like this:
[C#9304b1 hello.
Clearly, this is not how you would print a character array in Java. However I'm wondering if I just got garbage? I read on some site that printing a character array give you an address, but that doesn't look like an address to me... I haven't found a lot online about it.
So, what did I just print?
and bonus questions:
How do you correctly print a character array in java?
However I'm wondering if I just got garbage?
No, you got the result of Object.toString(), which isn't overridden in arrays:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
So it's not garbage, in that it has a meaning... but it's not a particularly useful value, either.
And your bonus question...
How do you correctly print a character array in java?
Call Arrays.toString(char[]) to convert it to a string... or just
System.out.println(hello);
which will call println(char[]) instead, which converts it into a string. Note that Arrays.toString will build a string which is obviously an array of characters, whereas System.out.println(hello) is broadly equivalent to System.out.println(new String(hello))
Related
String name = "Jack";
char letter = name.charAt(0);
System.out.println(letter);
You know this is a java method charAt that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
You can use String.operator[].
String name = "Jack";
String letter = name[0];
print(letter);
Note that this operates on UTF-16 code units, not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a char type, so you'll end up with another String.
If you need to operate on arbitrary Unicode strings, then you should use package:characters and do:
String name = "Jack";
Characters letter = name.characters.characterAt(0);
print(letter);
Dart has two operations that match the Java behavior, because Java prints integers of the type char specially.
Dart has String.codeUnitAt, which does the same as Java's charAt: Returns an integer representing the UTF-16 code unit at that position in the string.
If you print that in Dart, or add it to a StringBuffer, it's just an integer, so print("Jack".codeUnitAt(0)) prints 74.
The other operations is String.operator[], which returns a single-code-unit String. So print("Jack"[0]) prints J.
Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use String.runes to get code points or String.characters from package characters to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)
You can use
String.substring(int startIndex, [ int endIndex ])
Example --
void main(){
String s = "hello";
print(s.substring(1, 2));
}
Output
e
Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.
I have a char array that wrote in a file without any converting. the printed value to my file is [C#252ccf04 now I'm reading the file and this thing is being read as a string. now the retrieved data is [C#252ccf04 but this time it's a string. my problem is I want to assign it to another char array so I can read it using the Arrays.toString() method to reach the original value which is 123456 how can I accomplish that?
char[] pass = (data.substring(data.lastIndexOf(',') + 1).replaceAll(" ", "")).toCharArray();
System.out.println(Arrays.toString(pass));
// now the is: [[, C, #, 2, 5, 2, c, c, f, 0, 4]
and also I want to know what is this value what should I call it, is this a hashcode?
The value is the hashcode(as hex) plus the name of the class. According to the default toString() implementation:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You can't convert it back to the original character array. The hash code identifies the object while it is alive in memory. Once the program ends and the object dies, you can't get it back from the hashcode.
You should have saved the actual data as a String, or encrypted it yourself.
At school we were looking at a code for removing a character from a string.
I have a problem understanding the for loop in this code.
What happens if word.charAt(i) is equal to c? If word.charAt(i) is not equal to c the character is printed out. (words.charAt(i) gets printed out)
But if it is equal to c, where in the code does the character get removed?
Thank you in advance for your help. And I'm sorry for my bad English.
This is the code our teacher gave us:
String removeChar(String word, char c) {
String result = "";
for (int i = 0; i<word.length();i++) {
if (word.charAt(i) !=c) {
result += word.charAt(i);
}
}
return result;
}
You can read this code like:
Create an empty String result.
For each letter from word, check if it is not 'c' character. Only if it is not 'c', append this letter to result String (add this letter at the end of result String). If currently checked character is equal to 'c', do nothing.
When loop reaches the end of word, return result String.
By the way, appending String in a loop using += operator is not that efficient like using class StringBuilder and its append() method.
The char is not really removed;
it's simply not append (result += word.charAt(i)) into the string result.
In this way the string that is returned by the method is formed only by the chars that are different from char c.
This code just creates new String object (see variable result). At end of function this new string contains only characters which do not equal to c. Next it string returns as result of function.
Java strings is not mutable, so this is only way to "modify" string - create brand new string.
Character is not actually removed its just been appended to the empty new string(String result = "";) which you have declared above,when word doesn't contain the character 'c', then those characters are getting appended to result, finally you are retrieving that 'Result' string not 'Word',it still containing same value which you have sent.
the original question is like this.
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3' + "";
System.out.println(i);
}
}
and this gives me an error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
then I changed the code like this:
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3';
System.out.println(i);
}
}
the out put is 150.
but when I write my code like this:
public class test {
public static void main(String[] args){
System.out.println('a'+'b'+'c'+"");
}
}
the output become 294.
I wonder why.
The first one does not compile, because you concatenate a String at the end which cause the value to be a String which can't be converted directly to int.
The output of the second one is 150, because ASCII value for character 1,2,3 are 49,50,51 which return 150 when doing the addition.
The output of the last one is 294, because you are doing an addition of char values in the ASCII table (97+98+99)
You can verify the values here for a,b and c (or any other character).
Edit : To explain why the last one output the correct value instead of throwing an error, you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a String which is why it does not throw any error.
The first one would work if you would do Integer.parseInt('1' + '2' + '3' + "");
When you do this
int i = '1' + '2' + '3';
the JVM sums the ASCII codes of the given numbers. The result is 150.
When you add the empty String, you are trying to sum an int/char with a String. This is not possible. You can implicitly convert char to int and vice versa because they are primitive types. You cannot do this with String objects because they are not primitives but references. That's why you get an error.
When you do the println the primitive values are firstly summed and the automatically boxed into reference type so the sum is boxed into a Character object. The empty String is converted to a Character and then is added to the first one. So the result is a Character object that has an ASCII code 294. Then the toString method of the Character is called because that's what the println(Object) method does. And the result is 294
I hope this will help you to understand what is happening :)
The first is impossible because you can't convert String to int this way.
The second works because chars are kind of numbers, so adding chars is adding the numbers they really are. Char '1' is the number 49 (see ASCII table), so the sum is 49+50+51 which is 150.
The third works this way because + is a left parenthesized operator, which means that 'a'+'b'+'c'+"" should be read as (('a'+'b')+'c')+"". 'a' has ASCII code 97, so you have 294+"". Then Java knows that is should convert the value to a String to be able to catenate the two strings. At the end you have the the string 294. Modify your last code to the following System.out.println('a'+'b'+('c'+"")); and you will see that the result will be 195c.
You must note that System.out.println is a method that is used to convert values (of different types) to their String representation. This is always possible as every int can be converted to a String representation of it, but not the converse; not every String is a representation of an int (so Java will not let you do it so simply).
First: [int i = '1' + '2' + '3' + "";]
If you concat an empty string value, you convert it to a String object, and then String objects can't convert to int.
Second: [int i = '1' + '2' + '3';]
The binary arithmetic operations on char promote to int. It's equal to:
[int i = 49 + 50 + 51] - total: 150.
Third: [System.out.println('a'+'b'+'c'+"");]
At this case you convert 'a' + 'b' + 'c' (that is 294) to String (+"") and then print the result like a String value and that works ok.
For the code
int []arr = new int[4];
System.out.println(arr);
The output looks something like
[I#54640b25
What exactly is the compiler printing out? The memory address of arr? Unlike C, Java does not seem to equate the array name (in isolation) with the first position of the array.
In Java, each object has toString() method, and arrays are objects. The default is displaying the class name representation, then adding "#" and then the hashcode:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object
Try to print the following line and you should get the same output:
int[] arr = new int[5];
System.out.println(arr.getClass().getName() + "#" + Integer.toHexString(arr.hashCode()));
Use the following in order to print the value of array:
Arrays.toString(arr);
Using System.out.println(arr) directory will print use the default toString method which returns:
object.getClass().getName() + "#" + Integer.toHexString(object.hashCode())