--- Sum of elements at even index in an array (Java – explained simply) Imagine you’re sitting in front of me and you ask: 👉 “How do I add only the elements that are at even index positions in an array?” Let me explain it step by step 👇 --- 🔹 First, understand the idea of index In Java arrays, index always starts from 0. Example array: Index → 0 1 2 3 4 Array → 5 8 2 7 6 👉 Even indexes are: 0, 2, 4 👉 Elements at those indexes are: 5, 2, 6 So the answer will be: 5 + 2 + 6 = 13 --- 🔹 How do we solve this in Java? 1. Create a variable sum and initialize it to 0 2. Loop through the array 3. Check if the index is even (i % 2 == 0) 4. If yes, add that element to sum --- 💻 Java Code: int[] arr = {5, 8, 2, 7, 6}; int sum = 0; for (int i = 0; i < arr.length; i++) { if (i % 2 == 0) { sum = sum + arr[i]; } } System.out.println(sum); --- 🔹 What’s happening here? i % 2 == 0 → checks whether the index is even arr[i] → element present at that index Only elements at even index positions are added 📌 Output: 13 --- 🧠 One-line explanation: > “We loop through the array and add only those elements whose index is even.” This small logic helps you understand: ✔ index-based conditions ✔ loops with filtering ✔ problem-solving thinking in Java Perfect for DSA & interview basics 🚀 #Java #DSA #Array #Programming #CodingBasics #LearnJava #InterviewPrep
Java Array Sum of Even Index Elements
More Relevant Posts
-
🤯 Java's Hidden Cache War: Integer vs String - Which One Bites Developers More?♨️ Java caches small Integers (-128 to 127) but Strings work differently. Knowing why saves you from bugs AND improves performance. Quick breakdown: 👇 1. INTEGER CACHE (Reference-Based) Integer a = 100; Integer b = 100; System.out.println(a == b); Why: Integer.valueOf() reuses cached objects Range: -128 to 127 (configurable) Purpose: Performance for common numbers Gotcha: == works only within cache range! 2. STRING POOL (Value-Based) String s1 = "hello"; String s2 = "hello"; System.out.println(s1 == s2); Why: JVM pools string literals Manual control: String.intern() Purpose: Memory optimization Warning: Don't overuse intern()! THE CRITICAL DIFFERENCE: Integer cache: Fixed size, performance-focused String pool: Dynamic, memory-focused GOLDEN RULE: // ❌ Never do this: if (intObj1 == intObj2) // ✅ Always do this: if (intObj1.equals(intObj2) PRACTICAL IMPACT: Loops with autoboxing → Cache helps! Repeated strings → Pool helps! == comparisons → Will bite you! TEST YOURSELF: java Integer x = 200; Integer y = 200; System.out.println(x == y); // ??? Answer below! First 5 correct answers get a Java Memory cheatsheet. Like if you learned something! Save for your next interview prep! Follow for more Java insights! #Java #Programming #Caching #Developer #Coding #Java #JVM #MemoryManagement #PerformanceOptimization #SoftwareEngineering #Programming #Coding #BackendDevelopment #SystemDesign #JavaDeveloper #TechInterview #CleanCode #DeveloperTips #Caching
To view or add a comment, sign in
-
-
📌 new String() vs String Literal in Java In Java, Strings can be created in two different ways. Although they may look similar, they behave differently in memory. 1️⃣ String Literal When a String is created using a literal: • The value is stored in the String Pool • JVM checks if the value already exists • Existing reference is reused if available Example: String s1 = "java"; String s2 = "java"; Both references point to the same object. 2️⃣ new String() When a String is created using the `new` keyword: • A new String object is created in heap memory • It does not reuse the String Pool object by default Example: String s3 = new String("java"); `s3` points to a different object even if the value is the same. 3️⃣ Memory Impact • String literals reduce memory usage through reuse • `new String()` always creates an additional object • Using `new` unnecessarily can increase memory consumption 4️⃣ When to Use • Prefer String literals for most use cases • Use `new String()` only when a distinct object is explicitly required 💡 Key Takeaways: - String literals use the String Pool - `new String()` creates a separate heap object - Understanding this helps write memory-efficient code #Java #CoreJava #String #JVM #BackendDevelopment
To view or add a comment, sign in
-
Core Java interview questions with only advanced questions (no basics) 👇 1. How does JVM memory model work (Heap, Metaspace, Stack, PC, Native)? 2. Explain GC algorithms: G1 vs ZGC vs CMS – when to use what? 3. What is the hashCode()–equals() contract and how does it affect HashMap? 4. How does ConcurrentHashMap achieve thread-safety internally? 5. Difference between synchronized, ReentrantLock, and StampedLock? 6. What happens internally during a thread context switch? 7. Explain Java Memory Model (JMM) and the volatile keyword. 8. How does CompletableFuture work compared to Future? 9. Internal working of Java Streams – lazy evaluation & short-circuiting. 10. How does Optional help in avoiding NPE and when not to use it? 11. Type erasure in Generics – limitations and runtime impact. 12. Reflection: performance cost and real-world use cases. 13. Serialization vs Externalization – differences and risks. 14. JDBC connection pooling – why and how it improves performance? 15. How does Spring use Dependency Injection at runtime? 16. Singleton implementation pitfalls in multithreaded environments. 17. Factory vs Abstract Factory – real backend use case? 18. How does Java handle OutOfMemoryError and GC tuning? 19. Stack vs Heap memory – impact on performance and scalability. 20. How do you debug a production memory leak in Java? Skipping basics. Focusing on real interview questions. #Java #CoreJava #InterviewPrep #Backend #SoftwareEngineer
To view or add a comment, sign in
-
Day 13 : Variables 1. Variables are the containers in which we store data. 2. In java we can create variables with the help of datatype. 3.To give the name of variable should follow the Camel Case convention. Variable declaration and initialization statement: - 1.Declare a variable and store the value simultaneously. Syntax:- datatype variablename = value / expression ; E.g. :- int num=100; String name = “Shubham”; ⚠️ We cannot use a variable without declaring it. Variables are classified into two types 1. Class level Variables/Instance Variable:- The variables which are declared in the class block are known as Class level variable or Instance Variable. We can use a Instance variable without initialization because Instance variables Default values are assigned by the JVM. # In Java There is no Concept called Global Variable. They are classified into two types, i. Static Variable ii. Non-static Variable Examples: 1. class Demo { String name = "Ajit Pawar"; // instance variable main(String[] args) { Demo d = new Demo(); System.out.println(d.name); } } 2. class Demo{ static int a=10; //static variable main(){ s.o.p(a); // 10 } } 2. Local Variables:- The variables which are declared in the method block or any other block other than class block is known as local variables. For Ex. In Method block , constructor block, control flow statements block etc. Examples. 1. class Example{ main(){ int a =10; s.o.p(a); // 10 } } 2. class Example{ main(){ { int a =10; } s.o.p(a); // CTE } } #Java #CoreJava #JavaProgramming #JavaVariables #LearnJava #CodingJourney #ProgrammingStudent #DailyLearning #ComputerScience
To view or add a comment, sign in
-
-
📘 Core Java – Day 5 Topic: Loops (for loop & simple pattern) Today, I learned about the concept of Loops in Core Java. Loops are used to execute a block of code repeatedly, which helps in reducing code redundancy and improving efficiency. In Java, the main types of loops are: 1. for loop 2. while loop 3. do-while loop 4. for-each loop 👉 I started by learning the for loop. 🔹 Syntax of for loop: for(initialization; condition; increment/decrement) { // statements } 🔹 Working of for loop: Initialization – initializes the loop variable (executed only once) Condition – checked before every iteration Execution – loop body runs if the condition is true Increment/Decrement – updates the loop variable Loop continues until the condition becomes false ⭐ Example: Simple Star Pattern using for loop for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🔹 Key Points: ✔ for loop is used when the number of iterations is known ✔ It keeps code structured and readable ✔ Nested for loops are commonly used in pattern programs 🚀 Building strong fundamentals in Core Java, one concept at a time. #CoreJava #JavaLoops #ForLoop #JavaProgramming #LearningJourney #Day5
To view or add a comment, sign in
-
Stop writing messy Switch statements. 🛑 Old Java switches were loud, clunky, and prone to "fall-through" bugs. You had to repeat `case`, spam `break`, and pray you didn't miss one. Java 14+ changed the game with Switch Expressions. The New Way: ✅ Arrow syntax (->) → No more break keywords ✅ Expressions → Return values directly ✅ Exhaustiveness → Compiler forces you to cover every case ✅ Multiple labels → case 1, 2, 3 -> in one line ✅ yield → For multi-line case blocks // Old way 😫 String result; switch (day) { case 1: result = "Monday"; break; // Forget this? Bug! case 2: result = "Tuesday"; break; default: result = "Unknown"; } // New way 🚀 String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Unknown"; }; It's not just shorter— it's impossible to break by accident. Have you made the switch? 👇 #Java #SoftwareEngineering #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
-
🔍 Difference between Arrays.asList() and List.of() in Java Let’s understand this with a simple example 👇 List<Integer> ls = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> lst = List.of(1, 2, 3, 4, 5, 6); ✅ Case 1: Arrays.asList() 1️⃣ Change value using index ls.set(0, 100); Output [100, 2, 3, 4, 5, 6] 2️⃣ Try to add a new element ls.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element ls.remove(2); ❌ UnsupportedOperationException 🔎 Analysis Arrays.asList() returns a fixed-size list It is backed by an array ✅ You can modify elements using set() ❌ You cannot add or remove elements ✅ null values are allowed 📌 Introduced in Java 1.2 ✅ Case 2: List.of() 1️⃣ Try to change value lst.set(0, 100); ❌ UnsupportedOperationException 2️⃣ Try to add a new element lst.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element lst.remove(1); ❌ UnsupportedOperationException 🔎 Analysis List.of() creates a fully immutable list ❌ You cannot add, remove, or modify ❌ null values are not allowed 📌 Introduced in Java 9 ❓ Main Question: When to use which? ✅ Use List.of() When you need a read-only / immutable list, such as: List<String> roles = List.of("ADMIN", "USER", "MANAGER"); ✔ Best for constants ✔ Prevents accidental modification ✔ Cleaner & safer code Arrays.asList() allows value modification but not size change, whereas List.of() creates a completely immutable list. #Java #JavaInterview #Collections #BackendDevelopment #SpringBoot #HappyLearning #JavaLearner #JVM
To view or add a comment, sign in
-
How to add all elements of an array in Java (Explained simply) Imagine you’re sitting in front of me and you ask: 👉 “How do I add all the numbers present in an array using Java?” I’d explain it like this 👇 Think of an array as a box that already contains some numbers. For example: [2, 4, 6, 8] Now our goal is simple: ➡️ Take each number one by one ➡️ Keep adding it to a total sum Step-by-step thinking: First, we create a variable called sum and set it to 0 (because before adding anything, the total is zero) Then we loop through the array Each time we see a number, we add it to sum After the loop finishes, sum will contain the final answer Java Code: int[] arr = {2, 4, 6, 8}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println(sum); What’s happening here? arr[i] → current element of the array sum = sum + arr[i] → keep adding elements one by one Loop runs till the last element Final Output: 20 One-line explanation: “We start from zero and keep adding each element of the array until nothing is left.” If you understand this logic, you’ve already learned: ✔ loops ✔ arrays ✔ problem-solving mindset This is the foundation of many real-world problems in Java 🚀 #Java #Programming #DSA #BeginnerFriendly #LearnJava #CodingBasics
To view or add a comment, sign in
-
Hello connections I was revising Strings concept in java today. 😁 I have been hit with a question which I am posting below along with my logic 🤑 : Coding question: String Transformation, Convert input string to output string and print the output string. Input String: "91-044 56 9877 2976545" Output String: "910-445-698-772-976-545" My logic: String input = "91-044 56 9877 2976545"; input = input.replaceAll("-","").replaceAll(" ",""); String output =""; for(int i= 0; input.length()-i>=3 ;i+=3){ output = output + input.substring(i,i+3)+"-"; } output = output.substring(0,output.length()-1); return output; I am excited to know if there is any other way to solve it even if it's another language. 😀 (I solved it in java.) #HappyLearning
To view or add a comment, sign in
-
🚀 Core Java Insight: Variables & Memory (Beyond Just Syntax) Today’s Core Java session completely changed how I look at variables in Java — not as simple placeholders, but as memory-managed entities controlled by the JVM. 🔍 Key Learnings: ✅ Variables in Java Variables are containers for data Every variable has a clear memory location and lifecycle 🔹 Instance Variables Declared inside a class Memory allocated in the Heap (inside objects) Automatically initialized by Java with default values Examples of default values: int → 0 float → 0.0 boolean → false char → empty character 🔹 Local Variables Declared inside methods Memory allocated in the Stack No default values Must be explicitly initialized — otherwise results in a compile-time error 🧠 How Java Executes in Memory When a Java program runs: Code is loaded into RAM JVM creates a Java Runtime Environment (JRE) JRE is divided into: Code Segment Heap Stack Static Segment Each segment plays a crucial role in how Java programs execute efficiently. 🎯 Why This Matters Understanding Java from a memory perspective helps in: Writing cleaner, safer code Debugging issues confidently Answering interview questions with depth Becoming a developer who understands code — not just runs it 💡 Great developers don’t just write code. They understand what happens inside the system. 📌 Continuously learning Core Java with a focus on fundamentals + real execution behavior. #Java #CoreJava #JVM #JavaMemory #ProgrammingConcepts #SoftwareEngineering #InterviewPrep #DeveloperJourney #LearningEveryDay
To view or add a comment, sign in
-
Explore related topics
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