Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

String handling functions using Java

Adithya Challa

A string is a collection of characters. In Java, a string is an object that represents a collection of objects. A string is a predefined class used to create string objects. It is an immutable object, which means it can’t be updated once created.

The string class has a set of built-in-methods, defined below.

  • charAt(): It returns a character at a specified position.
  • equals(): It compares the two given strings and returns a Boolean, that is, True or False.
  • concat(): Appends one string to the end of another.
  • length(): Returns the length of a specified string.
  • toLowerCase(): Converts the string to lowercase letters.
  • toUpperCase(): Converts the string to uppercase letters.
  • indexOf(): Returns the first found position of a character.
  • substring(): Extracts the substring based on index values, passed as an argument.

Code

class Main{
  public static void main(String []args)
  {
    String s1="Adithya";
    String s2="Adithya";
    String s3="Adi";
    boolean x=s1.equals(s2);
    System.out.println("Compare s1 and s2:"+x);
    System.out.println("Character at given position is:"+s1.charAt(5));
    System.out.println(s1.concat(" the author"));
    System.out.println(s1.length());
    System.out.println(s1.toLowerCase());
    System.out.println(s1.toUpperCase());
    System.out.println(s1.indexOf('a'));
    System.out.println(s1.substring(0,4));
    System.out.println(s1.substring(4));  
  }
}

Code explanation

  • Lines 4-6: We create three strings s1, s2, and s3.

  • Line 7: We compare two strings s1 and s2 using equals() function.

  • Line 9: We find the character at position 5 in string s1 using charAt() function and print it.

  • Line 10: We concatenate two strings using the concat() function.

  • Line 11: We find the length of string s1 using length() function.

  • Line 12: We convert the string s1 to lowercase letters using toLowerCase() function.

  • Line 13: We convert the string s1 to uppercase letters using toUpperCase() function.

  • Line 14: We find the index of a in string s1 using indexOf() function.

  • Lines 15-16: We find the substring by passing indexes as parameters to the substring() function.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring