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
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
Now Reading
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
Welcome to this tutorial on charAt() in Java. This comprehensive guide aims to walk you through the fundamentals and advanced usage of `charAt()`, enabling you to harness the power of character-level operations on strings.
We will look into charAt() in Java examples and learn how to retrieve characters by index, handle edge cases, and apply this knowledge to solve real-world programming challenges.
The charAt() in Java is useful for manipulating and extracting individual characters from a string. Strings are essential data types in any programming language since they enable you to interact with text-based data in your programs. Double quotation marks ("") are used to encapsulate strings in Java.
Using charAt() in Java is a handy method for extracting certain characters from a string in Java programming. This technique lets you access certain characters inside a string depending on their index locations. The charAt() function comes in handy whether you're looking for a specific character or need to carry out character-based activities.
Java's charAt() function retrieves the character's char value from a string at the provided or given index. The index value must be in the range of 0 and length()-1. The initial character's index is 0, followed by character number one, and so on.
Here is the syntax for using the charAt() method:
char charAt(int index)
The charAt() method is a member of the String class, so you need to call it on an instance of the String class. It takes an integer parameter index, which represents the character's position you want to retrieve.
For example:
str.charAt(5);
We would use the above syntax to retrieve the 6th character from a string.
Now, let us check out a working example:
public class upGradTutorials {
public static void main(String[] args) {
String str = "upGrad.";
char result = str.charAt(3);
System.out.println(result); // Output: r
}
}
In the main method, we declare a String variable str and assign it the value "upGrad.". Then we use the charAt() method to retrieve the character at index 7, 'r', and store it in the result variable. Finally, we print the value of result to the console, which will output 'r'.
public class upGradTutorials {
public static void main(String[] args)
String str = "upGrad teaches Java.";
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
System.out.println(reversed.toString());
}
}
In the above program, we have a string "upGrad teaches Java.". We create a StringBuilder object called reversed to store the reversed string. We iterate over the characters of the original string starting from the last character (index str.length() - 1) to the first character (index 0). We use the charAt() method to retrieve each character and append it to the reversed StringBuilder. Finally, we convert the StringBuilder to a String using the toString() method and print the reversed string to the console.
(When using string "level" while running the program)
(When using string "upGrad" while running the program)
public class upGradTutorials {
public static void main(String[] args) {
String str = "upGrad";
boolean isPalindrome = true;
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
In the above example, we have a string "upGrad". We use two pointers, left and right, that point to the first and last characters of the string, respectively. We compare the characters at these pointers using the charAt() method. If they are not equal, we set the isPalindrome flag to false and exit the loop.
The loop continues until the left pointer becomes greater than or equal to the right pointer. After the loop, we check the value of the isPalindrome flag. If it is true, we print that the string is a palindrome; otherwise, we print that the string is not a palindrome.
public class upGradTutorials {
public static void main(String[] args) {
String str = "Hello, world!";
char target = 'o';
int count = 0;
int index = -1;
while ((index = str.indexOf(target, index + 1)) != -1) {
count++;
}
System.out.println("Number of occurrences of '" + target + "': " + count);
}
}
In this example, we have a string "Hello, world!" and a target character 'o'. We initialize a count variable to keep track of the number of occurrences. We also initialize the index variable to -1. We use the indexOf() method of the string to find the index of the target character starting from the index + 1 position. If a match is found, the index is updated, and we increment the count.
The loop continues until no more occurrences are found (i.e., indexOf() returns -1). Finally, we print the count of occurrences to the console.
An IndexOutOfBoundsException exception is thrown if the specified index is negative or greater than or equal to the length of the string. This exception indicates that the index is out of the valid range of the string.
It is essential to handle this exception when using the charAt() method to ensure your code does not crash or produce unexpected results when accessing characters at invalid indices.
Here is an example where we use a try-catch block to handle the IndexOutOfBoundsException when using charAt():
public class upGradTutorials {
public static void main(String[] args) {
String str = "Hello";
try {
char result = str.charAt(10);
System.out.println(result);
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid index. Exception: " + e.getMessage());
}
}
}
In the above program, we attempt to access the character at index 10 in the string "Hello". Since the string has a length of 5, the index is out of bounds and triggers an IndexOutOfBoundsException. The catch block catches the exception, and we print a custom error message to the console, including the details of the exception.
By handling the IndexOutOfBoundsException, we ensure that our program handles invalid index scenarios gracefully and avoids unexpected crashes or errors.
public class upGradTutorials {
public static void main(String[] args) {
String sentence = "upGrad teaches Java programming.";
int vowelCount = 0;
int consonantCount = 0;
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
// Check if the character is a letter
if (Character.isLetter(c)) {
// Check if the character is a vowel
if (isVowel(c)) {
vowelCount++;
} else {
consonantCount++;
}
}
}
System.out.println("Number of vowels: " + vowelCount);
System.out.println("Number of consonants: " + consonantCount);
}
private static boolean isVowel(char c) {
c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
In this example, we have a sentence "upGrad teaches Java programming." We iterate over each character in the sentence using a for loop and use the charAt() method to retrieve each character at its corresponding index.
Inside the loop, we first check if the character is a letter using Character.isLetter(c). If it is, we then call the isVowel() method to determine whether the character is a vowel or a consonant. If it's a vowel, we increment the vowelCount variable; otherwise, we increment the consonantCount variable.
After the loop finishes, we print the total number of vowels and consonants in the sentence to the console.
The isVowel() method is a helper method that checks whether a given character is a vowel. It converts the character to lowercase and then compares it against the vowels 'a', 'e', 'i', 'o', and 'u'. If the character matches any of these vowels, the method returns true; otherwise, it returns false.
We have discussed the essential concepts and examples of Java's charAt() function in this tutorial. It is important to practice using the charAt() function in various contexts, including extracting substrings, verifying user input, and creating original algorithms. This will improve your knowledge and ability to use this fundamental yet crucial Java method.
1. What is the maximum value for an input in charAt() function in Java?
The maximum value for an input in charAt() in Java is the numerical equivalent of the number of characters in a string - 1. The charAt() function starts counting from 0, not 1.
2. What is charAt(0) in Java?
charAt(0) has no specified or constant value in Java. However, it returns the 0th character of a string, which means the first character.
3. What is charAt equals in Java?
The equals() method in Java's Character class compares two Character objects. It takes one Character object as input and compares it with another Character object. Henceforth, it returns a boolean value indicating whether they are equal.
4. What is ASCII?
The American Standard Code for Information Interchange is an index for assigning numerical values to alphabet characters. They are divided into two sections- capital and small.
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...