Difference between "char" and "String" in Java - java

I am reading a book for Java that I am trying to learn, and I have a question. I can't understand what is the difference between the variable type char and String. For example, there is a difference between int and short, the bytes at the memory and the area of numbers that they have.
But what is the difference between char and String? except that char use (') and "String" (").
PS: It is my first "real" programming language. (At school I learned a fake-language for the purpose of the programming lesson.)

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.

char means single character. In java it is UTF-16 character.
String can be thought as an array of chars.
So, imagine "Android" string. It consists of 'A', 'n', 'd', 'r', 'o', 'i' and again 'd' characters.
char is a primitive type in java and String is a class, which encapsulates array of chars.

In layman's term, char is a letter, while String is a collection of letter (or a word). The distinction of ' and " is important, as 'Test' is illegal in Java.
char is a primitive type, String is a class

char is a primitive type, and it can hold a single character.
String is instead a reference type, thus a full-blown object. It can hold any number of characters
(internally, String objects save them in a char array).
Primitive types in Java have advantages in term of speed and memory footprint. But they are not real objects, so there are some possibilities you lose using them. They cannot be used as Generic type parameters, they could not have methods or fields, and so on.
However, every Java primitive type has a corresponding full-blown object, and the conversion between them is done automagically by the compiler (this is called autoboxing).
You can for example do:
int i=12;
Integer l=i;
The compiler takes care of converting the int to a Integer.

char have any but one character (letters, numbers,...)
char example = 'x';
string can have zero characters or as many as you want
String example = "Here you can have anything";

Char is a single alphabet where as String is a sequence of characters.
Char is primitive datatype where as String is a class.

A char holds a single character, while a string holds lots of characters.

char is a primitive type, and it can hold a single character. String is instead a reference type, thus a full-blown object.

Well, char (or its wrapper class Character) means a single character, i.e. you can't write 'ab' whereas String is a text consisting of a number of characters and you can think of a string a an array of characters (in fact the String class has a member char[] value).
You could work with plain char arrays but that's quite tedious and thus the String class is there to provide a convenient way for working with texts.

A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)

A char consists of a single character and should be specified in single quotes. It can contain an alphabetic, numerical or even special character. below are a few examples:
char a = '4';
char b = '$';
char c = 'B';
A String defines a line can be used which is specified in double quotes. Below are a few examples:
String a = "Hello World";
String b = "1234";
String c = "%%";

In string we can store multiple char.
e.g.
char ch='a';
String s="a";
String s1="aaaa";

In terms of ASCII values you can say char is a single ASCII value ranging from 0-255. Whereas String is a collection of ASCII values.
Try this code to learn better.
char c='a';
String s="a b c d e f g hijkl";
int i=c;
System.out.println(i);
for(int count=0;count<s.length();count++){
int temp=s.charAt(count);
System.out.print(temp+" ");
}
The output will be:
97
97 32 98 32 99 32 100 32 101 32 102 32 103 32 104 105 106 107 108
Since 97 is the ASCII value for small 'a'. 32 is the ASCII value for space. Hope this helps in-depth understanding of the concept.

A character is anything that you can type such as letters,digits,punctuations and spaces. Strings appears in variables.i.e they are text items in perls. A character consist of 16bits. While the lenght of a string is unlimited.

Related

How to get the previous char of a given char in java? [duplicate]

