String to Char Array and Char array to String Conversion - java

In my program I am getting a string from Database result set and convert it to char array like this:
emp.nid = rs.getString("nid").toCharArray();
In this part there is no error. The String is successfully converted to char array.
But I have another code like this:
nid_txt.setText(emp.nid.toString());
This prints some freaky text. Not the original. Why was this happens? Please help me.

You're calling toString on a char[] - and that inherits the implementation from Object, so you get the char[].class name, # and then the hash of the object. Instead, call the String(char[]) constructor:
nid_txt.setText(new String(emp.nid));

This happens because the toString() method is the String representation of the object, and not the String of what it contains.
Try doing like this:
nid_txt.setText(new String(emp.nid));

instead of foo.toString() do new String(foo).

You are calling the toString() on the array object. Try:
new String(emp.nid);
and you should see better results.

assuming that emp.nid is byte array second sentence is completely wrong. toString() method in such object won't work. Try insted creating new String based on byte array:
String s = new String(emp.nid);
nid_txt.setText(s);

Related

String literal with toCharArray() producing garbage in Java

I wanted to create a char array of the alphabet. I looked at this post:
Better way to generate array of all letters in the alphabet
which said this:
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
So in my code I have:
public class Alphabet {
private char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public String availableLetters(){
return letters.toString();
}
}
When I call the function availableLetters() from main() and printit to the console, it outputs this garbage:
[C#15db9742
What am I doing wrong?
The array is correct, the problem is that you are not printing it correctly.
If you print your array one character at a time, you would get a correct result:
for (char c : letters) {
System.out.print("'" + c + "' ");
}
demo
Unfortunately, Java standard class library does not provide a meaningful override of toString() for arrays, causing a lot of trouble for programmers who are new to the language.
If you want to print it in array form, then use:
System.out.println(Arrays.toString(letters));
BTW: The [C#15db9742 is not really garbage. It's what gets printed out when a class does not override the toString() method.
From Object.toString():
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method. 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())
You can pass the char array to the String constructor or the static method String.valueOf() and return that instead.

Java toString method in char[] [duplicate]

This question already has answers here:
Why does the toString method in java not seem to work for an array
(9 answers)
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
I thought the toString method will make a char array to a String, but I was wrong.
char[] k=new char[2];
k[0]='k';
k[1]='k';
System.out.println(k.toString());
This code will output: [C#112f614.
What exactly happened in this code k.toString()?
Should I never call toString method in a char array?
Thanks!
Happy New Year!
You want to use Arrays.toString(char[]{'a','b'});
You can use
char data[] = {'a', 'b', 'c'};
String str = new String(data);
See the javadoc
public String(char[] value)
Allocates a new String so that it
represents the sequence of characters currently contained in the
character array argument. The contents of the character array are
copied; subsequent modification of the character array does not affect
the newly created string. Parameters: value - The initial value of the
string
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Calling toString on an array will call the toString method from Object. Which will return you the hashCode
public String toString() Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method. 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())
Returns: a string representation of the object.
Because arrays are objects. So calling toString() result to call the toString() method herited from the object class which is :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
In [C#112f614, [C means that it's an array of char.
If you want to print the content of your array, use Arrays.toString(char[] a)
What exactly happened in this code k.toString()? Should I never call toString method in a char array?
The toString method of a char array inherits the default toString behavior from Object, which is to simply print a unique identifier derived from the object's location in memory. So unless you want that unique identifier, there's not much point in calling k.toString(). (k being your char array)
You should likely never call toString on any sort of array. The Arrays class has many utility methods for creating string representations of arrays.
A partial answer to this question: "What exactly happened in this code k.toString()?"
toString() is inherited from java.lang.Object and not overridden. The implementation just print the canonical class name plus the #-letter plus the hashcode. That is all. Therefore calling this methode is not useful for applications and is just for debugging purposes in IDEs to at least enlighten which type of object is there.
String can take a char array as a constructor.
String s = new String(k);

different Methods call in java

I'm new to java language I confused about different between these 2 methods calls (I don't know exactly it is method call or not)
but if i need to call method to calculate something I call this
salary obj=new salary();
obj.bonus(45000);
but when we call String length method we call this as
String name="Java lovely";
name.length();
What are the different of these 2 methods .Please help me to overcome this problem.
Thank you
String name="Java lovely";
You might confused with the string literal.
String is special in java
You will clear if I wrote
String s = new String("Java Lovely");
s.lenght();
String is a class. String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "Java lovely";
is equivalent to:
char data[] = {'J', 'a', 'v', 'a', ' ', 'l','o', 'v', 'e','l', 'y'};
String str = new String(data);
length is a method of String Class.
in upper part that is
salary obj=new salary();
obj.bonus(45000);
in this salary is a class and you created object of this 'obj' and bonus is a method that you defined in salary class and you are calling that method
and other is
String name="Java lovely";
name.length();
is here same
String name=new String("Java lovely");
and you are calling length method on String object 'name'.
both are same but one difference is String is constant(immutable) mean once you created it, you can't change it but your salary class is not constant,you can change it.
To understand java better u can read this book. Head first Java
It is exactly same. Both obj and name are instance of their class. BUt String is exceptional class in java.. It can be create like above without new keyword.
it's the same, as String is a ready included java class.
you can make :
String name = new String("dsdsd");
it seems like
String name = new String();
name = "dsdsd";
name.length();
What do you men by difference?
That the first call has something between the () ? And name.length not? That is because the method bonus is an method with parameters. It expects an value, at this case an integer or int to do something with this. but Name.length doesnt mean any values, it just returns the saved length of the string.
Or where else you see a difference?
obj.bonus(number); and
name.length ();
is actually the same...
Sry if this wasnt your question.
Edit: or do you mean the constructor? This is because string is special in java, actually new String("lalala"); is right.
salary obj=new salary(); // You are initializing salary class
obj.bonus(45000); // Your salary class contains bonus method and it takes
int argument
So you are call bonus method and parse 45000 to that.
String name="Java lovely"; // You are define a String
name.length(); // this will return the length of name String, no need input
argument and return int length

How to find character array length in Android

I had used the following code to find the length
String str=strLenData.toString();
int ipLen= str.length();
return ipLen;
ipLen would return 11 every time. whatever be the actual value of strLenData. when I call toString() function, value of str: "[C#40523f80". Now I have to use char[] and i need to know the end (or length) of char[].
How do I do it?
If I understand correctly the strLenData variable is a char[]? In that case, you can just do
return strLenData.length;.
I don't think strLenData is charSequence or something. its just a regular object and may be it does't have toString() method. so toString() method of Object class gets called which just returns the HashCode value of The Objects Reference.
so make sure strLenData.toString() can be used.
ipLen is returning 11 always because you are converting an char array to String equivalent by using toString() method.
if you want to create String by an char array use.
String str = new String(strLenData);
Or if you want just want to get length of your char array use answer given by Steven.
use strLenData.length;

Increment last letter of a string

Here's where I wish Java's String class had a replaceLast method, bu it doesn't and I'm getting the wrong results with my code.
I'm writing a program that searches a data structure for any items that match a string prefix. However, since I'm using an Iterator, the last item returned by the iter.next() call doesn't match the pattern, so I want to change the search string so that the last character of the query is increased by one letter. My testing code is returning [C#b82368 with this code and An as titleSearch:
public String changeLastCharacter(String titleSearch) {
char[] temp= titleSearch.toCharArray();
char lastLetter= temp[temp.length-1];
lastLetter++;
temp[temp.length-1]= lastLetter;
String newTitleSearch= temp.toString();
return newTitleSearch;
}
First, what is the cause of the output from this code?
Second, is there a better way to execute my solution?
You want:
newTitleSearch = new String(temp);
The toString method is not overridden for arrays; it's the usual Object.toString, intended for debugging. The above actually creates a string of the characters. An alternative is:
int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + new Character(titleSearch.charAt(len - 1) + 1);
Whenever you see unexpected output like ....#<hex-digits>, the chances are that you are accidentally using toString() on some object whose class inherits the default implementation from Object.
The default toString() method returns a String whose value consists of the type name for the object combined with the object's "identity hash code" as hex digits. In your case the [C part is the type name for a char[] object. The '[' means "array of" and the 'C' means the char primitive type.
The rules for forming the type names used in the default toString() method are fully documented in the javadocs for java.lang.Class.getName().
Your problem is temp.toString(). Try String newTitleSearch = new String(temp); instead.
I figured this out by System.out.println(temp[0]+","+temp[1]); after temp[1] add been assigned to the incremented value. You could do this even easier by using your IDE's debugger.
Since the array was being assigned properly, the problem had to be in the toString().

Categories

Resources