Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
Now Reading
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
The concept of string in Java is taught in any beginner Java programming class. It is an instrumental concept in different coding scenarios and a must-have in your Java knowledge arsenal. This tutorial provides an in-depth guide to the various concepts of strings in Java.
Java uses strings for various tasks, such as text data storage and manipulation, user input handling, file processing, network connection, and more. Java provides many inbuilt functions to work on strings.
Understanding the concept of strings is crucial for mastery of Java programming.
A string in Java is a data type used to store a sequence of characters. It acts the same way as an array does in Java.
There are two ways we can create strings in Java. Let us look at the Java string syntax:
Example syntax:
String myString = "Hello, World!";
myString = "Java Programming";
Example syntax:
String myString = new String("Hello, World!");
myString = new String("Java Programming");
A class in Java refers to a group of objects with similar properties. Different objects in a class may show different attributes and properties described by the class. A class is also called a blueprint for the creation of objects.
An interface in Java can be called the blueprint of a class and has fields like static, final, and public. The method body can not be defined in Java. An interface, unlike an abstract class, can not be instantiated.
Interfaces are used in Java for the following reasons:
Let us look at a Java string program with output.
Example:
import java.util.StringTokenizer;
public class StringInterfacesAndClassesExample {
public static void main(String[] args) {
// Using CharSequence interface
CharSequence charSequence = "Hello, World!";
int length = charSequence.length();
char firstChar = charSequence.charAt(0);
CharSequence subSequence = charSequence.subSequence(7, 12);
System.out.println("Length: " + length);
System.out.println("First Character: " + firstChar);
System.out.println("Subsequence: " + subSequence);
// Using StringBuilder class
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello");
stringBuilder.append(" ");
stringBuilder.append("World!");
String result = stringBuilder.toString();
System.out.println("StringBuilder result: " + result);
// Using StringTokenizer class
String sentence = "The quick brown fox jumps over the lazy dog";
StringTokenizer tokenizer = new StringTokenizer(sentence);
System.out.println("Tokenized sentence:");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
}
}
In this example, we create an instance of CharSequence and demonstrate its length(), charAt(), and subSequence() methods. Then, we use the StringBuilder class to efficiently concatenate strings. Finally, we tokenize a sentence using the StringTokenizer class to split it into individual words.
A sequence of characters is represented with the help of the CharSequence interface in Java. It is implemented with the help of
The string is immutable in Java, meaning it can not be modified. StringBuffer and StringBuilder classes are used for mutable strings.
The StringBuilder and StringBuffer classes provide mutable sequences of characters. They are commonly used for efficient string concatenation or manipulation.
The StringTokenizer class allows you to tokenize a string into individual tokens based on a specified delimiter.
Strings in Java are stored in a heap storage area called the string pool. String Intern pool and String Constant pool are other names of String pool. Java String class maintains the string pool and is empty by default, just like any other object storage.
When you initialize a new string, JVM checks if the same string is already present in the string pool before allotting space to it. If yes, it just stores a reference to the previously stored string to save resources.
In Java 8, the String pool was transferred from the Permanent Generation (PermGen) area to the standard heap area. This modification was developed to address problems with PermGen space, a fixed-size memory space that holds class metadata, interned strings, and other JVM-specific information.
A string works the same way an array of characters do. The String class in Java provides a lot of default methods like concat(), compare(), replace(), compareTo(), substring(), and more. With the help of these predefined functions, it is very convenient to operate on strings in Java.
Strings in Java are an immutable data type that stores a sequence of characters. Here we will discuss an example.
Let us look at this piece of code
String s1 = “computer”;
Here, the name of the string is s1, and the value stored in it is “computer.” The compiler treats the string like an array and puts the characters of “computer” in different memory locations in a series. If we take this example, the character ‘c’ is stored at position 0, ‘o’ is stored at position 1, and so on.
Here is an example of using strings in Java:
public class String1 {
public static void main(String[] args) {
String message = "Hello, World!";
int length = message.length();
System.out.println("Length: " + length);
String name = "Alice";
String greeting = message + " My name is " + name;
System.out.println("Greeting: " + greeting);
String substring = message.substring(7, 12);
System.out.println("Substring: " + substring);
String uppercase = message.toUpperCase();
String lowercase = message.toLowerCase();
System.out.println("Uppercase: " + uppercase);
System.out.println("Lowercase: " + lowercase);
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println("Comparison result: " + result);
String sentence = "I love programming";
String[] words = sentence.split(" ");
System.out.println("Words: ");
for (String word : words) {
System.out.println(word);
}
String paddedString = " Hello ";
String trimmedString = paddedString.trim();
System.out.println("Trimmed string: " + trimmedString);
String replacedString = message.replace('o', 'a');
System.out.println("Replaced string: " + replacedString);
}
}
There are numerous string methods in Java which make Java programming a lot easier. Let us look at some string methods in Java with examples.
The int length() method is used to measure the size of the string or how many characters the string consists of. The method has an integer return type and always returns the output in a whole number.
The char charAt(int index) method returns the character present at a specific point in an array. This method has a character return type and always returns characters. The position at which the method returns the character can be defined in the variable named index by the programmer.
The String concat(String string1) method adds a string at the end of another string. Here, it will add the string string1 at the end of another pre-existing desired string.
This method has a string return type and thus returns a string.
This method is used to extract a substring from an already declared string. We can derive the new string from a desired start point by mentioning it in the variable int beginIndex. If the endpoint is not specified at int endIndex, the method assumes the end to be till the end of the array. This method has a string return type.
The String equals(String anotherString) method is used to compare whether or not two strings have the same contents. If they are the same, the method returns true. Otherwise, it returns false. It is a boolean-type method and only returns true or false.
The contains() method is used to check if the provided substring is present inside the parent string we are checking in. The user can put the value of what they want to search in the substring variable in Java. This method also has a boolean data type and only returns true or false.
The String class, introduced in Java 8, contains a static method called String.join(). With a designated delimiter, you can concatenate multiple strings.
A static method in Java's String class is int compareTo(String string1, String string2). It performs a lexical comparison between two strings and outputs an integer value representing the relative order of the strings.
The String class in Java contains the method toUpperCase(). It creates a new string with the uppercase representation after changing every character in a string to uppercase. The return type of this method is a string.
Similarly, The String class in Java includes a built-in method called toLowerCase(). It gives back a new string that has all the characters in lowercase. This method also has the return type string.
The trim() method in Java removes any leading or trailing whitespaces in the string. This means the trim() method checks the beginning and end of the string. It stops scanning when it finds any white spaces from either end of the string. It does not hamper the orientation of spaces inside a string but only on the extremities.
The String class in Java includes a built-in method called replace(char oldChar, char newChar). Here, oldChar is a variable that pre-exists in the string and is replaced by newChar, which is user-defined. All instances of the oldChar are replaced with the newChar in the new string returned. This method also has a string return type.
Concatenating means linking multiple things together. Similarly, when we concatenate multiple strings in Java, they make a new string with the combination of two or more previously defined strings.
We can concatenate strings in Java using two methods:
Java format strings are created using the String.format() method. Java's String.format() function and the printf() method from the System.out or PrintStream class are used to create format strings. By mixing static text with placeholders for values that will be inserted during runtime, format strings enable you to build dynamic strings.
A backslash (/) is used in Java to indicate the escape character. It is applied when a string literal has to contain special characters or escape sequences. Here are a few often utilized escape mechanisms:
A common question most beginner-level Java learners face is, “ Why string is immutable in Java?”
A string in Java, by default, is an immutable data type in Java. This means the contents in a string cannot be altered in the same instance of the string. A new string instance is created in the string pool whenever we alter or mutate a string. The state of a mutable class can also not be changed.
Objects in Java whose values can be changed after initialization in Java are called mutable objects. The field, state, and values can be changed; while doing so, no new object will be created. It will alter the value of the existing object. StringBuilder() and StringBuffer() in Java are examples of methods by which mutable strings can be created.
Strings are essential to Java programming since they are the primary data type for textual information representation. Throughout this tutorial, we have examined the main characteristics and capabilities of strings in Java, learning more about their adaptability and significance. This should serve as the foundation for you to master more advanced Java programming concepts.
1. What is string interning in Java?
String interning in Java refers to storing string literals in a string pool to save the system's resources.
2. How do you compare strings in Java?
You can compare strings in Java using the compareTo() and equals() methods.
3. What are some best practices for working with strings in Java?
Using StringBuilder and being mindful of memory usage is a good practice for using strings in Java.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...