What's the meaning of char zero (0) in Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java string replace and the NUL (NULL, ASCII 0) character?
I'm doing some String algorithms in Java, and i noticed that wherever i include a char with the value of 0 (zero) it marks the end of the String. Like this:
String aString = "I'm a String";
char[] aStringArray = aString.toCharArray();
aStringArray[1] = 0;
System.out.println(new String(aStringArray)); //It outputs "I"
What's the reason/cause of this behaviour?

The character '\0' is the null character. It's a control character, and it does not terminate the string, that's not how strings work in Java (that's how they work in C, though.)

For some additional insight, add the following to you code:
System.out.println(new String(aStringArray).length());
for (Byte b : new String(aStringArray).getBytes()) {
System.out.print("["+b+"]");
}
Your rendering system (console or output window) is not displaying everything.

I'm wondering if you have posted your actual code. When using the String(byte[]) constructor the actual length of the string is dependent on the contents of the array.

Related

How to Output int from char in JAVA after storing it [duplicate]

This question already has answers here:
Char - Java not working as intended / my code
(4 answers)
Closed 3 years ago.
I am seeing a tutorial on udemy and there the instructor says that we can store the integer variable in the char data type. But when I try to print the value ... nothing shows up
I tried assigning the "char one" value to integer variable and then get the output from int variable,It works but why can not I use the char to output the value
public static void main(String[] args) {
char one = 10;
System.out.println(one);
}
If you look at the ASCII table you would see that the character 10 represents the newline character.
This can be proved by the code below:
public static void main(String[] args) {
char one = 10;
//no newline added by print, but println adds a newline implicitly
System.out.print("Test");
System.out.print(one);
System.out.print("Test");
}
The output is:
Test
Test
Although I used System.out.print a newline was still added in the output after the first Test. So you see something was actually printed.
Furthermore, when you pass a char to the System.out.println() the char is converted to its String representation as per the ASCII table by invoking the String.valueOf(char) as char is a primitive.
For Objects when you pass a reference in the System.out.println() the toString() method of the object would be called to get its String representation.
If you change the value to char one = 65 you would see the letter A printed.
In Java char type is an int, therefore they can be converted char <-> int.
When you print an int - you get an integer number. When you print char - you get an ASCII character. char ch = 10 - is not printable character.
char ch = 'A';
System.out.println(ch); // print 'A'
int code = ch;
System.out.println(code); // print 65 - ASCII code of 'A'
Adding to the above answers, if you want to output the int value from the variable "one", a cast would work:
char one = 10;
System.out.println((int) one);
If you take a look at the ASCII Table, you can see the value of 10 is LF which is a new line. If you print this alone, it will appear to be doing nothing because it is just a new line.
However if you modify the code a bit to print some actual characters on both side of the LF char:
char c1 = 70;
System.out.print(c1);
char one = 10;
System.out.print(one);
char c2 = 71;
System.out.print(c2);
This will output:
F
G
On separate lines due to the newline in between, without it they would have printed on the same line.
Additionally you can see on that table 70 corresponds with F, and 71 with G.
Note: Java does not technically use ASCII, but rather a different encoding depending on your environment(commonly UTF-16 or ISO-8859-1), however, the characters are usually equivalent to ASCII for the amount of values the ASCII table contains (a superset). For example char c1 = 202 will print Ê for me, which is not an ASCII value.
You are misinterpreting your output and drawing the wrong conclusion.
A char is a UTF-16 code unit. UTF-16 is a character encoding for the Unicode character set. UTF-16 encodes a Unicode codepoint with one or two UTF-16 code units. Typically, if it might be two code units, you'd use String or char[] instead of char. But if your codepoint is known to take only one UTF-16 code unit, you could use char.
The codepoint you are using is U+000A 'LINE FEED (LF)'. It does take one UTF-16 code unit \u000a, which is convertible from the integer value 0xa or 10. If you inspect your output carefully, you'll "see". Perhaps adding output before and after would help.

Adding three different char in java as java variable and getting a number [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 4 years ago.
IntelliJ IDEA Capture
Why i am getting 152, I think it will give me an error.
Please explain it.
public class character {
public static void main(String[] args) {
char myCharValue1 = 'A';
char myCharValue2 = '2';
char myCharValue3 = '%';
System.out.println(myCharValue1 + myCharValue2 + myCharValue3);
}
}
That is because chars refer to a number, which in turn has an ASCII representation.
Looking at an ASCII table you can see that the chars A, 2 and % have following values respectivly: 65, 50 and 37.
Adding those numbers together, you'll end up with 152 which is what you got in your example.
To print out those chars you could use following:
System.out.printf("%s%s%s&n", myCharValue1 + myCharValue2 + myCharValue3);
Which will print A2% (and a newline)
The concatenation + is for String. What you're doing is adding the numeric values of your chars and printing them together.
If you start with "" and then use + as Patrick Parker shows in his comment, it will become concatenation instead of simple addition and you'll get the result you expect.

Java - Upper Case Text [duplicate]

This question already has answers here:
First char to upper case [duplicate]
(7 answers)
Closed 8 years ago.
I am trying to get the first character of a string to convert into an upper case. How is this possible?
For example;
String c = "hi steve, how are you doing?";
I want the 'h' of 'hi' capitalized. How do I do that using code?
Thank you in advanced!
c = Character.toUpperCase(c.charAt(0))+c.substring(1);
You can use String's charAt method to get the first character and the Character toUpperCase method to convert it to upper case. Then use the substring method to get everything after the first character.
String c = "hi steve, how are you doing?";
c = Character.toUpperCase(c.charAt(0)) + c.substring(1);
System.out.println(c);
Use of stringbuilder creates less strings:
StringBuilder s1 = new StringBuilder("hi steve");
s1.replace(0, s1.length(), s1.toString().toLowerCase());
s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));

