Day 16: VarArgs and Recursion 🔸Variable Arguments (Varargs): A function with varargs can be created in Java using the following syntax: public static void foo(int... arr) { // arr is available here as int[] arr } foo can be called with zero or more arguments, like this: foo(7) foo(7, 8, 9) foo(1, 2, 7, 8, 9) We can also create a function bar like this: public static void bar(int a, int... arr) { // code } bar(1) bar(1, 2) bar(1, 7, 9, 11) 🔸Example static int avg(int... arr) { int result = 0; int avg = 0; for (int element : arr) { result += element; } avg = result / arr.length; return avg; } public static void main(String[] args) { System.out.println("The average is " + avg(3, 5, 8, 7)); } 🔸Recursion A function in Java can call itself. Such calling of a function by itself is called recursion. 🔸Syntax of Recursion in Java: returnType functionName(parameters) { if(base_condition) { return value; } else { return functionName(smaller_problem); } } 🔸Example: Factorial Using Recursion: static int factorial(int n) { if(n == 0 || n == 1) // base condition return 1; else return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println(result); } #Java #Programming #SoftwareDevelopment #JavaDeveloper #Coding #ProblemSolving #LearningJourney #ComputerScience #KodNest
Java Varargs and Recursion Examples
More Relevant Posts
-
Exception Nostalgia!! Coded in Java for several years and moved to Python recently, nevertheless the core concepts remain the same be it the classes, functions or exception handling :) 🚀 FastAPI Insight: Why Your 4xx Errors Still Show “detail” (and how to fix it cleanly) While working with FastAPI, I came across a subtle but important behavior in error handling. 🔍 The Situation You raise an exception like this: raise HTTPException( status_code=422, detail={ "error_code": "VALIDATION_ERROR", "message": "Something went wrong" } ) But the response always comes back as: { "detail": { "error_code": "...", "message": "..." } } 🤔 Even though you passed a custom structure, FastAPI wraps everything inside "detail". 🧠 Key Insight HTTPException → controls the status code FastAPI → always wraps response inside detail You cannot change this behavior directly ⚠️ Common Mistake Catching all exceptions like this: except Exception as e: This also catches HTTPException ❌ Result → Your intended 4xx/5xx error may get converted into a 200 response (bad API design) ✅ Correct Pattern except HTTPException: raise # preserve original status code 💡 The Real Solution If you want a clean, consistent API response like: { "status": "error", "error": { ... } } 👉 You need to override FastAPI’s default behavior: @app.exception_handler(HTTPException) async def custom_handler(request, exc): return JSONResponse( status_code=exc.status_code, content={ "status": "error", "error": exc.detail } ) 🎯 Final Takeaway ✔️ Use HTTPException for proper HTTP semantics ✔️ Always re-raise it inside except blocks ✔️ Use a custom exception handler for consistent API contracts This small tweak can make your API: Cleaner More predictable Easier to integrate with frontend systems #FastAPI #BackendDevelopment #Python #APIDesign #SoftwareEngineering #CleanCode #Microservices
To view or add a comment, sign in
-
𝐂𝐚𝐧 𝐰𝐞 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐞 𝐭𝐡𝐞 "𝐦𝐚𝐢𝐧()" 𝐦𝐞𝐭𝐡𝐨𝐝 𝐢𝐧 𝐉𝐚𝐯𝐚? In my previous post, we discussed that the "main()" method is static. No — we cannot override the "main()" method Why ? Because "main()" is static. And we cannot override static methods And in Java: 📃Overriding happens at runtime ⏱️ 📃 It depends on objects 👤 But ❌ Static methods belong to the class ❌ They are loaded during class loading time (before objects are created) 🔍𝐖𝐡𝐚𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐭𝐡𝐞𝐧? You can write a main() method in a child class ❌ But it does not override the parent’s main(). It’s called "𝐌𝐞𝐭𝐡𝐨𝐝 𝐇𝐢𝐝𝐢𝐧𝐠". 𝐜𝐥𝐚𝐬𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧"); } } 𝐜𝐥𝐚𝐬𝐬 𝐂𝐡𝐢𝐥𝐝 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧"); } } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐏𝐚𝐫𝐞𝐧𝐭 𝐩 = 𝐧𝐞𝐰 𝐂𝐡𝐢𝐥𝐝(); 𝐩.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧 𝐂𝐡𝐢𝐥𝐝.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧 } } Output : Parent main Child main ♟️These main() methods are not called automatically by the JVM — they run only when we explicitly invoke them. ♟️Only main(String[] args) is invoked automatically by JVM. Other overloaded or hidden main() methods are executed only when explicitly called. 🚀 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 "main()" method cannot be overridden because it is static — it can only be hidden #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #OOP #InterviewPrep
To view or add a comment, sign in
-
If you have a Java interview coming up, read this first. Not because I didn't know Java, but because I had never structured my thinking around the questions that actually get asked. Here's what I wish someone had handed me earlier. 👇 🔑 The OOP Pillars (know these cold) Java is built on 4 concepts. If you can't explain them clearly, the interview ends early. • Inheritance: a child class inherits properties from a parent. Think Dog extends to Animal. • Polymorphism: same method, different behaviour. A cat and a dog both have makeSound(), but they sound very different. • Encapsulation: hide your data behind private fields. Use getters and setters. Protect your class from the outside world. • Abstraction: expose only what is needed. Interfaces and abstract classes are your tools here. ⚡ The questions that always come up What's the difference between method overloading and overriding? → Overloading = same name, different parameters (compile-time) → Overriding = same name, same parameters, child redefines behaviour (runtime) What's JDK vs JRE vs JVM? → JVM runs the bytecode → JRE = JVM + libraries (for users) → JDK = JRE + dev tools like the compiler (for developers) Checked vs unchecked exceptions? → Checked = caught at compile time (FileNotFoundException) → Unchecked = caught at runtime (NullPointerException) "String vs StringBuilder vs StringBuffer?" → String is immutable → StringBuilder is mutable, not thread-safe (faster) → StringBuffer is mutable AND thread-safe (synchronized) 📦 Collections they love to ask about • ArrayList: resizable array, allows duplicates • HashMap: key-value pairs, one null key allowed • HashSet: no duplicates, unordered • LinkedList: dynamic sizing, great for frequent insertions/deletions • TreeSet: sorted, unique elements (red-black tree under the hood) 🔒 The keywords they test on • final: can't be changed/overridden/extended • static: belongs to the class, not the object • volatile: ensures visibility across threads • transient: skip this field during serialization • synchronized: one thread at a time, prevents race conditions 🧵 Threading basics they always sneak in Two ways to create a thread: extend Thread or implement Runnable. Know deadlock: it happens when two threads are each waiting for what the other holds. Know wait(), notify(), and notifyAll(): they coordinate thread communication. This is just the surface layer. But getting these right will take you through 80% of what you'll face in a Java interview. Hit a like and repost it to make it visible to a wider audience! Follow Tarun Tiwari for more! And if you're preparing right now, you've got this. 💪 #Java #JavaDeveloper #CodingInterview #SoftwareEngineering #ProgrammingTips #TechCareers #LearnJava #InterviewPrep #OOP #100DaysOfCode
To view or add a comment, sign in
-
Day 10 Today I practiced rotating an array n times from the left. Instead of shifting elements one by one, I used the reversal algorithm, which is more efficient and avoids extra space. Example: Input: {1,2,3,4,5}, n = 3 Output: {4,5,1,2,3} This was a great way to revise array indexing and in-place manipulation. ================================================== // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { int a []={1,2,3,4,5}; //output:{4,5,1,2,3} int n=3; int k=n%a.length; int left=0; int right=a.length-1; a=reverseArray(a,0,k-1); System.out.println(Arrays.toString(a)); a=reverseArray(a,k,right); System.out.println(Arrays.toString(a)); a=reverseArray(a,left,right); System.out.println("Final result:"+Arrays.toString(a)); } public static int [] reverseArray(int a [],int left , int right) { int temp; while(left < right) { temp=a[left]; a[left]=a[right]; a[right]=temp; left++; right--; } return a ; } } Output:[3, 2, 1, 4, 5] [3, 2, 1, 5, 4] Final result:[4, 5, 1, 2, 3] #AutomationTestEngineer #Selenium #Java #CodingPractice #Arrays #ProblemSolving
To view or add a comment, sign in
-
-
Tackling the "Silent Overflow" in Java 🛑🔢 I recently worked through LeetCode #7: Reverse Integer, and it was a fantastic deep dive into how Java handles 32-bit integer limits and the dangers of "silent overflows." The Problem: Reverse the digits of a signed 32-bit integer. If the reversed number goes outside the 32-bit signed range of [-2^{31}, 2^{31} - 1], the function must return 0 The "Asymmetry" Challenge: In Java, Integer.MIN_VALUE is -2,147,483,648, while Integer.MAX_VALUE is 2,147,483,647. The negative range is one unit larger than the positive range due to Two's Complement arithmetic. This creates a massive trap: using Math.abs() on the minimum value will actually overflow and remain negative! My Optimized Solution Strategy: I implemented a two-pronged approach to handle these edge cases efficiently: 1️⃣ Pre-emptive Boundary Filtering: I added a specific optimization check at the very beginning: if(x >= Integer.MAX_VALUE - 4 || x <= Integer.MIN_VALUE + 6) return 0;. This catches values at the extreme ends of the 32-bit range immediately, neutralizing potential Math.abs overflow before the main logic even begins. 2️⃣ 64-bit Buffering: I used a long data type for the reversal calculation. This provides a 64-bit "safety net," allowing the math to complete so I can verify if the result fits back into a 32-bit int boundary. Complexity Analysis: 🚀 Time Complexity: O(log_10(n))— The loop runs once for every digit in the input (at most 10 iterations for any 32-bit integer). 💾 Space Complexity: O(1)— We use a constant amount of extra memory regardless of the input size. Small details like bit-range asymmetry can break an entire application if ignored. This was a great reminder that as developers, we must always think about the physical limits of our data types! #Java #LeetCode #SoftwareDevelopment #ProblemSolving #Algorithms #CleanCode #JavaProgramming #DataStructures #CodingLife
To view or add a comment, sign in
-
-
💡 While implementing string permutations in Java, I noticed a small detail about 'substring()' that many developers overlook. Here’s the example I was working on. Find all permutations of "ABC". Total permutations: 3! = 6 ABC ACB BAC BCA CAB CBA The idea behind the algorithm is simple. At each step we: • pick one character • append it to the answer • recurse on the remaining characters A common Java implementation looks like this: public static void permutation(String str, String ans) { if (str.isEmpty()) { System.out.println(ans); return; } for (int i = 0; i < str.length(); i++) { char current = str.charAt(i); String newStr = str.substring(0, i) + str.substring(i + 1); permutation(newStr, ans + current); } } Initial call: permutation("ABC", "") While walking through the code, an interesting Java behavior appears. Consider this case: str = "ABC" i = 2 // character 'C' The code executes: str.substring(0, 2) → "AB" str.substring(3) → "" Why doesn't `substring(3)` throw an error? Because in Java: "#substring(beginIndex)" returns the substring from #beginIndex to the end of the string. If: beginIndex == str.length() Java simply returns an empty string, not an exception. So the expression becomes: "AB" + "" Result: "AB" This small language detail allows the permutation logic to work without extra boundary checks. Sometimes the most useful insights while solving DSA problems come from understanding how the programming language behaves at edge cases. #Java #DSA #Recursion #Algorithms #CodingInterview
To view or add a comment, sign in
-
-
Ever wondered why this prints true 🤔 Integer x = 125; Integer y = 125; System.out.println(x == y); // true But this prints false 😮 Integer x = 250; Integer y = 250; System.out.println(x == y); // false Looks the same… but behaves differently? Let’s break it 👇 The Reason: Integer Caching Java internally caches Integer values in the range -128 to 127. So when you write: Integer x = 125; Integer y = 125; 👉 It actually uses: Integer.valueOf(125); ✔ Both variables point to the same cached object ✔ That’s why → x == y is true ⚠️ But outside the range… Integer x = 250; Integer y = 250; ❌ No caching here ❌ Separate objects are created 👉 So → x == y is false 🚨 Important Twist (Most people miss this!) Integer x = new Integer(125); Integer y = new Integer(125); System.out.println(x == y); // false ❌ new Integer() always creates a new object ❌ Caching is NOT used here 👉 Integer caching works only with: ✔ Integer.valueOf() ✔ Autoboxing (Integer x = 125) 💡 Golden Rule x.equals(y) // ✔ Always use this for value comparison Small concepts like these can make or break your interview. Did you already know this or learned something new today? 👇 #Java #Programming #JavaTips #Coding #Developers #InterviewPrep #BackendDevelopment Inspired by amazing learning content from CoderArmy, Rohit Negi and Aditya Tandon — highly recommend following their new JAVA series!
To view or add a comment, sign in
-
Why Java Is Not a Pure Object-Oriented Language A pure object-oriented programming language is one where everything in the program is treated as an object. In such languages, even basic values like numbers, characters, and boolean values are represented as objects. There are no primitive data types. javava is a language that embraces many object-oriented concepts, yet it does not fully qualify as a purely object-oriented language. Here are the key reasons why: 1. Presence of Primitive Data Types Java includes several primitive data types, such as: - int - float - double - char - boolean - long - short - byte These types are not objects, which contradicts the principle that all values in a program should be objects. For example, in the code snippet below, `a` is a primitive value, not an object: ```java int a = 5; System.out.println(a); ``` In contrast, languages like Smalltalk treat even numbers and boolean values as objects. 2. Use of the static Keyword Java permits the declaration of methods and variables using the static keyword. Static members are associated with the class itself rather than with an instance of the class, allowing access without creating an object. This undermines the principle that all operations should occur through objects. For instance: ```java class Test { static int count = 0; static void show() { System.out.println("Hello"); } } ``` In this example, the method `show()` can be called without instantiating an object. 3. Wrapper Classes and Primitive Conversion Java offers wrapper classes such as: - Integer - Float - Double - Character - Boolean These classes enable primitive values to be treated as objects. However, Java still relies on primitive types through mechanisms like autoboxing and unboxing. For example: ```java public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: " + k); } } ``` In this case, primitive values #ProgrammingConcepts #SoftwareEngineering #Coding #BackendDevelopment #JavaInterview #TechLearning #ProgrammingEducation #CodeNewbie #DeveloperLife #ComputerScience #ProgrammingTips #JavaConcepts
To view or add a comment, sign in
-
-
🚀 Deep Dive into Java String Algorithms: From Basics to Palindromes I recently wrapped up an intensive session focused on mastering String manipulation in Java, specifically focusing on substrings and algorithmic problem-solving. It was a powerful reminder that complex problems become simple when you break them down into smaller, manageable parts. Here are the key takeaways from the session: 🔹 Subarrays vs. Substrings: One of the most important realizations was that the logic for printing all subarrays and substrings is essentially the same. The transition from handling primitive arrays to String objects is seamless once you understand how to manage indices using loops and s.charAt(). 🔹 Algorithmic Efficiency: We explored how to find the Longest Palindromic Substring by: Breaking down the problem: First, ensure you can print every possible substring. Optimizing the search: Reversing the size loop allows you to find the longest potential candidate first. Two-Pointer Palindrome Check: Implementing a check using two indexing variables (i and j) to compare characters from both ends without the overhead of reversing the string. 🔹 Debugging & Exceptions: We had a fascinating discussion on StringIndexOutOfBoundsException. A key insight was how the way you write your code—such as storing a value in a variable versus printing it directly—can determine exactly when and how an exception is triggered during execution. 🔹 Practical Application: Beyond theory, we implemented logic to: Find if one string is a contiguous substring of another. Count occurrences of a specific substring within a larger text. Handle case sensitivity using equalsIgnoreCase() for more robust comparisons. The Road Ahead: The session concluded with a "six-output" challenge—a complex assignment requiring us to reverse individual words in a sentence, count character lengths, and manipulate sentence structures (e.g., "India is my country"). As we move into a short break, the goal is clear: consistency. Whether it's five hours of deep practice or solving just two problems on the worst of days, staying in touch with the code is what builds mastery. #Java #Coding #SoftwareDevelopment #Algorithms #DataStructures #LearningJourney TAP Academy
To view or add a comment, sign in
-
-
Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
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