[course04] 02 String

[course04] 02 String

Strings

String is a class, and a value of type String is an object. That object contains data, namely the sequence of characters that make up the string. It also contains subroutines. All of these subroutines are in fact functions.

String advice;
advice = "Seize the day!";

String day = "new day";
String username = new String("Joh");
username = "Harry";
System.out.print("The number of characters in ");
System.out.print("the string \"Hello World\" is ");
System.out.println( "Hello World".length() );
  • String is not a primitive type, but a class/type

  • String variables store references to memory addresses

  • Strings are immutable! That is, you cannot change a string, but you can assign a new string to a variable.

  • A string cannot span more than one line

Java escape sequence

String is a sequence of (unicode) characters

When we declare a variable of type String, it does not create an object. String founder;

To create an object we use the new operator:

Strings have a shortcut way of creating them:

difference the two types

Object vs Primitive Data

devdocs java

  • s1.equals(s2)

  • s1.equalsIgnoreCase(s2)

  • s1.length()

  • s1.charAt(N)

  • s1.substring(N,M)and s1.substring(N)

  • s1.indexOf(s2) and s1.lastIndexOf(x)

  • s1.compareTo(s2) and s1.compareToIgnoreCase(s2)

  • s1.toUpperCase() and s1.toLowerCase()

  • s1.trim()

immutable feature of String

The concatenation operator

use equals to compare String

String pool

Substring

substring

Replacing Characters

replace

Compare the lexicographical order of two strings

compareTo

Enums

An enum is a type that has a fixed list of possible values, which is specified when the enum is created.

Multiline Strings

""" text blocks, this is only supported in Java 15

Java 8 multiline Strings

Letter Counter

Java Version

Python Version

String demo

Last updated

Was this helpful?