I have a capital letter defined in a variable string, and I want to output the next and previous letters in the alphabet. For example, if the variable was equal to 'C', I would want to output 'B' and 'D'.
One way:
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Well if you mean the 'ABC' then they split into two sequences a-z and A-Z, the simplest way I think would be to use a char variable and to increment the index by one.
char letter='c';
letter++; // (letter=='d')
same goes for decrement:
char letter='c';
letter--; // (letter=='b')
thing is that the representation of the letters a-z are 97-122 and A-Z are 65-90, so if the case of the letter is important you need to pay attention to it.
If you are limited to the latin alphabet, you can use the fact that the characters in the ASCII table are ordered alphabetically, so:
System.out.println((char) ('C' + 1));
System.out.println((char) ('C' - 1));
outputs D and B.
What you do is add a char and an int, thus effectively adding the int to the ascii code of the char. When you cast back to char, the ascii code is converted to a character.
All the answers are correct but none seem to give a full explanation so I'll try. Just like any other type, a char is stored as a number (16-bit in Java). Unlike other non-numeric types, the mapping of the values of the stored numbers to the values of the chars they represent are well known. This mapping is called the ASCII Table. The Java compiler treats chars as a 16-bit number and therefore you can do the following:
System.out.print((int)'A'); // prints 65
System.out.print((char)65); // prints A
For this reason, the ++, -- and other mathematical operations apply to chars and provide a way to increment\decrement their values.
Note that the casting is cyclic when you exceed 16-bit:
System.out.print((char)65601); // also prints A
System.out.print((char)-65471); // also prints A
P.S. This also applies to Kotlin:
println('A'.toInt()) // prints 65
println(65.toChar()) // prints A
println(65601.toChar()) // prints A
println((-65471).toChar()) // prints A
just like this :
System.out.printf("%c\n",letter);
letter++;

Converting String to Char array in JAVA

I am using the toCharArray method to convert a string to an array of type char but every time i try to print the array, it is printing numbers instead of the characters stored in the string. When i print the string the characters are printed just fine.
char[] nArray = capitalizedSentence.toCharArray();
for (int i = 0; i < nArray.length; i++)
{
System.out.println(nArray[i] + '\n');
}
EXAMPLE:
If my capitalizedSentence string has the value "Saad", when i convert it to a character array and print it, it prints the following:
93
75
75
78
can someone please help me so that it prints the individual characters stored in the capitalizedSentence string?
nArray[i] is a char; so is the '\n' constant. Character is an unsigned integral type, so characters are added together in the same way as all integers - numerically. When an addition happens, you end up with an int, not a char, so calling println on it produces a numeric result.
Removing + '\n' will fix the problem. You would get a newline character from println, so all characters would appear on a new line.
Demo.
Replace '\n' with "\n"
Why? Because the compiler sees you adding 2 characters together, to the compiler char and int primitive data types are considered to interchangeable and so the + is actually adding the 2 int values together. Using double quotes will tell the compiler that you are adding a string to a character.
I think this will help you. Use for-each loop
char[] nArray = capitalizedSentence.toCharArray();
for(Character c: nArray ){
System.out.println(c);
}

How to represent empty char in Java Character class

