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
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
Now Reading
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
Java uses a string method to create, modify, and otherwise work with input strings because strings are conceptualized as objects in Java. A series of characters encased in double quotes is referred to as a string in Java. A fragment of another string is referred to as a substring in Java.
This tutorial will explore what substring in Java means, its types, usage, workings, syntax, and examples.
A substring in Java is a string segment that may be obtained by calling the substring() function. A continuous sequence of characters from the original string can be used to construct a new string using this method, a built-in method of the String class in Java. The starting and ending sets of the chosen substring inside the original string are specified by one or two integer parameters sent to Java's substring() function.
The starting location of the substring is the sole argument needed in the first variant of the substring() function. It takes the substring and extracts it from the starting point of the string to the end at the specified place. The starting and ending locations of the substring must be specified as two parameters in the second variant of the substring() function. It takes the first parameter position as the start point and ends right before the second parameter position.
Remember that the substring() function creates a new string that includes the characters of the requested substring. No changes are made to the original string.
A substring in Java is a section of a string that has been extracted using the substring function. It is a brand-new string with a continuous run of the characters from the first string. The requested substring's start and end indexes are the two arguments that the built-in substring method in Java requires.
Let's look at an illustration to see how the substring() technique works. Let's say we want to extract the substring "everyone" from the text "Good morning everyone":
Here is an example Java application for the substring:
Here is an example Java application for the string.split():
The substring() technique has two variations. Getting a substring from a string after a particular word in Java is returned by this method, which has two variations. The substring stretches from the character at the supplied index to the string's last character.
In this example, a string str with the phrase "Good morning, everyone" is present. Using the substring technique, we take a substring() out of the original string. In this scenario, the substring is "everyone" since we begin at position 13 (which is equivalent to the letter "E" in this case) and end at place 21 (which is equivalent to the letter "e" in this case).
There are two variations of this function, which produces a new string that is a substring of the original string. The substring starts at the character at the given index and goes to the end of the string or up to endIndex - 1 if the second parameter is provided.
This example contains a string with the phrase "This is an example" in it. We use the substring(begIndex, endIndex) method to separate a substring from the original text. The begIndex and endIndex arguments specify the starting and ending positions of the substring, respectively (inclusive and exclusive). If we start at position 10 (which is equivalent to the letter "E" in this case) and stop at position 18 (which is equivalent to the letter "e" in this case), the resulting substring will be "example."
Here are some other Java-based programs that handle exceptions and have corner cases:
When trying to access a file that doesn't exist or can't be accessed, a FileNotFoundException error message appears. Using a try-catch block, we can manage this exception. Here's an illustration:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
File file = new File("file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
The file "file.txt" in this example is nonexistent. A FileNotFoundException is raised when we attempt to read the information inside of this file using the Scanner class. The message "File not found!" is printed when we handle this error using a try-catch block.
When we attempt to convert a class to a type incompatible with the object's real type, we see a ClassCastException. Using a try-catch block, we can cope with this exception. Here's an illustration:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = "Hello World";
try {
Integer num = (Integer) obj;
System.out.println(num);
} catch (ClassCastException e) {
System.out.println("Cannot cast to Integer!");
}
}
}
A ClassCastException will be raised when a string object, obj, is attempted to be converted to an integer type with the (Integer) operator. Try-catch blocks handle this error, and "Cannot cast to Integer!" is printed.
Java's implementation of integer division generates an integer quotient and tosses the remainder. Corner situations like dividing by zero and overflow must be considered when performing division with an integer type. Here's an illustration:
public class IntegerDivisionExample {
public static void main(String[] args) {
int num1 = 2147483647; // maximum value of int
int num2 = -1;
try {
int result = num1 / num2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero or integer overflow!");
}
}
}
In this example, we have two integers, num1, and num2, where num1 is the maximum value of int and num2 is -1. We try to perform the division of num1 by num2, which will result in an ArithmeticException due to integer overflow. We handle this exception using a try-catch block and print a message "Cannot divide by zero or integer overflow!".
Java string methods are often used to take off a specific string section. This approach comes in two different forms:
This variation produces a new string that is a substring of the original text, beginning at the startIndex position supplied and continuing until the end of the original string.
In the above example, the substring begins at index 13 of the original string ("E") and contains all characters from there to the string's end.
This variation provides a new string that is a substring of the original content, starting at the startIndex position and going all the way to the endIndex position but not incorporating it.
The substring in the example above begins at index 0 ("G") and ends at index 12("g"). However, the character at index 12 is not a part of the substring.
To take a section of a specified string, use Java's substring() method. The function generates a new string that contains a segment of the original string, beginning at the provided index and ending at the specified index. This article will examine the Java substring() function's internal implementation.
public String substring(int startIndex) Example : System.out.println(" Substring starting from index 13: "+ s.substring(13));// Everyone
public String substring(int startIndex, int endIndex) Example : System.out.println(" Substring starting from index 0 to 12: "+ s.substring(0,12));// Good morning
StartIndex and endIndex are the two inputs for the substring() function. The substring's starting index is defined by the startIndex option. It defines the substring's ending index and is an optional argument called endIndex. If endIndex is left blank, the substring will begin at the startIndex index and go to the end of the main string.
Java's String class has an implementation of the substring() method. The Java Virtual Machine (JVM) produces a new string object and transfers the necessary characters from the old string object to the new string object when the substring() method is invoked on a string object.
The function only accepts the startIndex input in the first implementation. The startIndex is first verified as valid by the function. An exception called StringIndexOutOfBoundsException is issued if the startIndex is either larger than or equal to the length of the original string.
Numerous applications implement the Java substring methods.
1. Removing Prefixes or Suffixes: The Java approach uses the substring to eliminate prefixes and suffixes. For instance, here is an example showing how to extract the greeting from the provided text:
2. Parsing Strings: Here is an example of how to parse texts and extract particular elements or data using the substring methods. The example uses the substring technique to separate the year from a date original string.
3. Extracting Portions of Strings: Extracting particular sections of a string is one of substring()'s main purposes. For example, you could isolate a specific passage of a longer text or extract a person's initial name from their complete name.
The two substring() technique variations are:
Understanding the substring() function is crucial for efficient string manipulation in various computer languages, including Java. Using its many versions, developers can extract substrings based on the precise beginning and ending indices or relative locations.
With the ability to remove the initial character, extract a specific range, or get substrings from the end of a string, the substring() function provides variety and flexibility in extracting parts of strings. Developers may improve their string handling abilities and successfully handle a variety of programming difficulties by understanding the principles and uses of the substring() technique.
1. How to find length of substring in Java?
The substring stretches from the character at beginIndex to that at endIndex. Therefore, (endIndex - beginIndex) is the length of the substring.
2. What is a Substring in Javascript?
Substring is a built-in function in Javascript frequently used to return a portion of a given string so that smaller strings may be made out of the larger string. Because Javascript strings are immutable, the original string is preserved, and a new string is returned each time. It doesn't modify or manipulate the original string in any way.
3. What is substring() in SQL?
In SQL, the substring function extracts characters from a given string. With this function, you can extract any quantity of substrings from a single text.
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...