Java: Strings

String Methods:

String txt = "Hello World";
System.out.println(txt.toUpperCase());   // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase());   // Outputs "hello world"

 

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

System.out.println(txt.indexOf("p")); // Outputs 0
System.out.println(txt.indexOf("l")); // Outputs 1

 

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

 

String x = "10";
String y = "20";
String z = x + y;  // z will be 1020 (a String)

 

String x = "10";
int y = 20;
String z = x + y;  // z will be 1020 (a String)

 

Special Characters

Escape characterResultDescription
\' ' Single quote
\" " Double quote
\\ \ Backslash
 

 

 

 

CodeResult 
\n New Line

String txt = "Hello\nWorld!";
System.out.println(txt);

// Outputs 

Hello
World!

\r Carriage Return

String txt = "Hello\rWorld!";
System.out.println(txt);

// Outputs 

Hello
World!

\t Tab

String txt = "Hello\tWorld!";
System.out.println(txt);

// Outputs 

Hello    World!

\b Backspace

String txt = "Hel\blo World!";
System.out.println(txt);

// Outputs 

Helo World!

 

posted @ 2022-11-24 03:17  小白冲冲  阅读(29)  评论(0编辑  收藏  举报