I want to represent an empty character in Java as "" in String...
Like that char ch = an empty character;
Actually I want to replace a character without leaving space.
I think it might be sufficient to understand what this means: no character not even space.
You may assign '\u0000' (or 0).
For this purpose, use Character.MIN_VALUE.
Character ch = Character.MIN_VALUE;
char means exactly one character. You can't assign zero characters to this type.
That means that there is no char value for which String.replace(char, char) would return a string with a diffrent length.
As Character is a class deriving from Object, you can assign null as "instance":
Character myChar = null;
Problem solved ;)
An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.
You say you want to "replace a character without leaving a space".
If you are dealing with a char[], then you would create a new char[] with that element removed.
If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.
Here are some samples of how you could remove a char:
public static void main(String[] args) throws Exception {
String s = "abcdefg";
int index = s.indexOf('d');
// delete a char from a char[]
char[] array = s.toCharArray();
char[] tmp = new char[array.length-1];
System.arraycopy(array, 0, tmp, 0, index);
System.arraycopy(array, index+1, tmp, index, tmp.length-index);
System.err.println(new String(tmp));
// delete a char from a String using replace
String s1 = s.replace("d", "");
System.err.println(s1);
// delete a char from a String using StringBuilder
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(index);
s1 = sb.toString();
System.err.println(s1);
}
As chars can be represented as Integers (ASCII-Codes), you can simply write:
char c = 0;
The 0 in ASCII-Code is null.
If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character
I was looking for this. Simply set the char c = 0; and it works perfectly. Try it.
For example, if you are trying to remove duplicate characters from a String , one way would be to convert the string to char array and store in a hashset of characters which would automatically prevent duplicates.
Another way, however, will be to convert the string to a char array, use two for-loops and compare each character with the rest of the string/char array (a Big O on N^2 activity), then for each duplicate found just set that char to 0..
...and use new String(char[]) to convert the resulting char array to string and then sysout to print (this is all java btw). you will observe all chars set to zero are simply not there and all duplicates are gone. long post, but just wanted to give you an example.
so yes set char c = 0; or if for char array, set cArray[i]=0 for that specific duplicate character and you will have removed it.
You can't. "" is the literal for a string, which contains no characters. It does not contain the "empty character" (whatever you mean by that).
In java there is nothing as empty character literal, in other words, '' has no meaning unlike "" which means a empty String literal
The closest you can go about representing empty character literal is through zero length char[], something like:
char[] cArr = {}; // cArr is a zero length array
char[] cArr = new char[0] // this does the same
If you refer to String class its default constructor creates a empty character sequence using new char[0]
Also, using Character.MIN_VALUE is not correct because it is not really empty character rather smallest value of type character.
I also don't like Character c = null; as a solution mainly because jvm will throw NPE if it tries to un-box it. Secondly, null is basically a reference to nothing w.r.t reference type and here we are dealing with primitive type which don't accept null as a possible value.
Assuming that in the string, say str, OP wants to replace all occurrences of a character, say 'x', with empty character '', then try using:
str.replace("x", "");
char ch = Character.MIN_VALUE;
The code above will initialize the variable ch with the minimum value that a char can have (i.e. \u0000).
this is how I do it.
char[] myEmptyCharArray = "".toCharArray();
You can do something like this:
mystring.replace(""+ch, "");
String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE
Where
EMPTY_SPACE = " " (this is String)
TAB = '\t' (this is Character)
String after = before.replaceAll(" ", "").replace('\t', '\0')
means
after = "word"
You can only re-use an existing character. e.g. \0 If you put this in a String, you will have a String with one character in it.
Say you want a char such that when you do
String s =
char ch = ?
String s2 = s + ch; // there is not char which does this.
assert s.equals(s2);
what you have to do instead is
String s =
char ch = MY_NULL_CHAR;
String s2 = ch == MY_NULL_CHAR ? s : s + ch;
assert s.equals(s2);
Use the \b operator (the backspace escape operator) in the second parameter
String test= "Anna Banana";
System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string

char[] to String sequence mismatching in Java for Unicode characters

I have a method like below (please ignore the code optimization issue.) This method replaces the Unicode character (Bengali characters)
static String swap(String temp, char c)
{
Integer length=temp.length();
char[] charArray = temp.toCharArray();
for(int u=0;u<length;u++)
{
if(charArray[u]==c)
{
char g=charArray[u];
charArray[u]=charArray[u-1];
charArray[u-1]=g;
}
}
String string2 = new String(charArray);
return string2;
}
while debugging, i got the values of charArray like the below image:
please note that the characters are in a sequenced format what I want. But after the execution of the statement, the value stored in String variable is mismatched. like below:
I want to display the string as "রেরেরে" but it is displaying "েরেরের" what i not want. Please tell me what I am doing wrong.
Note - I don't know Bengali, but I know a bit (or a lot, depending on whom you ask) about Unicode and how Java supports it. The answer assumes knowledge of the latter and not the former.
Going by the Unicode 6.0 Bengali chart, রে is a combination of the dependent vowel sign ে (0x09C7) and the consonant র (0x09B0) and is represented as a sequence of two characters in the character array.
If you are getting the dependent vowel sign alone, in the resulting character sequence (and hence the string), then your optimization is likely to be kooky, as it appears to assume that Bengali characters in Unicode can be represented as a single Unicode codepoint or a single char variable in Java; this would result in the scenario where a consonant would be replaced by another consonant, but the dependent vowel preceding the consonant would never be replaced.
I think a correct optimization must therefore consider the presence of dependent vowels, and compare the following consonant in addition to the vowel , i.e. it must compare two characters in the character array, instead of comparing individual characters. This might also imply that your method signature must be changed to allow for a char[] to be passed, instead of a single char, so that Bengali characters can be replaced with the intended Bengali character, instead of replacing a Unicode codepoint with another, which is what is being done currently.
The notes in other answers on the ArrayIndexOutofBoundsException is valid. The following example that uses your character replacement algorithm demonstrates that not only is your algorithm incorrect, but it is quite possible for the exception to be thrown:
class CodepointReplacer
{
public static void main(String[] args)
{
String str1 = "রেরেরে";
/*
* The following is a linguistically invalid sequence,
* but Java does not concern itself with linguistical correctness
* if the String or char sequence has been constructed incorrectly.
*/
String str2 = "েরেরের";
/*
* replacement character র for our strings
* It is not রে as one would anticipate.
*/
char c = str1.charAt(1);
optimizeKookily(str1, c);
optimizeKookily(str2, c);
}
private static void optimizeKookily(String temp, char c)
{
Integer length = temp.length();
char[] charArray = temp.toCharArray();
for (int u = 0; u < length; u++)
{
if (charArray[u] == c)
{
char g = charArray[u];
charArray[u] = charArray[u - 1]; //throws exception on second invocation of this method.
charArray[u - 1] = g;
}
}
}
}
A better character replacement strategy would therefore be to use the String.replace (the CharSequence variant) or String.replaceAll functions, assuming that you would know how to use these with Bengali characters.
problem is in
for(int u=0;u<length;u++)
{
if(charArray[u]==c)
{
char g=charArray[u];
charArray[u]=charArray[u-1];
charArray[u-1]=g;
}
}
See when u=0 what is the value of charArray[u-1] that is the index -1.Modify your for loop or just put the condition where u=0.
Your code will cause an IndexOutOfBound Exception.
When u=0, charArray[u-1]=-1.

