CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Dates

Dates and Strings
String class
Create strings

Creating a string

String newString = new String(stringLiteral);
for example, String message = new String("Welcome to Java");

Two ways to create an empty string

String name = "";
String name = new String();

Two ways to create a string from another string

Since strings are used frequently, Java provides a shorthand initializer for creating a string:

String title = "Murach's Beginning Java 2";
String title = bookTitle;

Two ways to create a string from an array of characters

char cityArray[] = {'D','a','l','l','a','s'};
String cityString1 = new String(cityArray);
String cityString2 = new String(cityArray, 0, 3);

Two ways to create a string from an array of bytes

byte cityArray[] = {68, 97, 108, 108, 97, 115};
String cityString1 = new String(cityArray);
String cityString2 = new String(cityArray, 0, 3);

Notes

  • Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world's diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters.
  • A char data type contains a single Unicode character, which is stored in two bytes. To code a literal char value, you use single quotes instead of double quotes.
  • 	char letter = 'A'; (ASCII)
    	char numChar = '4'; (ASCII)
    	char letter = '\u0041'; (Unicode)
    	char numChar = '\u0034'; (Unicode)
    	

    The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b.

    	 char ch = 'a';
    	 System.out.println(++ch);
    	
  • A byte data type can hold the Unicode value for every character in the ASCII character set.

ASCII Character Set is a subset of the Unicode from \u0000 to \u007f


Previous | Constructors | Create strings | Methods | Code | Next