Strings and Math

String Methods:

length()
Description: Returns the number of characters in a string.
Example:
String name = "Phoenix";
System.out.println(name.length()); // 7
This counts all characters in the string, including letters.

substring(start, end)
Description: Returns part of the string from the start index up to (but not including) the end index.
Example:
String name = "Phoenix";
System.out.println(name.substring(0,3)); // "Phe"
This takes characters at index 0, 1, and 2.

substring(start)
Description: Returns the substring from the given index to the end.
Example:
String name = "Phoenix";
System.out.println(name.substring(3)); // "enix"
This starts at index 3 and continues to the end of the string.

indexOf(str)
Description: Returns the index of the first occurrence of a character or substring.
Example:
String name = "Phoenix";
System.out.println(name.indexOf("o")); // 2
This finds the first position where "o" appears.

equals(str)
Description: Compares two strings for equality.
Example:
String a = "hello";
String b = "hello";
System.out.println(a.equals(b)); // true
This checks if both strings have the same content.

Always use equals() instead of == when comparing strings. This is because the == operator compares object references (memory addresses), not the actual content of the strings.

compareTo(str)
Description: Looks at two strings character by character from left to right and compares their Unicode (ASCII) values.

It returns:

  • 0 → if the strings are exactly the same

  • Negative number → if the first string comes before the second

  • Positive number → if the first string comes after the second
    Example:
    System.out.println("apple".compareTo("banana")); // negative number
    This returns a negative number because "apple" comes before "banana".

toLowerCase()
Description: Converts all characters to lowercase.
Example:
System.out.println("Hi".toLowerCase()); // "hi"
This changes all letters to lowercase.

toUpperCase()
Description: Converts all characters to uppercase.
Example:
System.out.println("Hi".toUpperCase()); // "HI"
This changes all letters to uppercase.

Math Methods

Math.pow(a, b)
Description: Raises a number to a power. Returns a double.
Example:
System.out.println(Math.pow(2,3)); // 8.0
This calculates 2 to the power of 3.

Math.sqrt(x)
Description: Returns the square root of a number. Returns a double.
Example:
System.out.println(Math.sqrt(16)); // 4.0
This finds the square root of 16.

Math.abs(x)
Description: Returns the absolute value.
Example:
System.out.println(Math.abs(-5)); // 5
This removes the negative sign.

Math.random()
Description: Generates a random decimal between 0 (inclusive) and 1 (exclusive).
Example:
System.out.println(Math.random()); // example: 0.37
This produces a random decimal value between 0 and 1.

General Formula for Math.random()

(int)(Math.random() * ((max - min) + 1)) + min

This returns a random integer between min (inclusive) and max (inclusive).