Strings are very important part of any programming language. Same is the case with Java. There are so many String methods in String class and it will become difficult to explain all of them. I am mainly focusing on some methods which are worthful to beginners. I will also explain some basics about Strings here which makes Strings easy to understand. So, lets begin.
Basics about Strings in Java
1. You can create Strings in various ways:-
a) By Creating a String Object
String s=new String(“abcdef”);
b) By just creating object and then referring to string
String a=new String();
c) By simply creating a reference variable
2. All the strings gets collected in a special memory are for Strings called ” String constant pool”.
3. JVM does all string related tasks to avoid the memory wastage for more info on this refer “How JVM Handles strings”.
4. Every String is considered as a string literal.
5. Strings are immutable only reference changes string never changes. New string literals are referenced when there is any manipulation. The old string gets lost in the preceding. look below
Important String Methods
Following are most commonly used methods in the String class.
1. public String concat(String s)
This method returns a string with the value of string passed in to the method appended to the end of String which used to invoke the method.
System. out. println(s.concat(“hijlk”));
Note:-Always use assignment operator in case of concat operator otherwise concat will be unreferenced and you will get old String. example
System. out. println(s);
It will present output as ” abcdefg ” different than what we have expected. So always be careful in using the assignment operator in String method calls.
2. public charAt(int index)
This method returns a specific character located at the String’s specific index. Remember, String indexes are zero based. Example
String s=”Alfanso Mango”;
System. out. println(s.charAt(0));
About the Author:
Vaibhav Pandey got offered employment from an Indian Multinational IT Company. He is 21 years old. He has a huge interest in Java programming and has liked it from his study days. Vaibhav loves to blog and share his experiences and thoughts. He now resides in Lucknow, a state capital in India. Check out his blog at http://javatutorialsworld.blogspot.com.