From the course: Java 11+ Essential Training

Manage character values as primitives - Java Tutorial

From the course: Java 11+ Essential Training

Start my 1-month free trial

Manage character values as primitives

- [Instructor] Java distinguishes between characters and strings. A character is a primitive data type that consists of a single character. A string is a complex object that references a collection of characters. You can declare an individual variable as a character either explicitly using the char key word, then I would assign a variable name or identifier, and then I can assign a literal value, a single character wrapped in single quotes. You use single quotes for characters and double quotes for strings. You can also use inferred typing. This time I'll use var and I'll say C2 equals two, again, with single quotes, and then I'll create a third variable named C3. You can also create character values using literals that are Unicode expressions. I'll start with char, I'll name this variable dollar, and then I'll use backslash U for Unicode, and then a four-digit value. 0024 is the value for the dollar sign. If you want to convert a character to an upper or lowercase value, you can use a static method of the character wrapper class. So, for example, I might create a variable named upper and I'll use character.toUpperCase and I'll pass in C1. That's meaningless with a numeric value, so now I'll say C1 equals lowercase A. I don't have to set the type again because I've already declared the variable. I'm just resetting its value. And then I'll once again say upper equals character to uppercase, and, this time, I get an uppercase A. You can create an array of characters like this. I'll start with char, and then the opening and closing brackets mean create an array, a collection of values. I'll name this variable chars and I'll use this expression. I'll start with a brace and then H, E, L, L, and O. Each of these values is a single character wrapped in single quotes. Therefore, it's a primitive character. But now the collection of characters gives you the entire word. If you wanted to turn that array into an actual string, you could say string S equals new string and pass in the array. And now you actually have a string and you know that because it's wrapped in double quotes. And if you want to turn that back into a character array, you could create a variable named charArray and get that value with S.toCharArray. And now you're back to the original array of primitive values. So an array of characters can be used to build a string, and a string can return its array of characters. Knowing that a string is a complex object that references a collection of primitive single characters is incredibly valuable as you learn how to work with strings in Java.

Contents