Strings in Java
Strings are used to store textual data. The text to be stored in a string variable is enclosed in double quotation marks.
Strings Concatenation
String concatenation is the process of joing two strings with "+" operator or by using concat() method.
String Methods
| Name | Description | Code |
|---|---|---|
| length() | int length = "Java Programming".length(); | finds the length of string |
| indexing() | char firstChar = "Java".charAt(0), secondChar = "Java".charAt(1); | accesses characters of a string by index. |
| equals() | boolean isEqual = "hello".equals("Hello"); | compares strings for equality. |
| equalsIgnoreCase() | boolean isEqualIgnoreCase = "hello".equalsIgnoreCase("Hello"); | for case-insensitive comparison. |
| trim() | String trimmedText = " Java is fun! ".trim(); | removes leading and trailing spaces. |
| replace() | String replacedText = " Java is fun! ".replace("Java", "Python"); | replaces one text with other. |
| split() | String[] words = " Java is fun! ".split(" "); | splits the string into an array of words |
| concat() | String result = "Hello".concat(" ").concat("World"); | joins two or more strings. |
| substring() | String sub2 = "Hello, World!".substring(0, 5); | extracts portion of a strings. |
| toUpperCase() | String upperCaseText = "Hello, World!".toUpperCase(); | converts string to upper case. |
| toUpperCase() | String lowerCaseText = "Hello, World!".toLowerCase(); | converts string to upper case. |
There are different escape characters in Java, which are used alongwith strings. They are listed in printing output section.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP
Sign in to track your progress and earn XP!
Exercise 1 of 2Medium
How are strings terminated in C?
15 XP~3 min
Exercise 2 of 2Easy
To find the length of a string, we use the ___ function.
10 XP~2 min