Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "char" and "String" in Java

Tags:

java

string

char

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.)

like image 231
Android Girl Avatar asked May 03 '12 11:05

Android Girl


People also ask

What is the difference string and char?

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.

What is string and character in Java?

An object of type Character contains a single field whose type is char . This Character class also offers a number of useful class (that is, static) methods for manipulating characters. Strings are a sequence of characters and are widely used in Java programming. In the Java programming language, strings are objects.

What is the difference between string and char array?

String is implemented to store sequence of characters and to be represented as a single data type and single entity. Character Array on the other hand is a sequential collection of data type char where each element is a separate entity. String internal implementation makes it immutable in nature.

What is a char in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


2 Answers

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.

like image 126
user207421 Avatar answered Sep 16 '22 19:09

user207421


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.

like image 44
Vladimir Ivanov Avatar answered Sep 19 '22 19:09

Vladimir Ivanov