Difference between char and String in Java
char
is one character. String
is zero or more characters.
char
is a primitive type. String
is a class.
char c = 'a';
String s = "Hi!";
Note the single quotes for char
, and double quotes for String
.
Is there a difference in SIZE between String a and a Char 'a'?
Note there are actually 3 cases
String "a"
Character 'a'
char 'a'
of these, char 'a' will take up the least amount of space (2 bytes), whereas Char 'a' and String "a" are both objects and so because of the memory overhead associated with an Object, both will be approximately the same size
Point of using char rather than String
char is a primitive data type while String is a class. If you need to store just 1 character, using a char is always better as it would consume lesser memory also using a String to store 1 character is just unrequired as every String also has a lot of methods that are kind of irrelevant for a single character. So, if it is just 1 character that you need to store, using a char is far better choice for the following reasons.
- String would need to create an object to store the char, while char is a primitive type and no such objects are created.
- Lesser memory and faster processing.
Also, char type can be used with arithmetic operators like + and -.
So, use char when you only need to store a character and don't need any String methods and use String when there is more than 1 character to deal with.
Read here for more details
Difference between a string and an array of characters
To correct compilation error replace with one of the below char[]
statement
String s = "MY PROFESSION";
char c1[] = "MY PROFESSION".toCharArray();
char c2[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N' };
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
Following section compares above statement with each other
String Constant
String s="MY PROFESSION";
- "MY PROFESSION" is a constant and stored in String pool see Where does Java's String constant pool live, the heap or the stack?
s
is immutable i.e content ofString
is intact can not be modified.- Size/Length of string is fixed (not possible to append)
Character Array
char c1[]="MY PROFESSION".toCharArray();
char c2[]={'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N'};
c1
holds copy of String's underlying array (viaSystem.arraycopy
) and stored in heap spacec2
is built on the fly in the stack frame by loading individual character constantsc1
&c2
are mutable i.e content ofArray
can be modified.c2[0]='B'
- Size/Length of Array is fixed (not possible to append)
StringBuilder / StringBuffer
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
- Both
sb
andsbu
are mutable.sb.replace(0, 1, 'B');
- Both
sb
andsbu
are stored in heap - Size/Length can be modified.
sb.append( '!');
StringBuffer
's methods are synchronised whileStringBuilder
's methods are not
Difference between String + char and String + single char String
Using A + "B" is much slower than using A + 'B' based on this test result
Concatenate char literal ('x') vs single char string literal (“x”)
Test Result:
averageing to:
a+'B': 4608ms
a+"B": 5167ms
What's the difference between string[i] and string.charAt(i) in Java?
This might clear things up for you:
public static void main(String[] args) {
String str = "my name is Muneeb";
String[] strarray = str.split(" "); //split on white space.
for(int i=0; i<str.length(); i++){
System.out.println(str.charAt(i));
}
for(int i=0; i<strarray.length; i++){
System.out.println(strarray[i]);
}
}
The first output will be:
m
y
n
a
m
e
i
s
M
u
n
e
e
b
The second output will be:
my
name
is
Muneeb
differences between char * and string
Assuming you're referring to std::string
, string
is a standard library class modelling a string.
char* is just a pointer to a single char. In C and C++, various functions exist that will take a pointer to a single char as a parameter and will track along the memory until a 0 memory value is reached (often called the null terminator). In that way it models a string of characters; strlen
is an example of a function (from the C standard library) that does this.
If you have a choice, use std::string
as you don't have to concern yourself with memory.
Difference between new String(char[]) and char[].toString
In Java, toString
on an array prints [
, then a character representing the array element type (C
in this case) and then the identity hash code. So in your case, are you sure it is returning the original string and not something like [C@f4e6d
?
Either way, you should use new String(arr)
. This is the shortest, neatest, way of converting a char[]
back to a String
. You could also use Arrays.toString(arr)
Related trivia
The reason that your arr.toString()
method returns something like [Cf4e6d
is that Object.toString
returns
getClass().getName() + '@' + Integer.toHexString(hashCode())
For a char
array, getName()
returns the string [C
. For your program you can see this with the code:
System.out.println(arr.getClass().getName());
The second part of the result, Object.hashCode()
, returns a number based on the object's memory address, not the array contents. This is because by default the definition of "equals" for an object is reference equality, i.e. two objects are the same only if they are the same referenced object in memory. You will therefore get different arr.toString()
values for two arrays based on the same string:
String s = "fdsa";
char[] arr = s.toCharArray();
char[] arr2 = s.toCharArray();
System.out.println(arr.toString());
System.out.println(arr2.toString());
gives:
[C@4b7c8f7f
[C@5eb10190
Note that this is different for the String
class where the equality rules are overridden to make it have value equality. However, you should always use string1.equals(string2)
to test for string equality, and not ==
as the ==
method will still test for memory location.
Related Topics
Difference Between One-To-Many, Many-To-One and Many-To-Many
Generate Uml Class Diagram from Java Project
How to Find Out What Keystore My Jvm Is Using
How to Do an Integer.Parseint() for a Decimal Number
How to Convert Pojo to JSON and Vice Versa
How to Test If My Font Is Rendered Correctly in PDF
Simple Hibernate Query Returning Very Slowly
What Is the Right Action to Take Upon Closing Windows in Java/Swing
Best Way to Pick a Random Subset from a Collection
Openjdk Availability for Windows Os
Converting a Jfreechart Timeseries Series with Day Data to Week or Month Data
Is Polymorphism Possible Without Inheritance
How to View Tomcat Log Files in Eclipse