Difference between '.' and "." in java

Is there a difference between concatenating strings with '' and ""?
For example, what is the difference between:
String s = "hello" + "/" + "world";
and
String s = "hello" + '/' + "world";
Literals enclosed in double quotes, e.g. "foo", are strings, whereas single-quoted literals, e.g. 'c', are chars. In terms of concatenation behaviour, there'll be no discernible difference.
Nevertheless, it's worth remembering that strings and chars aren't interchangeable in all scenarios, and you can't have a single-quoted string made up of multiple characters.
System.out.println('a'+'b'+'c');
> 294
System.out.println("a"+"b"+"c");
> abc
What's happening here is that (char)+(char)=(int)
In other words. Use "" for text to avoid surprises.
"." is a String, '.' is a char.
You may just look into the JDK :-)
Given two functions:
public static String concatString(String cs) {
return "hello" + cs + "world";
}
public static String concatChar(char cc) {
return "hello" + cc + "world";
}
after examination of the bytecode it boils down to two AbstractStringBuilder.append(String) vs. AbstractStringBuilder.append(char).
Both methods invoke AbstractStringBuilder.expandCapacity(int)) which will allocate a new char[] eventually and System.arraycopy the old content first.
Afterwards AbstractStringBuilder.append(char) just has to put the given char in the array whereas AbstractStringBuilder.append(String) has to check a few constraints and calls String.getChars(int, int, char[], int) which does another System.arraycopy of the appended string.
"." is a String consisting of only one character. '.' is a character.
Once you concatenate them together there is no difference.
'' is for character literals.
So you cannot do this:
"Osc" + 'ar' + "Reyes"
Because ar is not a character literal.
In your example it doesn't make much difference because
'/'
is a char literal, and
"/"
is a String literal containing only one character.
Additionally you can use any UTF character with the following syntax
'\u3c00'
So you can also use:
"Osc" + '\u3c00' + "ar
Adding a char is about 25% faster than adding a one character String. Often this doesn't matter however, for example
String s = "hello" + "/" + "world";
This is converted to one String by the compiler so no String concatenation/append will occur at run-time in any case.
Theoretically it is quicker to add a char to a string - Java 6 seems to create StringBuffers under the covers and I remember reading on a Java Performance site that concatenating a char will be marginally quicker.
You will probably find the following articles useful:
Java String Performance Testing
Java String Concatenation
char theLetterA = 'A';
string myString = "a string";
you can only put a single char in between '' if you want to add some more characters use those in between "".
as string is a collection of characters like strong text"hello world"
we can have same thing by using '' like- 'h' 'e' 'l' 'l' 'o' .....
and each has to be stored in different char variable which can be very hectic
so use "" when you have more than one char to store and '' for single char

Categories