Saturday, November 16, 2024

Common String methods in Java

Almost all programming languages use Strings I'm sure. In Java, they are used a lot, and the language even made Strings it's own class. So, unlike other data types like `int` or `boolean`, Java's String data type is actually an object which is why we capitalize it when initiating a string.

Since String is an object, it also comes with it's own String methods. A full list of String methods can be found at this W3Schools link: https://www.w3schools.com/java/java_ref_string.asp

Below are some common ones:

  • length(): returns the length of a String as an int
  • concat(arg): returns a combination of String1 and the arg of the method - which could be another String or a mixture of blank spaces and a String.
    • String1.concat(" " + String2); as an example of multiple values in the argument
  • indexOf(arg): returns the index of the argument given
  • charAt(arg): returns a character at index arg
  • equals(arg): you cannot use the == operator to compare two strings in Java, so you need to use this method instead. This is case sensitive, but you can also use equalsIgnoreCase() as an alternative if you don't care about the case (or don't want to for the sake of your program's objective).
  • substring(arg, [arg2]): this returns a String that falls in line with the argument(s) you give the method signature. If you give just one argument, it will return a String that starts at that index all the way to the end of the String. If you declare two arguments, it will return a String that starts at the index of the first argument and will go up to but not including argument two.
  • toUpperCase()/toLowerCase(): these return a string in all caps or all lowercase. This is good for situations where you want to make sure case is ignored and you just want to compare the characters in the String.

No comments:

Post a Comment