DEV Community

Vidya
Vidya

Posted on

String in java

Definition
A String in Java is a sequence of characters used to store text like names, sentences, etc.

👉 In Java, a string is an object of the class java.lang.String
👉 Strings are immutable (cannot be changed after creation)

How String is Stored in memory

String a = "Java";
String b = "Java";
String c = new String("Java");

Example

  String name = "Hello";
Enter fullscreen mode Exit fullscreen mode

Important String Methods

1.length() → find number of characters

String str = "Java";
System.out.println(str.length());   // 4

Enter fullscreen mode Exit fullscreen mode

2. toUpperCase() → convert to uppercase

String str = "hello";
System.out.println(str.toUpperCase());   // HELLO
Enter fullscreen mode Exit fullscreen mode

3. toLowerCase() → convert to lowercase

        String str = "JAVA";
        System.out.println(str.toLowerCase());   // java

Enter fullscreen mode Exit fullscreen mode

4. charAt(index) → get character at position

       String str = "Java";
       System.out.println(str.charAt(2));   // v

Enter fullscreen mode Exit fullscreen mode

5. equals() → compare two strings

String a = "java";
String b = "java";

System.out.println(a.equals(b));   // true
Enter fullscreen mode Exit fullscreen mode

6. equalsIgnoreCase() → compare ignoring case

 String a = "JAVA";
 String b = "java";

 System.out.println(a.equalsIgnoreCase(b));   // true
Enter fullscreen mode Exit fullscreen mode

7. contains() → check if string contains something

String str = "Hello Java";
System.out.println(str.contains("Java"));   // true
Enter fullscreen mode Exit fullscreen mode

8. substring() → get part of string

 String str = "Programming";
 System.out.println(str.substring(0, 4));   // Prog
Enter fullscreen mode Exit fullscreen mode

9. replace() → replace characters

 String str = "Java";
 System.out.println(str.replace("a", "o"));   // Jovo
Enter fullscreen mode Exit fullscreen mode

10. trim() → remove spaces

String str = "  hello  ";
System.out.println(str.trim());   // hello
Enter fullscreen mode Exit fullscreen mode

Top comments (0)