Why this java statement is generating this output? [duplicate]

This question already has answers here:
The concatenation of chars to form a string gives different results
(5 answers)
Closed 9 years ago.
I have a string str, let's say it's value is "hell".
The below statement returns "205hellhe" instead of "hehellhe"
return (str.charAt(0)) + (str.charAt(1))+str+(str.charAt(0)) + (str.charAt(1));
why (str.charAt(0)) + (str.charAt(1)) is returning 205 instead of "he" and why the same statement is returning "he" at the end?
Expressions are evaluated Left-To-Right.
Hence first two chars are evaluated and added, which results in a char (value = 205).
Next this char(=205) is added to a string, which results in String.
Hence the strange output.
Fix:
Use a StringBuilder instead
public static void main(String[] args) {
String str = "hell";
StringBuilder buff = new StringBuilder();
buff.append(str.charAt(0))
.append(str.charAt(1))
.append(str)
.append(str.charAt(0))
.append(str.charAt(1));
System.out.println(buff.toString());// prints 'hehellhe'
}
This is happening because the values of the ASCII codes of the characters are being added instead of being concatenated. In ASCII, h is represented as 104, and e as 101. The concatenation isn't working, probably because both operands in this case are chars/integers.

How to convert an alpha numeric string into long by java code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Eg. BRYR904000Z5 must be converted into numeric format such that
( A = 101, B=102, C=103.... you get it till Z=126 )
I want BRYR904000Z5 as 1021181251189040001265
I would also want to know if the entire number can be displayed. (working on a password generator)
I saw a code to separate the characters but this difficult to understand for me. Thank you
Here's a skeleton of an algorithm:
create a new, empty StringBuilder
loop through all the chars of the string
at each iteration:
if the current char is >= 'A' and <= 'Z', transform it to its numeric value, and append this numeric value to the StringBuilder
else, append the current character to the StringBuilder
transform the StringBuilder into a String
If we're dealing with all capital letters, as it seems that we are, the ASCII value for A is 65. So, in order to get A to be 101, we have to add 36:
/*Expects only capital letters*/
public int charToIntCustomConversion(char c)
{
return (int) c + 36;
}
(int) c gets the ASCII value for c and returns that int + 36.
To convert back:
/*Expects only capital letters*/
public char intToCharCustomConversion(int n)
{
return (char) (n - 36);
}
EDIT:
Forgive me if there is any confusion, the above methods are only for converting from char to int and int to char. You don't need to convert the numbers, since they remain the same, ie simply add them to the String.
In other words, loop through your String and call charToIntCustomConversion when you encounter a letter (again, assumed all are capital), if you encounter a number, simply add it to converted string.
Going back to the original String is a little trickier, but that does not seem to be what you are asking, nonetheless, if you know that an int cooresponds to a character that was converted, you can use intToCharCustomConversion.
Converting Back:
If you want to easily be able to determine if a number in the converted String cooresponds to a character or a number from the original String, the easiest thing to do will probably be to use an Array. If an element in the converted array is a single number, you know that it was originally a number. If it is a 3-digit number, you know that it was originally a char.
NB: There are many more, potentially better ways to do this..
StringBuilder result = new StringBuilder();
for(int i =0; i < string.length(); ++i) {
char c = string.charAt(i);
if (Character.isLetter(c) {
result.append(c - 0x0041 + 101);
} else if (Character.isDigit) {
result.append(c);
} else throw new RuntimeException("BS");
}
0x0041 stands for the unicode of the uppercase A.

Categories