💡 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
Java substring() behavior in permutations algorithm
More Relevant Posts
-
🚨 Java Myth Buster: “Finally block always executes” — Really? 🤔 Most developers confidently say: 👉 “Yes, finally always runs!” ❌ Let’s break that myth with a real example 👇 --- 💻 Code Example: public class Test { public static void main(String[] args) { try { System.out.println("Inside try"); System.exit(1); } finally { System.out.println("Inside finally"); } } } --- 📌 Output: Inside try 😳 Wait… where is the "finally" block? --- 💡 Explanation (Simple & Clear): When "System.exit(1)" is executed: - 🚫 JVM shuts down immediately - 🚫 No further code executes - 🚫 "finally" block is completely skipped --- 🔢 Understanding Exit Codes: - "System.exit(0)" → Normal termination ✅ - "System.exit(1)" → Abnormal termination ❌ 👉 But important point: Both will skip the "finally" block! --- ⚠️ So when does finally NOT execute? ✔️ When JVM is forcefully terminated ✔️ Using "System.exit()" ✔️ JVM crash / system failure ✔️ Infinite loop (control never reaches finally) --- 🧠 Interview Takeaway: 👉 “Finally block executes in almost all cases, except when JVM terminates abruptly like with System.exit().” --- 🔥 This is one of the most asked tricky Java interview questions! 💬 Did you know this before? #Java #JavaDeveloper #CodingInterview #Programming #TechTips #Developers #InterviewQuestions #JavaBasics
To view or add a comment, sign in
-
📌 Method References in Java — Cleaner Than Lambdas Method references provide a concise way to refer to existing methods using lambda-like syntax. They improve readability when a lambda simply calls an existing method. 1️⃣ What Is a Method Reference? Instead of writing a lambda: x -> System.out.println(x) We can write: System.out::println --- 2️⃣ Syntax ClassName::methodName Used when: • Lambda just calls an existing method • No additional logic is required --- 3️⃣ Types of Method References 🔹 Static Method Reference ClassName::staticMethod Example: Integer::parseInt --- 🔹 Instance Method Reference (of object) object::instanceMethod Example: System.out::println --- 🔹 Instance Method Reference (of class) ClassName::instanceMethod Example: String::length --- 🔹 Constructor Reference ClassName::new Example: ArrayList::new --- 4️⃣ Example Comparison Using Lambda: list.forEach(x -> System.out.println(x)); Using Method Reference: list.forEach(System.out::println); --- 5️⃣ Benefits ✔ More readable code ✔ Less boilerplate ✔ Cleaner functional style ✔ Works seamlessly with Streams --- 🧠 Key Takeaway Method references are a shorthand for lambda expressions that call existing methods. Use them when they improve clarity, not just to shorten code. #Java #Java8 #MethodReference #FunctionalProgramming #BackendDevelopment
To view or add a comment, sign in
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
𝙒𝙝𝙮 𝙙𝙤 𝙎𝙩𝙖𝙩𝙞𝙘 𝘽𝙡𝙤𝙘𝙠𝙨 𝙚𝙭𝙚𝙘𝙪𝙩𝙚 𝙤𝙣𝙡𝙮 𝙤𝙣𝙘𝙚 𝙞𝙣 𝙅𝙖𝙫𝙖 ? After my previous post on Order of Execution, a follow-up question naturally came to mind: 👉 Why does a Static Block execute only once in Java? The answer lies in 𝐂𝐥𝐚𝐬𝐬 𝐋𝐨𝐚𝐝𝐢𝐧𝐠. 📝 Key Concept In Java, Static Blocks belong to the Class, not to Objects. When the JVM loads a class into memory, it performs class initialization. During this phase, all static variables and static blocks are executed. And here’s the important part: ➡️A class is loaded only once by the JVM ➡️ Therefore Static Blocks execute only once 👨💻 Example 𝐜𝐥𝐚𝐬𝐬 𝐓𝐞𝐬𝐭 { 𝐬𝐭𝐚𝐭𝐢𝐜 { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐒𝐭𝐚𝐭𝐢𝐜 𝐛𝐥𝐨𝐜𝐤 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝"); } 𝐓𝐞𝐬𝐭() { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); } } 📌 𝐎𝐮𝐭𝐩𝐮𝐭 𝐒𝐭𝐚𝐭𝐢𝐜 𝐛𝐥𝐨𝐜𝐤 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 👉 Notice something interesting? Even though three objects are created, the Static Block runs only once. 📍Simple way to remember Class loads once ➡️ Static block runs once Object created multiple times ➡️Constructor runs multiple times Understanding these small JVM behaviors makes many Java interview questions much easier. Did you know this earlier? Or is this something you recently discovered? Let’s discuss in the comments 💬 #Java #JavaDeveloper #JavaBackend #TechJourney #TechInsights #LearnBySharing #Programming #JavaConcepts #JVM
To view or add a comment, sign in
-
• Why Does Java Use 2 Bytes for "char"? At first glance, this can feel confusing… =>Why does Java use 2 bytes (16 bits) for a single character, when older languages used just 1 byte? Let’s break it down : -> The Core Reason: Unicode Support Java uses the Unicode standard to represent characters. 1) Unicode is designed to support a wide range of global character sets 2) It includes scripts like Latin, Devanagari, Chinese, Arabic, and more =>To accommodate this, Java chose 16 bits (2 bytes) for "char" => What Does 2 Bytes Mean? - 1 byte = 8 bits - 2 bytes = 16 bits =>This allows representation of up to 65,536 distinct values =>Why Not 1 Byte Like C/C++? Languages like C/C++ were originally based on ASCII: • 1 byte (8 bits) → limited character range => Java, on the other hand, was designed with broader character representation in mind. • Important Insight Java uses UTF-16 encoding for "char" 1) Most commonly used characters fit within 2 bytes 2) Some characters are represented using surrogate pairs --> Conclusion Java’s choice of 2 bytes for "char" is rooted in its design around Unicode-based character representation rather than ASCII limitations. #Java #Programming #Unicode #SoftwareEngineering #BackendDevelopment #Java #CoreJava #JavaDeveloper #JVM #ProgrammingConcepts #BackendDeveloper #DevelopersOfLinkedIn #Tech #Coding
To view or add a comment, sign in
-
-
Think var in Java is just about saving keystrokes? Think again. When Java introduced var, it wasn’t just syntactic sugar — it was a shift toward cleaner, more readable code. So what is var? var allows the compiler to automatically infer the type of a local variable based on the assigned value. Instead of writing: String message = "Hello, Java!"; You can write: var message = "Hello, Java!"; The type is still strongly typed — it’s just inferred by the compiler. Why developers love var: Cleaner Code – Reduces redundancy and boilerplate Better Readability – Focus on what the variable represents, not its type Modern Java Practice – Aligns with newer coding standards But here’s the catch: Cannot be used without initialization Only for local variables (not fields, method params, etc.) Overuse can reduce readability if the type isn’t obvious Not “dynamic typing” — Java is still statically typed Pro Insight: Use var when the type is obvious from the right-hand side — avoid it when it makes the code ambiguous. Final Thought: Great developers don’t just write code — they write code that communicates clearly. var is a tool — use it wisely, and your code becomes not just shorter, but smarter. Special thanks to Syed Zabi Ulla and PW Institute of Innovation for continuous guidance and learning support. #Java #Programming
To view or add a comment, sign in
-
-
Thread Life Cycle in Java 1. NEW (Thread Created) 👉 Meaning: Thread object is created, but not started yet. Example: Thread t = new Thread(() -> { System.out.println("Running"); }); 📌 State: t.getState(); // NEW 2. RUNNABLE (Ready + Running) 👉 Meaning: Thread is ready to run and may be executing. ⚠️ In Java: RUNNING is part of RUNNABLE OS decides when it runs Example: t.start(); // Goes to RUNNABLE 📌 State: RUNNABLE 3. BLOCKED (Waiting for Lock) 👉 Meaning: Thread is waiting to acquire monitor lock. Example: synchronized(obj) { // other thread holds lock } If lock busy → BLOCKED. 4. WAITING (Waiting Indefinitely) 👉 Meaning: Thread waits until another thread wakes it. Caused by: wait() join() park() Example: obj.wait(); // WAITING 5. TIMED_WAITING (Waiting for Time) 👉 Meaning: Thread waits for a fixed time. Caused by: sleep(1000) wait(1000) join(1000) Example: Thread.sleep(1000); // TIMED_WAITING 6. TERMINATED (Dead) 👉 Meaning: Thread finished execution. Example: run() ends → TERMINATED #Java #Multithreading #interview #sde #interviewpreparation #ThreadLifecycle
To view or add a comment, sign in
-
First Latter Count In Java Interview : ----------------------------------- What it does: Splits the string into words → ["Hello", "World", "Java"] Takes first letter of each word → H, W, J Joins them → "HWJ" Which DSA concept is this?: ---------------------------- This is not a heavy DSA problem, but it involves some basic DSA + programming concepts: 1. String Processing Splitting strings Extracting substrings Core concept: String manipulation 2. Array / List Traversal str.split() → gives an array Iterating over elements (via stream) DSA base: Linear traversal (O(n)) 3. Functional Programming (Java Streams) map() → transformation collect() → aggregation Not DSA, but modern Java programming paradigm 4. Basic Algorithm Pattern This follows a simple pattern: Input → Transform each element → Combine results Complexity Time: O(n) (n = number of words) Space: O(n) (for storing split words)
To view or add a comment, sign in
-
-
Solved a classic DSA problem today – Valid Anagram Given two strings, the challenge is to check whether they are anagrams of each other. Day - 1 Input: s = "listen", t = "silent" Output: true Input: s = "hello", t = "world" Output: false 🔹 Approach 1 (Best - O(n) Time, O(1) Space) 👉 Character frequency count use karo (array of size 26) Code (Java) Java public class ValidAnagram { public static boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] count = new int[26]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i) - 'a']++; count[t.charAt(i) - 'a']--; } for (int c : count) { if (c != 0) return false; } return true; } public static void main(String[] args) { System.out.println(isAnagram("listen", "silent")); // true System.out.println(isAnagram("hello", "world")); // false } } ✅ Time Complexity: O(n) ✅ Space Complexity: O(1) (fixed 26 size array) 🔹 Approach 2 (Normal - Sorting Method) 👉 Dono strings ko sort karo, fir compare karo Code Java import java.util.Arrays; public class ValidAnagramSort { public static boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; char[] a = s.toCharArray(); char[] b = t.toCharArray(); Arrays.sort(a); Arrays.sort(b); return Arrays.equals(a, b); } } ⏱ Time Complexity: O(n log n) 💾 Space Complexity: O(n) #Raghavgarg #day1 #streak #raghav #DSASTREAKWITHPWSKILLS #RAGHAV #dsa #pw #pwskills #pw #pwskills #raghavgarg Raghav Garg
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
-
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
Very helpful, keep posting ☺️