What is the difference between charValue() and toString() methods of class Character. Both of them return the same i.e, the character value held by the object of the class character as in following code.
public class OtherCharMethods
{
public static void main(String[] args)
{
Character c1 = 'A';
Character c2 = 'A';
System.out.printf(
"c1 = %s\nc2 = %s\n\n", c1.charValue(), c2.toString());
if (c1.equals(c2))
System.out.println("c1 and c2 are equal\n");
else
System.out.println("c1 and c2 are not equal\n");
}
} // end class OtherCharMethods
The one method returns a single char value (primitive type); the other one returns a String (reference type).
That is all there is to this.
Given your comment: the thing to understand - that returned string will of course contain exactly one character; the one that charValue() returns to you.
But: those are still two different things. As the literals "a" and 'a' also contain one char; but in the end mean different things. If you just print the variables to System.out; of course that gives the same result. But that doesn't make a char the same as a String.
Character#charValue() returns a char, Character#toString() returns an string OBJECT, that is a huge difference between those two, one is a primitive, the other an object
charValue() will represent certain value of the character and toString() function will convert the value into string. so both the operation are different.. if you try to give more than one character in the charvalue() function's object, it will give a compile time error but in toString() case its different you can pass any kind of object and any number of characters which capable to convert it to string.
Related
code:
String st = "abc";
String sl = st.charAt(0)+st.charAt(st.length()-1));
The second line is wrong for some reason and I don't know why
The book is wrong, and Eclipse is right.
In Java, you can write "abc" + whatever, or whatever + "abc", and it concatenates the strings -- because one side is a String.
But in st.charAt(0)+st.charAt(st.length()-1)), neither side is a String. They're both chars. So Java won't give you a String back.
Instead, Java will actually technically give you an int. Here are the gritty details from the Java Language Specification, which describes exactly how Java works:
JLS 4.2 specifies that char is considered a numeric type.
JLS 15.18.2 specifies what + does to values of numeric types.
In particular, it specifies that the first thing done to them is binary numeric promotion, which converts both chars to int by JLS 5.6.2. Then it adds them, and the result is still an int.
To get what you want to happen, probably the simplest solution is to write
String sl = st.charAt(0) + "" + st.charAt(st.length() - 1));
Because charAt returns char [ int ]
use this code :
String st = "abc";
StringBuilder str = new StringBuilder();
str.append(st.charAt(0));
str.append(st.charAt(st.length() - 1));
System.out.println(str.toString());
append method accept the char, or string, ..
well this is what it says: "- Type mismatch: cannot convert from int to String"
Meaning exactly what #Jaime said. If I remember correctly, a char is technically represented by an integer value. (i.e. 'a' + 1 = 'b'). So you're adding two char values, which isn't the same thing as adding two strings together, or even concatenating two char values. One fix would be to use String.valueOf(st.charAt(0)) + String.valueOf(st.charAt(st.length()-1))) to concatenate the two char values.
I want to convert those if-statements into a ternary operator expression, but I've been struggling since I haven't had the need to use them that much. The code essentially replaces the characters '1' with 'i', removes characters that are not letters, and also removes upper-case letters by enqueuing elements that don't meet those conditions.
private static Iterable<Character> transformationA(Queue<Character> q) {
Queue<Character> retq = new Queue<>();
for(Character c: q) {
if(c.equals('1')) {
retq.enqueue('i');
}
if(Character.isLowerCase(c)) {
retq.enqueue(c);
}
}
return retq;
}
Edit: thanks for your comments, code and suggestions.
Something like:
inQueue.stream()
.map(c -> '1'.equals(c)?'i':c)
.filter(Character::isLowerCase)
.collect(Collectors.toCollection(Queue::new)));
Ternary operation does not fit
As commented, a ternary operation is not appropriate to your code. A ternary operation in Java is an expression, returning a result.
In your case, you do not have a "if x is true, return y, otherwise return z" situation. In your case you may enqueue an I, or you may enqueue a lowercase letter, or you may do nothing (thereby ignoring that nth character).
Unicode code points
The char type (and its Character wrapper class) are legacy, essentially broken. As a 16-bit value, the char type is incapable of representing even half of the characters defined in Unicode.
Instead use Unicode code point integer numbers.
Pass in a collection of int or Integer (or IntStream) rather than Character objects. And actually, I would just pass in a CharSequence (the interface for String, etc.).
To see if the code point represents the character for the digit 1, check for a code point number of 49 (decimal), the ASCII/Unicode number for the digit 1: if( codePoint == 49 ) { … } where codePoint is an int/Integer.
For lowercase check, pass the code point integer: if( Character.isLowerCase( codePoint ) ) { … }.
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.
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 8 years ago.
I was trying to implement a string reversal algorithm by using two pointer variables at each end of the string where i points to the beginning and j points to the end. The elements at these places are swapped and then i and j are incremented and decremented respectively until i is less than j and i not equal to j. I am storing the string in a character array while doing this since string is immutable in java. However, when I am trying to convert this character array back to a string using the toString() method it is displaying random values. I know the code is correct since if I output the character array it displays the right values.
public class switcher {
int i=0,j;
char temp;
public void reverse(String s){
char [] ar = s.toCharArray();
j=ar.length-1;
while(i!=j&&i<j){
temp = ar[i];
ar[i]=ar[j];
ar[j]=temp;
i++;
j--;
}
String b=ar.toString();
System.out.println(b);
System.out.println(ar);
}
The output is as follows for the two print statements:
amistad
[C#22a79c31
datsima
As you can see the string output is not correct. However, the array output is perfect.
Please tell me what I am doing wrong.
If you want to print String which should be based on array of character then you should wrap this array with new String object. So instead of
String b = ar.toString();
use
String b = new String(ar);
You need to know that arrays inherit toString() method from Object so its code returns
getClass().getName() + "#" + Integer.toHexString(hashCode());
which means you will see [C as result of getClass().getName() which represents one dimensional array of characters, # token and hexadecimal form of arrays hexcode 22a79c31.
In case you would want to print content of array with different type of data than char you wouldn't be able to wrap it in String. Instead you will have to iterate over each elements and print them. To avoid writing your own method for this Java gives you java.util.Arrays class with toString(yourArray) method which will iterate over each elements of array and generate String in form
[element0, element1, element2, ... , elementN-1]
ar.toString() will not return the string representation of the character array. It will return the index of the array in memory. If you want b to print out properly, pass ar to it as a constructor, like so:
String b = new String(ar);
As others have said, that's correct.
Most Java objects do not do a value conversion in their tostring. Instead they print the tokenized name of the type as known internally to the VM.
To convert a character array to a string for printing you want to do the opposite of what you did to convert it from a string.
The simplest way is simply to make use of the string constructor that takes a character array
So rather then saying:
System.out.println(ar);
You could say
System.out.println(new String(ar));
char c = '\u0000';
When I print c, it shows 'a' in the command line window.
So what's the default value of a char type field?
Someone said '\u0000' means null in Unicode; is that right?
The default value of a char attribute is indeed '\u0000' (the null character) as stated in the Java Language Specification, section §4.12.5 Initial Values of Variables .
In my system, the line System.out.println('\u0000'); prints a little square, meaning that it's not a printable character - as expected.
'\u0000' is the default value for a character. Its decimal equivalent is 0.
When you are declaring some char variable without initializing it, '\u0000' will be assigned to it by default.
see this code
public class Test {
char c;
public static void main(String args[]) throws Exception {
Test t = new Test();
char c1 = '\u0000';
System.out.println(t.c);
System.out.println(c1);
System.out.println(t.c == c1);
}
}
This code will print true for the last print.
Default value of Character is Character.MIN_VALUE which internally represented as MIN_VALUE = '\u0000'
Additionally, you can check if the character field contains default value as
Character DEFAULT_CHAR = new Character(Character.MIN_VALUE);
if (DEFAULT_CHAR.compareTo((Character) value) == 0)
{
}
'\u0000' stands for null . So if you print an uninitialized char variable , you'll get nothing.
It's '\u0000'. See here for more information.
The default char is the character with an int value of 0 (zero).
char NULLCHAR = (char) 0;
char NULLCHAR = '\0';
its tempting say as white space or integer 0 as per below proof
char c1 = '\u0000';
System.out.println("*"+c1+"*");
System.out.println((int)c1);
but i wouldn't say so because, it might differ it different platforms or in future. What i really care is i ll never use this default value, so before using any char just check it is \u0000 or not, then use it to avoid misconceptions in programs. Its as simple as that.
The default value of a char data type is '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
You can see the info here.
Note that there is a distinct difference between null and zero.
In http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html (referenced above), the statement is made :-
There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
That is why the following statements will give you an error and not the other :-
char a = null; //Type mismatch: cannot convert from null to char.
char b = 0; //Valid syntax.
\u0000 is the default value for char type in Java
As others mentioned, you can use comparison to check the value of an uninitialized variable.
char ch;
if(ch==0)
System.out.println("Default value is the null character");
I think it is '\u00000' or just '' rather than '\u0000'
(The 1st one has 5 zeros while the last one has four zeroes.)
Default value for char is \u0000
public class DefaultValues {
char varChar;
public static void main(String...l)
{
DefaultValues ob =new DefaultValues();
System.out.println(ob.varChar=='\u0000');
}
}
This will return true
The default value of char is null which is '\u0000' as per Unicode chart. Let us see how it works while printing out.
public class Test_Class {
char c;
void printAll() {
System.out.println("c = " + c);
}
public static void main(String[] args) {
Test_Class f = new Test_Class();
f.printAll();
} }
Note: The output is blank.
The default value of a char primitive type is '\u0000'(null character) as stated in the Java Language Specification.
The shortcut for 'u0000' is '\0', So the null can be represented either by 'u0000' or '\0'.
The below Java program validates null representations using instance char field 'c'.
public class DefaultValueForchar {
char c;
public static void main(String[] args) {
char c0 = '\0';
char cu0000 = '\u0000';
DefaultValueForchar obj = new DefaultValueForchar();
System.out.println(obj.c);
System.out.println(c0);
System.out.println(cu0000);
System.out.println(c0==cu0000);
System.out.println(obj.c==c0);
System.out.println(obj.c==cu0000);
}
}