📄 stringclassdemo.java
字号:
package unitOne;
import java.io.*; // the PrintWriter class is here
//no need to import String since it's in java.lang
/**
* This class is a demo of class String
*
* @author iCarnegie
* version 1.0.0
*/
public class StringClassDemo {
private static PrintWriter stdOut = new PrintWriter(System.out, true);
/**
* Main method, show the use of class String
*
* @param args not used
*/
public static void main(String[] args) {
String strHello = new String("Hello");
// string literal will be replaced by new String("World")
String strWorld = "World";
// string concatenation prints: Hello, World
stdOut.println(strHello + ", " + strWorld);
// prints the character r
stdOut.println(strWorld.charAt(2));
// prints the integer 2 which is the index of the first 'l' in strHello
stdOut.println(strHello.indexOf('l'));
// prints the integer 1 which is the index of the start of the string
// "or" in strWorld
stdOut.println(strWorld.indexOf("or"));
// prints the integer 6 which is the index of the first 'o' in the
// string "HelloWorld" starting from index 5
stdOut.println((strHello + strWorld).indexOf('o', 5));
// prints: "Hello" and "World" are equal in length
stdOut.print("\"" + strHello + "\" and \"" + strWorld + "\" are ");
if (strHello.length() != strWorld.length()) {
stdOut.print("not ");
}
stdOut.println("equal in length");
// reassign strWorld to a new String could have
// been written: strWorld = "Hello";
strWorld = new String("Hello");
// nothing is printed here
// This may be surprising, but remember, since
// Strings are objects, the == compares the addresses
// of the objects, not the objects themselves.
if (strHello == strWorld) {
stdOut.println("The strings are equivalent according to ==");
}
// the following is what should have been written
// prints: The strings are equivalent.
if (strHello.equals(strWorld)) {
stdOut.println("The strings are equivalent.");
}
// a group of static methods exist to convert from
// a primitive to a String representation of it
String strValues;
strValues = String.valueOf(5.87); // strValues is now "5.87"
strValues = String.valueOf(true); // strValues is now "true"
strValues = String.valueOf(18); // strValues is now "18"
// concatenation
stdOut.println(strValues+" , "+5.87 + "" + true + "" + 18); // prints 5.87true18
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -