...

/

Text values with String and char

Text values with String and char

Learn to work with text data in Java.

We'll cover the following...

A variable used to hold a string value in Java has the type String. The string data itself, when typed in quotes in code, is called a string literal; Java should interpret it as literal string data, and not as code.

What does the following code print? Is there an error in the code? Fix it.

class Fixme {
public static void main(String args[]) {
String greeting;
greeting = "hello";
System.out.println(greeting);
System.out.println(hello);
System.out.println("greeting");
System.out.println("hello");
}
}

String is a class

Each of the Java programs you have seen so far was defined as a single class containing some methods. A class in Java has two purposes:

  1. A class is a collection of methods that you may call.
  2. A class defines a custom data type, and can be used to make objects of that class.

The String class serves both purposes: it provides some methods that are useful for Strings, and it defines a String data type that you can use to make string objects.

Let’s look at the first use first. The String class is contained somewhere in a Java file called String.java. It contains within it several static methods. You can call a static method of a class by using the format Classname.methodname().

Usually, before using the static methods of a class, you need to import that class, which we will see how to do later, but String is special and built-in.

The static method String.valueOf()

As an ...