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
Now Reading
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
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
Dive into the world of Java. Today's focus: the pivotal 'For Loop'. It's a cornerstone in coding, fundamental for iteration in Java.
In this tutorial, we will delve into the 'For Loop' structure, its applications, and nuances. You'll grasp why it's a key tool in a Java programmer's arsenal and gain practical knowledge to tackle real-world coding tasks with confidence.
Here are the details for the three parts of a 'For Loop' in Java:
1. Initialization Expression
This starts the loop. It initializes the loop variable. Usually, we use it to set a counter to a specific value. It executes only once.
2. Test Expression
This checks a condition. If it returns true, the loop continues. If it returns false, the loop ends. We usually check if the counter has reached a certain value.
3. Update Expression
This updates the loop variable. After each loop iteration, this expression runs. We often use it to increment or decrement the counter.
Loop Type | Initialization | Test Before Iteration | Runs at Least Once | Update Statement |
For Loop | Yes | Yes | No | Yes |
While Loop | No | Yes | No | No |
Do-While Loop | No | No | Yes | No |
For Loop initializes a counter, tests before iteration, and contains an update statement within the loop structure itself.
While Loop in Java checks the condition before entering the loop but does not have an inherent initialization or update statement.
Do-While Loop ensures the code block executes at least once, as it checks the condition after running the loop. But similar to While Loop, it lacks inherent initialization and update statements.
The 'For Loop' structure in Java is as follows:
For loop in Java example:
Here's a simple example of a 'For Loop' that prints numbers from 1 to 5:
In this case, int i=1 is the initialization part, where we initialize our counter i to 1.
i<=5 is the test expression. Before each loop iteration, we check if this condition is true. If i is less than or equal to 5, we continue the loop. If not, we stop the loop.
i++ is the updated expression. After each iteration of the loop, we increase i by one.
Running this code, you'll see the numbers 1 through 5 printed on your console.
Here's what each part does:
Java offers many types of 'For Loops' for diverse scenarios. They are:
1. Simple For Loop
The basic form of 'For Loop' we discussed earlier is the Simple For Loop. It consists of initialization, testing, and update expressions.
Example:
2. Enhanced For Loop (For Each Loop)
The Enhanced For Loop, also known as the "for-each" loop, is designed for iteration over arrays or collections, making the code more readable.
Example:
3. Labeled For Loop
A Labeled For Loop allows us to name our loops. This can be beneficial when we have nested loops and want to break or continue a specific outer loop.
Example:
4. Infinite For Loop
An Infinite For Loop continues indefinitely. This happens if the test condition never becomes false. It's usually a coding error, but can sometimes be useful.
Example:
These variations offer flexibility to handle different scenarios in programming with Java.
Remember, 'For Loops' are excellent for cases where you know how many times the loop should run.
Explanation:
This is a typical flowchart for a 'For Loop' in Java. It illustrates the cyclic and iterative nature of the loop, helping understand the flow of the loop process.
The For-Each Loop, also known as the Enhanced For Loop, offers a simpler way to iterate over arrays or collections. It's ideal for scenarios where you don't need to manipulate the elements' indexes.
Here's its general structure:
Type represents the data type of the elements. var is the variable that takes the value of each element during the iteration. array is the array or collection you're traversing.
Example
Consider the following array of integers:
Here, number takes on the value of each element in the numbers array. The loop prints out these values one by one. So, the output would be 1, 2, 3, 4, and 5, each on a new line.
Output
Note
While the For-Each Loop is simple and easy to use, it doesn't provide control over the index. You can't know the index of the current element within the loop, nor can you alter the iteration step (like skipping every other element). If you need such control, use a traditional For Loop.
The For-Each Loop also works great with collections. Here's an example with an ArrayList:
Output
In this example, name takes the value of each element in the names ArrayList. The loop prints out these names one by one. So, the output would be Alice, Bob, Charlie, each on a new line.
An Infinite For Loop is a loop that runs indefinitely. This usually occurs when the condition in the loop never becomes false. It's often due to a programming error, but sometimes, it's intentional.
Here's the structure of an Infinite For Loop:
Example
Here's an example of an infinite loop that would print "Hello, World!" endlessly:
Note
Running an infinite loop like the one above will print "Hello, World!" continuously until you manually stop the program.
In practical scenarios, infinite loops are not usually desirable as they can cause the program to become unresponsive or consume too much CPU time. Yet, they can be useful in cases where a program needs to run indefinitely until it's manually stopped, such as a server waiting for client requests.
Please be careful when running infinite loops, as they can make your program run indefinitely, consuming system resources. Always ensure there's a valid way to stop the loop.
A Nested For Loop in Java means there is a For Loop inside another For Loop. It's very useful when dealing with multi-dimensional data structures like arrays.
Here's the structure:
Example
An example of a nested for loop that prints a 5x5 matrix:
Output
The output would be:
This forms a 5x5 matrix, where each row is the numbers 1 through 5.
Nested For Loops are very useful in Java for manipulating multi-dimensional data structures or performing repeated operations.
The 'For Loop' in Java is a versatile control structure, integral to iterative operations in your code. Whether it's the traditional 'For Loop', the 'Enhanced For-Each Loop', the 'Labeled For Loop', or even the 'Infinite For Loop', each variant presents unique utilities in different programming contexts. Coupled with the power of nested loops, these tools provide a robust approach to handling repetitive tasks efficiently. Mastery of 'For Loops' empowers you to deal effectively with arrays, collections, and multi-dimensional data structures, enhancing your Java programming proficiency.
1. What happens if I leave out a part of the 'For Loop' syntax in Java?
Leaving out a part of the 'For Loop' syntax can have different effects. For instance, if you omit the initialization part, you must ensure the loop variable is initialized elsewhere in the code. If the condition is absent, the loop becomes an infinite loop.
2. Can I use data types other than int for the loop variable in a 'For Loop'?
Absolutely! You can use other data types such as byte, short, long, or even char for the loop variable. However, the choice should make sense according to your looping requirements. For example, using a double or float is generally unusual, unless you need to increment by fractions.
3. How does 'For Loop' behave with an empty body?
A 'For Loop' with an empty body will still execute the initialization, condition check, and increment/decrement operations. However, since the body is empty, no substantial work gets done inside the loop. In most scenarios, having an empty loop body would not be useful.
4. Are there alternatives to 'For Loops' in Java for iterative operations?
Java provides many alternatives for iterative operations, such as 'While Loop' and 'Do-While Loop'. These control structures can be used interchangeably, depending on the specific use-case. Moreover, Java provides a stream API and methods like forEach for collections, offering a functional programming approach to iterations.
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...