- Different Methodologies in Project Management
- Difference between Soap and Rest | Know more about it
- What is Python array? Learn with examples
- Best Career options after Engineering | Everything You Need to Know [OverView]
- What is list in Python ? All you need to know [ OverView ]
- What is Data Modelling? : All you need to know [ OverView ]
- What are Microservices? : A Complete Guide For Beginners with Best Practices
- What is Python Programming | A Definitive Guide with Best Practices
- All You Need To Know About Python List | A Complete Guide For Beginners with Best Practices
- What Is a Software Developer | Software Developer job description and duties | Everything You Need to Know
- What is Artificial Intelligence Chatbot?
- Kotlin vs Java | Know Their Differences and Which Should You Learn?
- What is Abstraction in Java | Implementations of Abstraction in Java | A Definitive Guide with Best Practices
- What are the Important Data Structures and Algorithms in Python?
- Go vs Python | Know Their Differences and Which Should You Learn?
- Best Python IDEs and Code Editors | Expert’s Top Picks | Everything You Need to Know
- Go Programming Language | Expert’s Top Picks | A Definitive Guide [ OverView ]
- Python Scopes and Their Built-in Functions | Everything You Need to Know | Expert’s Top Picks
- Python String Formatting | A Complete Guide For Beginners [ OverView ]
- Python Serialization | A Complete Guide For Beginners | Learning Guide
- What is .Net FrameWork? Uses and its Benefits | Everything You Need to Know
- What is Quality Assurance ? : A Definitive Guide | Everything You Need to Know [ OverView ]
- What is Spike Testing ? : A Definitive Guide | Expert’s Top Picks | Free Guide Tutorial
- Average Full Stack Developer Salary in India [ For Freshers and Experience ]
- What is WSDL in Web Services ? Expert’s Top Picks | Free Guide Tutorial
- Virtual Instrumentation using Labview | Comprehensive Guide [ Explained ]
- Gradle vs Maven | Know Their Differences and Which Should You Learn?
- Python Sleep Method | Free Guide Tutorial & REAL-TIME Examples
- Kotlin vs Python | A Complete Guide with Best Practices
- Spring Boot vs Spring MVC | Differences and Which Should You Learn?
- IT Engineer Salary in India – How much does one earn?
- What is pip ? and Getting Started with Python pip | All you need to know [ OverView ]
- Node.js Installation on Windows and Ubuntu | Free Guide Tutorial
- Skills Needed for Full Stack Developers | All you need to know [ OverView ]
- What is Axios in React? and Its Uses [ OverView ]
- What is MEAN Stack? All you need to know [ OverView ]
- How to Install Node.JS on Ubuntu | Everything You Need to Know
- Average Annual Salary of a Python Certified Professional – Career Path
- What is Scala Programming? A Complete Guide with Best Practices
- What Is User Input in Python? Expert’s Top Picks
- Interface vs Abstract Class | Difference You Should Know
- Final Year Computer Science Project Ideas | All you need to know [ OverView ]
- Technical Architect | Free Guide Tutorial & REAL-TIME Examples
- Logical Programs in Java | Step-By-Step Process
- C++ vs Java | Difference You Should Know
- What is C Programming? Comprehensive Guide
- What Is a Quality Engineer? ( Everything You Need to Know )
- Python Project Ideas for Beginners | All you need to know
- How to Run Python Scripts? Comprehensive Guide
- Python Operators
- How To Install NumPy in Python?
- Top Software Courses to Get High Paying Jobs
- Loops In Python
- Tips to Avoid Application Rejection
- Top Young App Developers Who Became Millionaires
- Top Technical Courses After Graduation
- Node JS Architecture
- What is PyCharm?
- Resources To Help You Learn Java Programming
- How to Become a Software Engineer?
- Best Programming Languages to Learn in 2020
- Scala vs Python
- How to Become a Full Stack Developer?
- The Most Popular Java Applications Used World-wide
- What is Java String?
- Full Stack Developer vs Front End Developer vs Back End Developer
- Python Collections
- Identifiers in Python
- Dynamic Method Dispatch in Java
- Hadoop Ecosystem
- Method Overloading in Python
- Convert Decimal To Binary In Python
- How To Make A Chatbot In Python?
- How to Input a List in Python?
- Hash Tables and Hashmaps in Python
- Top Python Framework’s
- Python Split Method with Example
- Python Enumerate
- Inheritance in Java
- Init in Python
- Goto Statement in Python
- Literals in Java
- Polymorphism in Oops
- Socket Programming in Python
- Object Class in Java
- Break, Continue, and Pass Statements in Python
- Exception Handling in Java
- Java BASIC Programs
- Different Methodologies in Project Management
- Difference between Soap and Rest | Know more about it
- What is Python array? Learn with examples
- Best Career options after Engineering | Everything You Need to Know [OverView]
- What is list in Python ? All you need to know [ OverView ]
- What is Data Modelling? : All you need to know [ OverView ]
- What are Microservices? : A Complete Guide For Beginners with Best Practices
- What is Python Programming | A Definitive Guide with Best Practices
- All You Need To Know About Python List | A Complete Guide For Beginners with Best Practices
- What Is a Software Developer | Software Developer job description and duties | Everything You Need to Know
- What is Artificial Intelligence Chatbot?
- Kotlin vs Java | Know Their Differences and Which Should You Learn?
- What is Abstraction in Java | Implementations of Abstraction in Java | A Definitive Guide with Best Practices
- What are the Important Data Structures and Algorithms in Python?
- Go vs Python | Know Their Differences and Which Should You Learn?
- Best Python IDEs and Code Editors | Expert’s Top Picks | Everything You Need to Know
- Go Programming Language | Expert’s Top Picks | A Definitive Guide [ OverView ]
- Python Scopes and Their Built-in Functions | Everything You Need to Know | Expert’s Top Picks
- Python String Formatting | A Complete Guide For Beginners [ OverView ]
- Python Serialization | A Complete Guide For Beginners | Learning Guide
- What is .Net FrameWork? Uses and its Benefits | Everything You Need to Know
- What is Quality Assurance ? : A Definitive Guide | Everything You Need to Know [ OverView ]
- What is Spike Testing ? : A Definitive Guide | Expert’s Top Picks | Free Guide Tutorial
- Average Full Stack Developer Salary in India [ For Freshers and Experience ]
- What is WSDL in Web Services ? Expert’s Top Picks | Free Guide Tutorial
- Virtual Instrumentation using Labview | Comprehensive Guide [ Explained ]
- Gradle vs Maven | Know Their Differences and Which Should You Learn?
- Python Sleep Method | Free Guide Tutorial & REAL-TIME Examples
- Kotlin vs Python | A Complete Guide with Best Practices
- Spring Boot vs Spring MVC | Differences and Which Should You Learn?
- IT Engineer Salary in India – How much does one earn?
- What is pip ? and Getting Started with Python pip | All you need to know [ OverView ]
- Node.js Installation on Windows and Ubuntu | Free Guide Tutorial
- Skills Needed for Full Stack Developers | All you need to know [ OverView ]
- What is Axios in React? and Its Uses [ OverView ]
- What is MEAN Stack? All you need to know [ OverView ]
- How to Install Node.JS on Ubuntu | Everything You Need to Know
- Average Annual Salary of a Python Certified Professional – Career Path
- What is Scala Programming? A Complete Guide with Best Practices
- What Is User Input in Python? Expert’s Top Picks
- Interface vs Abstract Class | Difference You Should Know
- Final Year Computer Science Project Ideas | All you need to know [ OverView ]
- Technical Architect | Free Guide Tutorial & REAL-TIME Examples
- Logical Programs in Java | Step-By-Step Process
- C++ vs Java | Difference You Should Know
- What is C Programming? Comprehensive Guide
- What Is a Quality Engineer? ( Everything You Need to Know )
- Python Project Ideas for Beginners | All you need to know
- How to Run Python Scripts? Comprehensive Guide
- Python Operators
- How To Install NumPy in Python?
- Top Software Courses to Get High Paying Jobs
- Loops In Python
- Tips to Avoid Application Rejection
- Top Young App Developers Who Became Millionaires
- Top Technical Courses After Graduation
- Node JS Architecture
- What is PyCharm?
- Resources To Help You Learn Java Programming
- How to Become a Software Engineer?
- Best Programming Languages to Learn in 2020
- Scala vs Python
- How to Become a Full Stack Developer?
- The Most Popular Java Applications Used World-wide
- What is Java String?
- Full Stack Developer vs Front End Developer vs Back End Developer
- Python Collections
- Identifiers in Python
- Dynamic Method Dispatch in Java
- Hadoop Ecosystem
- Method Overloading in Python
- Convert Decimal To Binary In Python
- How To Make A Chatbot In Python?
- How to Input a List in Python?
- Hash Tables and Hashmaps in Python
- Top Python Framework’s
- Python Split Method with Example
- Python Enumerate
- Inheritance in Java
- Init in Python
- Goto Statement in Python
- Literals in Java
- Polymorphism in Oops
- Socket Programming in Python
- Object Class in Java
- Break, Continue, and Pass Statements in Python
- Exception Handling in Java
- Java BASIC Programs
What is Java String?
Last updated on 28th Sep 2020, Artciles, Blog, Software Engineering
Strings in Java
- Strings, which are widely used in Java programming, are a sequence of characters.
- In Java programming language, strings are treated as objects.
- The Java platform provides the String class to create and manipulate strings
Creating a String
There are two ways to create a String in Java
- String literal
- Using new keyword
Subscribe For Free Demo
Error: Contact form not found.
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
- String str1 = “Welcome”;
- String str2 = “Welcome”;
The problem with this approach: As I stated in the beginning that String is an object in Java. However we have not created any string object using new keyword above. The compiler does that task for us it creates a string object having the string literal (that we have provided , in this case it is “Welcome”) and assigns it to the provided string instances.
But if the object already exist in the memory it does not create a new Object rather it assigns the same old object to the new instance, that means even though we have two string instances above(str1 and str2) compiler only created on string object (having the value “Welcome”) and assigned the same to both the instances. For example there are 10 string instances that have same value, it means that in memory there is only one object having the value and all the 10 string instances would be pointing to the same object.
What if we want to have two different object with the same string? For that we would need to create strings using new keyword.
Using New Keyword
As we saw above that when we tried to assign the same string object to two different literals, compiler only created one object and made both of the literals to point the same object.
To overcome that approach we can create strings like this:
- String str1 = new String(“Welcome”);
- String str2 = new String(“Welcome”);
In this case compiler would create two different object in memory having the same string.
Example
- public class Example{
- public static void main(String args[]){
- //creating a string by java string literal
- String str = “welcome”;
- char arrch[]={‘h’,’e’,’l’,’l’,’o’};
- //converting char array arrch[] to string str2
- String str2 = new String(arrch);
- //creating another java string str3 by using new keyword
- String str3 = new String(“Java String Example”);
- //Displaying all the three strings
- System.out.println(str);
- System.out.println(str2);
- System.out.println(str3);
- }
- }
Output:
welcome
hello
Java String Example
Java String Methods
Here are the list of the methods available in the Java String class.
1.char charAt(int index)
- It returns the character at the specified index.
- Specified index value should be between 0 to length() -1 both inclusive.
- It throws IndexOutOfBoundsException if index<0||>= length of String.
2.boolean equals(Object obj)
Compares the string with the specified string and returns true if both matches else false.
3.boolean equalsIgnoreCase(String string)
- It works same as equals method but it doesn’t consider the case while comparing strings.
- It does a case insensitive comparison.
4.int compareTo(String string)
This method compares the two strings based on the Unicode value of each character in the strings.
5.int compareToIgnoreCase(String string)
Same as CompareTo method however it ignores the case during comparison.
6.boolean startsWith(String prefix, int offset)
It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
7.boolean startsWith(String prefix)
It tests whether the string is having specified prefix, if yes then it returns true else false.
8.boolean endsWith(String suffix)
Checks whether the string ends with the specified suffix.
9.int hashCode()
It returns the hash code of the string.
10.int indexOf(int ch)
Returns the index of first occurrence of the specified character ch in the string.
11.int indexOf(int ch, int fromIndex)
Same as indexOf method however it starts searching in the string from the specified fromIndex.
12.int lastIndexOf(int ch)
It returns the last occurrence of the character ch in the string.
13.int lastIndexOf(int ch, int fromIndex)
Same as lastIndexOf(int ch) method, it starts search from fromIndex.
14.int indexOf(String str)
This method returns the index of first occurrence of specified substring str.
15.int lastindexOf(String str)
Returns the index of last occurrence of string str.
16.String substring(int beginIndex)
It returns the substring of the string. The substring starts with the character at the specified index.
17.String substring(int beginIndex, int endIndex)
Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
18.String concat(String str)
Concatenates the specified string “str” at the end of the string.
19.String replace(char oldChar, char newChar)
It returns the new updated string after changing all the occurrences of oldChar with the newChar.
20.boolean contains(CharSequence s)
- It checks whether the string contains the specified sequence of char values.
- If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
21.String toUpperCase(Locale locale)
Converts the string to upper case string using the rules defined by specified locale.
22.String toUpperCase()
Equivalent to toUpperCase(Locale.getDefault()).
23.public String intern()
This method searches the specified string in the memory pool and if it is found then it returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.
24.public boolean isEmpty()
- This method returns true if the given string has 0 length.
- If the length of the specified Java String is non-zero then it returns false.
25.public static String join()
This method joins the given strings using the specified delimiter and returns the concatenated Java String
26.String replaceFirst(String regex, String replacement)
It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
27.String replaceAll(String regex, String replacement)
It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
28.String[] split(String regex, int limit)
It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
29.String[] split(String regex)
Same as split(String regex, int limit) method however it does not have any threshold limit.
30.String toLowerCase(Locale locale)
It converts the string to lower case string using the rules defined by given locale.
31.public static String format()
This method returns a formatted java String
32.String toLowerCase()
Equivalent to toLowerCase(Locale. getDefault()).
33.String trim()
Returns the substring after omitting leading and trailing white spaces from the original string.
34.char[] toCharArray()
Converts the string to a character array.
35.static String copyValueOf(char[] data)
It returns a string that contains the characters of the specified character array.
36.static String copyValueOf(char[] data, int offset, int count)
Same as above method with two extra arguments – initial offset of subarray and length of subarray.
37.void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
38.static String valueOf()
This method returns a string representation of passed arguments such as int, long, float, double, char and char array.
39.boolean contentEquals(StringBuffer sb)
It compares the string to the specified string buffer.
40.boolean regionMatches(int srcoffset, String dest, int destoffset, int len)
It compares the substring of input to the substring of specified string.
41.boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len)
Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
42.byte[] getBytes(String charsetName)
It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
43.byte[] getBytes()
This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
44.int length()
It returns the length of a String.
45.boolean matches(String regex)
It checks whether the String is matching with the specified regular expression regex.
46.int codePointAt(int index)
It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.
