All about String in Java

  • The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
  • ” ” is reserved for string and ‘ ‘ is reserved for a character.
  • Strings are constant; their values cannot be changed after they are created. {Strings are immutable in Java}
  • Java String Pool:
    • In Java, the JVM maintains a string pool to store all of its strings inside the memory.
    • The string pool helps in reusing the strings.
      • If the string already exists, the new string is not created.
      • Instead, the new reference, example points to the already existing string (Java).
      • If the string doesn’t exist, a new string will be created.

How to declare a String in Java?

String s1 = "HelloWorld";

String ” ” vs. char ‘ ‘

String s1 = "123abc";
char c1 = 'c';

do we need to import String Library?

No.

Display String

System.out.println(s1);

Take a string from the user

Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();

Size/length of a String

System.out.println(s1.length());

Access elements using index and loop through the string

System.out.println(s1.charAt(0));
		
for (int i = 0; i < s1.length(); i++) {
    System.out.println(s1.charAt(i));
}

Add two strings

String first = "first";
String second = "second";
		
//technique-1
second = first + second;
System.out.println(second);

//technique-2
first.concat(second);
System.out.println(first);
System.out.println(first.concat(second));

Create substrings

System.out.println(first.substring(2,first.length()));
System.out.println(first.substring(2);

Char Array vs. String

char[] arr = {'a', 'b','c'};
String s1 = "abc";

arr[0] = 'b';
//s1.charAt(0) = 'b';

s1 = s1 + 'd';//how?

char[] charArray = s1.toCharArray();

String s2 = charArray.toString();

String s3 = "Hello there Hello there";
String[] words = s3.split(" ");

for(int i=0; i<words.length; i++) {
	System.out.println(words[i]);
}

Compare two strings

String s1 = "first";
String s2 = "first";
		
System.out.println((s1==s2));
System.out.println(s1.equals(s2));
		
s2  = new String("first");
System.out.println((s1==s2));
System.out.println(s1.equals(s2));

s1 = "Hello";
s2 = "HellO";

System.out.println(s1.equals(s2));
System.out.println(s1 == s2);		

if(s1.compareTo(s2) == 0){
    System.out.println("Strings are equal");
}

Thanks and Regards,

2 Comments.

Leave a Reply

Your email address will not be published. Required fields are marked *