HelloStrings
//
// HelloStrings.java
//
public class HelloStrings
{
public static void main(String[] args)
{
String hello = "HelloWorld";
// The + operator concatenates Strings
System.out.println("hello: " + hello);
// A String variable is a reference to a String object,
// which has methods (functions) like `length()`
System.out.println("hello.length(): " + hello.length());
System.out.println();
// String indexing is 0-based
System.out.println("hello.charAt(0): " + hello.charAt(0));
System.out.println("hello.charAt(1): " + hello.charAt(1));
System.out.println("hello.charAt(2): " + hello.charAt(2));
System.out.println();
// The String method `substring(a,b)` returns the substring
// specified by the half-open interval [a,b)
String firstPart = hello.substring(0,5);
System.out.println("firstPart: " + firstPart);
// substring(a) is shorthand for substring(a, length())
String secondPart = hello.substring(5);
System.out.println("secondPart: " + secondPart);
System.out.println();
// Use the equals() method to compare String values.
//
// In the code below, s and t refer to the same String
// object, i.e. s == t.
//
// u is a different String object with the same value
// "Hello", so s != u, but s.equals(u) == true.
String s = new String("Hello");
String t = s;
String u = new String("Hello");
System.out.println("s == t: " + (s == t));
System.out.println("s == u: " + (s == u));
System.out.println("s.equals(u): " + s.equals(u));
}
}
Output:
hello: HelloWorld
hello.length(): 10
hello.charAt(0): H
hello.charAt(1): e
hello.charAt(2): l
firstPart: Hello
secondPart: World
s == t: true
s == u: false
s.equals(u): true