I run this method:
String str=Character.valueOf(char).toString()
The output comes like a small square at console and just like a bar code in the file. What the actual format of the output is, also the output is not able to copy.
Character.valueOf(char) simply takes a char and returns a Character wrapper instance representing the same value. Using toString() on that returns a String containing only that single charcter.
So if your initial char value represents a printable character, then the result should be just as printable.
If, however, you use an arbitrary numeric value (especially, if you use 0, 1 or very high values) as your starting point, then the result will be a String containing a single Unicode character with that codepoint. That's unlikely to be a useful result.
In other words: crap in, crap out.
What is your actual input value and what do you expect to happen?
Try
String.valueOf(c);
.toString() offers a string representation of an object and that can be anything. What you want is not the string representation of the Character object. You want to convert/create a string from a char.
Related
I've seen in some java libraries when returning a string the value is concatenated with an empty value.
For example package java.io;
/**
* The system-dependent default name-separator character, represented as a
* string for convenience. This string contains a single character, namely
* <code>{#link #separatorChar}</code>.
*/
public static final String separator = "" + separatorChar;
Why not return only separatorChar?
Are strings the preferred datatype for return values? Give that this is only a char anyway why use a string datatype?
Are there any performance implications of doing this conversion?
One is a String, the other is char. It's useful to always be dealing with a String, rather than having to check if it's a char.
This is one of several ways of converting a char to a String. Although this used to be one of the slower ways of converting from char to String, as of java 6 update 20, with the introduction of -XX:+OptimizeStringConcat flag, concatenation is the fastest way to convert any value to string. As of Java 7, this option is turned on by default. So you're correct. There are performance implications. Here is a really great post which discusses this : https://stackoverflow.com/a/44485322/1028560.
Declaration of a character:
char ch = '';
When I do this i am getting the error 'empty character literal'.
Declaration of a String:
String str = "";
I see no error in doing that to a String.
The question is, why doesn't a similar error show up for the declaration of a String, or why declaration of empty character generating such error where empty string is getting passed
String is a set of chars and String str=""; contains no chars(read: empty string)
but if you want to have Char variable it must have some value. '' means no value.
String is a class in Java with its own syntax and methods. It accepts strings in double quotes. And a string is actually an Array of characters and is hence acceptable to be posted empty.
Char on the other hand is a data type and cannot be left undetermined. It needs to specified NULL.
I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.
Basically char is a thing you put in a box, and a string is a box to hold all those things. You can have an empty box but not a non-existant thing.
A string is an array of characters. By passing it nothing, i.e. making it equal to "" you basically make an empty array which is fine. But char is a primitive type hence it cannot be "empty". The closest you can get is setting it equal to '\0' which is the null character.
Here char represents the 16-bit integer value of the character in quotes. Refer this table for the values.
There is no representation number for "empty/no character".
In case of String refer their source code. You can see that empty string is represented internally by 0 size char array. So String internally does not have magical representation of empty/no character. For "" String class does not allocate any space per se
I'm trying to convert the first two characters of a String using the parseInt method but I cannot. It's supposed to look like this:
String firstChars = IntMessage.substring(0,2);// firstChars is a String that corresponds to the first two characters of the string.
message=ASCII[(Integer.parseInt(firstChar))-32];//The message variable is a String that is supposed to take a firstChars variable and make it an integer so it can be used by the ASCII array in determining which element of the array is to be concatenated to the message String.
For example if the first two characters are 98, I want to take that substring and convert it into an int.
Well, other than the fact that your string is called firstChars and you're trying to parse firstChar, that should work fine.
But this is an area where you should either be using a debugger with breakpoints so you can figure out what values are being placed in the variables, or just print them out:
IntMessage before doing the substring (and shouldn't this normally start with a lower case letter if it's an object?).
firstChars after doing the substring (make sure it's numeric, for example).
Integer.parseInt(firstChars) after that, making sure it's what you expect.
Then Integer.parseInt(firstChars) - 32.
Finally, ASCII[Integer.parseInt(firstChars) - 32].
Then it will be a simple matter of examining all the outputs to see what the problem is.
Do you know the problem as to why i am not getting Hello
byte f [] ="hello".getBytes();
System.out.println(f.toString());
Because byte[]#toString() is (usually) not implemented as new String(byteArray), which would lead to the result you expect (e.g. System.out.println(new String(byteArray));.
You may want to give this page an eye...
Because the toString method of a byte array does not print its contents (at all). And bytes are not characters anyway. Why do you expect to see "hello"? Why not doing System.out.println("hello") directly?
The reason you are getting "strange" output from System.out.println(f.toString()) is that you are printing an array, not a String. Java's array classes do not override the toString() method. Therefore the toString() method that is being called is the one from java.lang.Object which is defined to output the object's class name and its identity hashcode. (In this case, the class name of the byte[] class will be "[b".)
I think your confusion arises from the fact that you are mentally equating a String and a byte array. There are two reasons why this is conceptually wrong:
In Java, Strings are not arrays of anything. The String class a fully encapsulated class that cannot be cast to anything else .... apart from Object.
In Java, a String models a sequence of characters, not a sequence of bytes.
The latter is a key difference because there are many possible conversions between character sequences and bytes, many of which are lossy in one or both directions. When you call "hello".getBytes() you get the conversion implied by your platform's default character encoding, but you could have supplied a parameter to getBytes to use a different encoding in the conversion.
as f is not a string, toString() method of object class is called and not of String class.
toString of String class returns a String and toString of object class returns :
getClass().getName() + '#' + Integer.toHexString(hashCode())
..... aww aww dont go too far ...its same as :
classname.#hexadecimal code for the hash code
You're not able to convert between a byte array and a String without providing an encoding method.
Try System.out.println(new String(f, "UTF8"));
Currently when I make a signature using java.security.signature, it passes back a string.
I can't seem to use this string since there are special characters that can only be seen when i copy the string into notepad++, from there if I remove these special characters I can use the remains of the string in my program.
In notepad they look like black boxes with the words ACK GS STX SI SUB ETB BS VT
I don't really understand what they are so its hard to tell how to get ride of them.
Is there a function that i can run to remove these and potentially similar characters?
when i use the base64 class supplied in the posts, i cant go back to a signature
System.out.println(signature);
String base64 = Base64.encodeBytes(sig);
System.out.println(base64);
String sig2 = new String (Base64.decode(base64));
System.out.println(sig2);
gives the output
”zÌý¥y]žd”xKmËY³ÕN´Ìå}ÏBÊNÈ›`Αrp~jÖüñ0…Rõ…•éh?ÞÀ_û_¥ÂçªsÂk{6H7œÉ/”âtTK±Ï…Ã/Ùê²
lHrM/aV5XZ5klHhLbctZs9VOtMzlfc9Cyk7Im2DOkXJwfmoG1vzxMIVS9YWV6Wg/HQLewF/7X6XC56pzwmt7DzZIN5zJL5TidFRLsc+Fwy/Z6rIaNA2uVlCh3XYkWcu882tKt2RySSkn1heWhG0IeNNfopAvbmHDlgszaWaXYzY=
[B#15356d5
The odd characters are there because cryptographic signatures produce bytes rather than strings. Consequently if you want a printable representation you should Base64 encode it (here's a public domain implementation for Java).
Stripping the non-printing characters from a cryptographic signature will render it useless as you will be unable to use it for verification.
Update:
[B#15356d5
This is the result of toString called on a byte array. "[" means array, "B" means byte and "15356d5" is the address of the array. You should be passing the array you get out of decode to [Signature.verify](http://java.sun.com/j2se/1.4.2/docs/api/java/security/Signature.html#verify(byte[])).
Something like:
Signature sig = new Signature("dsa");
sig.initVerify(key);
sig.verify(Base64.decode(base64)); // <-- bytes go here
How are you "making" the signature? If you use the sign method, you get back a byte array, not a string. That's not a binary representation of some text, it's just arbitrary binary data. That's what you should use, and if you need to convert it into a string you should use a base64 conversion to avoid data corruption.
If I understand your problem correctly, you need to get rid of characters with code below 32, except maybe char 9 (tab), char 10 (new line) and char 13 (return).
Edit: I agree with the others as handling a crypto output like this is not what you usually want.