Course Content
Java Basics
Java Basics
Basic Methods In String Part 1
How to Work with Strings Using Methods?
As mentioned earlier in the "Array" section, we won't delve into what methods are and how to create them. We will discuss this later in a separate course. For now, it will be sufficient for you to know that methods are invoked using a dot (.
) after the String
variable we created.
Let's take a look at several commonly used methods:
length()
: Returns the length of the string;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; int l = s.length(); System.out.println(l); } }
charAt(int index)
: Returns the character at the specified index in the string;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; char c = s.charAt(2); System.out.println(c); } }
substring(int beginIndex)
: Returns a new string that is a substring of the original string, starting from the specified index;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; String s1 = s.substring(3); System.out.println(s1); } }
substring(int beginIndex, int endIndex)
: Returns a new string that is a substring of the original string, starting from thebeginIndex
and ending at theendIndex-1
;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; String s1 = s.substring(3, 5); System.out.println(s1); } }
toLowerCase()
: Converts the string to lowercase;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "sTRiNg"; String s1 = s.toLowerCase(); System.out.println(s1); } }
toUpperCase()
: Converts the string to uppercase;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; String s1 = s.toUpperCase(); System.out.println(s1); } }
contains(CharSequence sequence)
: Checks if the string contains the specified sequence of characters;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; boolean b = s.contains("a"); System.out.println(b); } }
replace(char oldChar, char newChar)
: Replaces all occurrences of the specified oldChar with the newChar;
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string is good"; String s1 = s.replace('i', 'f'); System.out.println(s1); } }
toCharArray()
: Converts the string to a character array.
Main
package com.example; public class Main { public static void main(String[] args) { String s = "string"; char[] array = s.toCharArray(); for (char element : array) { System.out.print(element + " "); } } }
The list turned out to be quite extensive, so we'll continue exploring String methods in the next chapter.
In the following chapter, we will provide practical examples of using these methods.
Everything was clear?