Java Tutorial menu

Java Strings

A String stores text, such as a name, a message or an address.

Creating a String

Example

java
String greeting = "Welcome to Workownix";

Strings are objects, so they come with many useful methods you can call with a dot.

Common String Methods

MethodWhat it returns
length()Number of characters
toUpperCase()The text in capital letters
toLowerCase()The text in small letters
charAt(i)The character at position i
indexOf("x")Position of the first match, or -1
substring(a, b)Part of the text from a up to (not including) b
contains("x")true if the text is found
trim()The text without spaces at the start and end
replace("a", "b")The text with every "a" changed to "b"

Example

java
public class Main {
  public static void main(String[] args) {
    String city = "Karachi";

    System.out.println(city.length());
    System.out.println(city.toUpperCase());
    System.out.println(city.charAt(0));
    System.out.println(city.indexOf("chi"));
    System.out.println(city.substring(0, 4));
  }
}
Output
7
KARACHI
K
4
Kara

Positions (indexes) in a string start at 0, not 1. In "Karachi", K is at index 0 and the last i is at index 6.

Joining Strings

You can join strings with + or with concat():

Example

java
public class Main {
  public static void main(String[] args) {
    String first = "Ayesha";
    String last = "Khan";
    System.out.println(first + " " + last);
    System.out.println(first.concat(last));

    int roll = 42;
    System.out.println("Roll no: " + roll);
  }
}
Output
Ayesha Khan
AyeshaKhan
Roll no: 42

When you join a string and a number, Java turns the number into text. Be careful: "1" + 2 + 3 gives "123", but 1 + 2 + "3" gives "33", because Java works from left to right.

Comparing Strings

Use equals() to check if two strings have the same text. Do not use == for strings, because it checks whether they are the same object in memory.

Example

java
public class Main {
  public static void main(String[] args) {
    String password = "pak123";
    String typed = "PAK123";

    System.out.println(password.equals(typed));
    System.out.println(password.equalsIgnoreCase(typed));
  }
}
Output
false
true

Special Characters

Use a backslash \ to put special characters inside a string:

CodeResult
\"Double quote
\\Backslash
\nNew line
\tTab

Example

java
System.out.println("He said \"Shukriya\"\nand left.");
Output
He said "Shukriya"
and left.

Exercise

Exercise

What does "Lahore".length() return?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp