One loop works perfectly, the other crashes — both use 'for'! When you start learning Java Collections, this common confusion pops up: ArrayList<Integer> num = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10)); Index-based for loop (works perfectly): for (int i = 0; i < num.size( ); i++) { System.out.println(num.get(i)); // i is the index here } 𝗢𝘂𝘁𝗽𝘂𝘁: 2 4 6 8 10 𝗘𝗻𝗵𝗮𝗻𝗰𝗲𝗱 𝗳𝗼𝗿-𝗲𝗮𝗰𝗵 𝗹𝗼𝗼𝗽 (𝗰𝗼𝗺𝗺𝗼𝗻 𝗺𝗶𝘀𝘁𝗮𝗸𝗲): for (Integer i : num) { System.out.println(num.get(i)); // ❌ WRONG! } In a 𝐟𝐨𝐫-𝐞𝐚𝐜𝐡 𝐥𝐨𝐨𝐩, 𝐢 𝐢𝐬 𝐭𝐡𝐞 𝐚𝐜𝐭𝐮𝐚𝐥 𝐞𝐥𝐞𝐦𝐞𝐧𝐭 𝐯𝐚𝐥𝐮𝐞 (like 2, 4, 6), not the index. So, use i directly—don’t call list.get(i) because it treats i as an index, causing errors. So num.get(i) tries to get element at index 2, then 4, then 6 — but your List only has indices 0 to 4 (since its size is 5). num.get(10) is invalid — this throws IndexOutOfBoundsException because the last valid index is 4. 𝐊𝐞𝐲 𝐩𝐨𝐢𝐧𝐭𝐬 𝐟𝐨𝐫 𝐜𝐥𝐚𝐫𝐢𝐭𝐲: ✅ In index loop: i = index → safe to do num.get(i). ✅ In for-each loop: i = element → just use System.out.println(i) directly. Avoid calling num.get(i) here. 💡 𝐑𝐞𝐦𝐞𝐦𝐛𝐞𝐫: ArrayList grows dynamically when you add elements (add()). But calling get(index) with an out-of-range index will crash your program — it does NOT auto-create elements or indexes. Suresh Bishnoi Sir #ArrayList #Coding #CollectionFrameWork #Java #ForLoop #Code #Tips
Java Collections: for-each loop vs index-based loop
More Relevant Posts
-
Day 90 of #100DaysOfCode Solved Squares of a Sorted Array in Java 🔠 Approach The task was to take an array of integers sorted in non-decreasing order, square each number, and then return the result array also sorted in non-decreasing order. Brute-Force Method The solution implemented here is a straightforward two-step brute-force approach: Squaring: I iterated through the input array nums and replaced each element with its square (i.e., nums[i] * nums[i]). This handles both positive and negative numbers correctly. Sorting: After squaring all elements, I used Java's built-in Arrays.sort(nums) method to sort the entire array. While correct, this approach has a time complexity dominated by the sorting step, which is O(NlogN), where N is the number of elements. The runtime of 10 ms shows that a more efficient, two-pointer approach (which can solve this in O(N) time) is generally preferred for optimal performance. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Array #Sorting #ProblemSolving
To view or add a comment, sign in
-
-
Extract a character from a string To get a character from a string in Java, you can use the charAt() method of the String class. This method takes an index as an argument and returns the character at that position (0-based index). Here's a simple Java program to demonstrate this: Code : public class GetCharacterFromString { public static void main(String[] args) { String str = "Hello, World!"; int index = 7; // Index of the character to retrieve (0-based) // Get the character at the specified index char ch = str.charAt(index); // Print the character System.out.println("Character at index " + index + " is: " + ch); } } Can anyone guess the output ?. #JavaProgramming #JavaCode #Coding #ProgrammingTips #LearnJava #JavaDevelopment #CodeSnippet #SoftwareDevelopment #TechTips #100DaysOfCode
To view or add a comment, sign in
-
💡Did you know that Generics simplify your code in Java, even if you don't use them directly? If you’ve ever worked with Java Collections, you’ve already used one of the language’s most powerful features: Generics. But why are they so important? 1. Type Safety Generics allow you to specify the type of objects a collection or class can work with. This drastically reduces ClassCastException and other runtime surprises, leading to more stable applications. 2. Cleaner Code by Eliminating Explicit Casts By specifying the type upfront, the compiler automatically handles casts when retrieving elements. 3. Improved Code Reusability Write classes once, and use them with any object type. Generics enable you to build flexible, reusable components without sacrificing type integrity. A perfect example? The List Interface! When you declare a List, you must typically specify the type of object it will hold within angle brackets (<>). This specified type is the type argument for the generic interface. For example: • List<String> means the list can only hold String objects. • List<Integer> means the list can only hold Integer objects. Without Generics (pre-Java 5), you could add any element to the List, but: • Adding different types of variables to the list would lead to a ClassCastException. • When retrieving values, you had to manually cast each element. This simple difference illustrates how generics transform potential runtime headaches into compile-time warnings, allowing developers to catch and fix issues much earlier in the development cycle. #Java #Generics #Programming #CleanCode #SoftwareDevelopment #JavaCollections #CodingTips
To view or add a comment, sign in
-
-
Day 28/100 – #100DaysOfCode 🚀 | #Java #LeetCode #DynamicProgramming ✅ Problem Solved: Scramble String 🔀 🧩 Problem Summary: Given two strings s1 and s2, determine whether one is a scrambled version of the other. A string is scrambled by recursively dividing it into two non-empty substrings and swapping them. 💡 Approach Used: Implemented Recursion + Memoization using a HashMap for overlapping subproblems. Used character frequency checks to prune unnecessary recursion calls. Used Java’s BiFunction with inline helper logic for recursion. ⚙️ Time Complexity: O(n⁴) (due to substring operations and recursion) 📦 Space Complexity: O(n²) ✨ Takeaway: Even complex recursive problems can be optimized efficiently with Memoization and early pruning. 🚀 #Java #LeetCode #DynamicProgramming #Recursion #ProblemSolving #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 18/100 of #100DaysOfCode ✅ Solved “Isomorphic Strings” (LeetCode #205) using Java! 🧩 Problem: Given two strings s and t, determine if they are isomorphic. 👉 Two strings are isomorphic if characters in one string can be replaced to get the other — while keeping order and unique mapping intact. 🧠 Approach: Used a HashMap to store the mapping of characters from s → t. Checked if each character in s has a consistent mapping in t. Also ensured that no two characters in s map to the same character in t. ✨ Example: s = "egg", t = "add" → true (e→a, g→d) s = "foo", t = "bar" → false 📈 Complexity: Time: O(n) Space: O(n) 💡 Key Learnings: Understood how to maintain one-to-one character mapping using a HashMap. Reinforced logic building for pattern matching between strings. 💻 Tech Used: Java | HashMap | Problem Solving #LeetCode #100DaysOfCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing #DevCommunity
To view or add a comment, sign in
-
-
☑️ Day 96 | #120DaysOfLearning | Java Full Stack 🌟 Topic: Multiple Bean Injection, @Primary vs @Qualifier in Spring Boot ☑️ What I Learned: ✨ How Spring Boot handles situations where multiple beans of the same type exist. ✨ Why Spring gets confused during autowiring and how to avoid Bean Ambiguity errors. ✨ Understood the usage of @Primary as default bean selector. ✨ Learned how @Qualifier gives explicit control over which specific bean to inject. 🧩 Key Concepts: 1️⃣ Why Multiple Bean Conflict Occurs ✨ When more than one class implements the same interface, Spring gets confused during @Autowired. ✨ It throws NoUniqueBeanDefinitionException (meaning—“Which one should I inject?”) 2️⃣ @Primary Annotation ✨ Declares one bean as default among multiple candidates. ✨ Spring will automatically inject this bean if no specific instruction is given. 🌟 Example: Setting GPayService as the default payment service. 3️⃣ @Qualifier Annotation ✨ Used to explicitly specify the exact bean name to inject. ✨ Overrides @Primary if both are applied. 🌟 Example: @Qualifier("phonepePayment") → Forces injection of PhonePeService only. ☑️ Simple Real-Life Analogy: 📱 @Primary = Default SIM card for all outgoing calls. 📞 @Qualifier = Use specific SIM for this one special call. 🫶 Special Thanks to : #DestinationCodegn.. Anand Kumar Buddarapu Sir , Saketh Kallepu Sir, Uppugundla Sairam Sir.. #SpringBoot #JavaDevelopment #JavaFullStack #SpringFramework #BeanInjection #Qualifier #Primary #BackendDevelopment #LearnJava #SpringBootTutorial #JavaLearningJourney #CodeEveryday
To view or add a comment, sign in
-
You should use 𝚂𝚝𝚛𝚒𝚗𝚐 𝚊 = “𝙷𝚎𝚕𝚕𝚘”, and not 𝚂𝚝𝚛𝚒𝚗𝚐 𝚊 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”) in Java. Here’s why. 👇 If you write Java, you deal with String objects all day long. But do you know the hidden memory optimization that saves your application from running out of space? It's the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥. 𝐒𝐭𝐫𝐢𝐧𝐠 𝐩𝐨𝐨𝐥, 𝐨𝐫 𝐭𝐡𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥, is a special storage area in the Java 𝐇𝐞𝐚𝐩 𝐦𝐞𝐦𝐨𝐫𝐲 where string literals are stored. The core idea is to avoid creating multiple duplicate String objects in memory when they have the same content. The String Pool is the 𝐤𝐞𝐲 to efficient, scalable code and a crucial JVM feature. When you declare a String literal (𝐒𝐭𝐫𝐢𝐧𝐠 𝐚 = "𝐇𝐞𝐥𝐥𝐨"), the JVM first checks the Pool. If the string already exists, the new variable will simply point to that existing object in the pool, avoiding new memory allocation. This optimization only works because Java String objects are 𝐢𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞. 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟷 = “𝙷𝚎𝚕𝚕𝚘”; 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟸 = “𝙷𝚎𝚕𝚕𝚘”; Both strings point to the same object in memory. So if you do: 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟸); // 𝚝𝚛𝚞𝚎 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟹 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”); It always 𝐟𝐨𝐫𝐜𝐞𝐬 the creation of a new object in the main Heap, outside the String Pool. So if you do: 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟹); // 𝚏𝚊𝚕𝚜𝚎 If you absolutely must use the new operator you can call .𝚒𝚗𝚝𝚎𝚛𝚗() on your string to explicitly move or fetch its reference from the Pool, forcing the JVM to 𝐫𝐞𝐮𝐬𝐞 𝐨𝐛𝐣𝐞𝐜𝐭𝐬. 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟹 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”).𝚒𝚗𝚝𝚎𝚛𝚗(); 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟹); // 𝚝𝚛𝚞𝚎 What’s your favorite JVM optimization trick? Share in the comments! 👇 #Java #JVM #SoftwareEngineering #TechCareer #ProgrammingTips #MemoryManagement #PerformanceTuning #Coding
To view or add a comment, sign in
-
☀️ Day 14 of My 90 Days Java Challenge – Wrapper Classes: Bridging Primitives & Objects Today’s topic looked simple on the surface — Wrapper Classes — but once I explored deeper, I realized how much they quietly power modern Java. Here’s what I discovered 👇 🔹 1️⃣ The bridge between primitive and object worlds Java’s primitive types (int, char, double) live outside the object ecosystem. Wrapper classes (Integer, Character, Double, etc.) bring them into the object-oriented world, allowing them to be used in collections, generics, and frameworks. 🔹 2️⃣ Autoboxing & unboxing – silent helpers Since Java 5, the compiler automatically converts between primitives and wrappers: int ↔ Integer, double ↔ Double. It feels seamless — but I learned it’s not free. Excessive autoboxing can lead to hidden performance hits if ignored in high-volume loops. 🔹 3️⃣ Immutability matters All wrapper classes are immutable — once created, their value cannot change. This design choice ensures thread-safety and reliability, but it also reminds you to handle them carefully when performance matters. 🔹 4️⃣ == vs .equals() — the classic trap Many developers stumble here. == compares references, while .equals() compares values. This subtle difference can cause silent logical bugs when comparing wrapper objects. 💭 Key takeaway: Wrapper classes are not just about syntax convenience — they represent Java’s effort to unify primitive speed with object-oriented design. Understanding their behavior makes you a smarter, more intentional Java developer. #Day14 #Java #CoreJava #WrapperClasses #Autoboxing #Unboxing #OOP #LearningJourney #90DaysChallenge
To view or add a comment, sign in
-
Primitives vs Wrappers in Java: A Practical Balance for Performance and API Design 💡 In Java, choosing between primitive types (int, boolean, long) and their wrapper counterparts (Integer, Boolean, Long) isn’t just a speed race—it shapes how you model nullability, API contracts, and data flows. 🚀 Primitives win on performance and memory: fewer objects, no nulls, and straightforward arithmetic. They’re the default for local variables and tight loops. 🧭 Wrappers unlock object‑oriented conveniences: nullability, easy use in generics, and compatibility with reflection or frameworks. But boxing/unboxing and higher memory usage can sneak into hot paths. Key takeaways: - Use primitives in performance‑sensitive code and internal math. - Use wrappers in DTOs, API surfaces, or data stores where nulls or optional values matter. - Prefer primitive streams (IntStream, LongStream) to avoid boxing in data pipelines. - If you need to express absence with primitives, consider OptionalInt/OptionalLong rather than nulls. - When working with large, memory‑sensitive collections, consider primitive‑specific collections from third‑party libraries. - Be mindful of NPEs when a wrapper value is null. Bottom line: balance is design‑driven, not dogmatic. Align your choice with API guarantees and performance budgets. What’s your take? Have you faced a scenario where the primitive vs wrapper choice changed performance or design outcomes? What specific suggestions would you add to improve this post (e.g., with a short code snippet)? #Java #JavaPerformance #PrimitivesVsWrappers #SoftwareEngineering #Programming
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development