🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
Java String args in main() Explained
More Relevant Posts
-
🧠 Java Interview Question 👉 How to find duplicate characters in a String? Example: Input: "programming" Output: g, r, m Simple approach using HashMap: import java.util.HashMap; public class DuplicateCharacter { public static void main(String[] args) { String str = "programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : map.keySet()) { if (map.get(c) > 1) { System.out.println(c); } } } } 💡 Logic: Count frequency of each character and print duplicates. 👉 Have you solved this in a different way? #Java #SpringBoot #Coding #InterviewQuestions #BackendDeveloper
To view or add a comment, sign in
-
🚀 Java Interview Trap: Why "finally" Can Hide Exceptions 🤯 This is a dangerous one that many developers miss Example: public class Test { public static void main(String[] args) { try { throw new RuntimeException("Error in try"); } finally { throw new RuntimeException("Error in finally"); } } } 👉 Output: Exception in thread "main" java.lang.RuntimeException: Error in finally 🤔Where did the original exception go? 💡 What’s happening? - Exception thrown in try ❌ - finally block executes - New exception in finally overrides the original 👉 Original exception is LOST 😱 🔥 Why this is dangerous? - You lose actual root cause - Debugging becomes very hard - Production issues become confusing ✅ Better Approach: try { throw new RuntimeException("Error in try"); } catch (Exception e) { throw e; // preserve original } finally { System.out.println("Cleanup done"); } ⚠️ Interview Twist: try { return 10; } finally { throw new RuntimeException("Oops"); } 👉 Method will NOT return 10 ❌ 👉 Exception will be thrown instead 😳 💥 Golden Rule: ❌ Never throw exceptions from finally ❌ Avoid return in finally ✅ Use it only for cleanup 🎯 Pro Tip: Use try-with-resources instead of complex finally blocks #Java #JavaInterview #CodingInterview #Developers #Programming #TechTips
To view or add a comment, sign in
-
🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
To view or add a comment, sign in
-
🔥 Day 8: equals() vs == in Java (Very Important Interview Topic) This is one of the most commonly asked Java interview questions — and also one of the most misunderstood! 👇 🔹 == (Double Equals) Compares memory/reference location Checks if two objects point to the same memory String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false ❌ 🔹 equals() Method Compares actual content (values) Defined inside Object class (can be overridden) String a = new String("Java"); String b = new String("Java"); System.out.println(a.equals(b)); // true ✅ 🔹 String Special Case (String Pool) String x = "Hello"; String y = "Hello"; System.out.println(x == y); // true ✅ 👉 Because both refer to same object in String Pool 💡 Pro Tip: Always use equals() for comparing object values — especially Strings! 📌 Final Thought: "== checks if objects are the same, equals() checks if values are the same." #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Tech #Learning #Day8 #JavaBasics
To view or add a comment, sign in
-
-
💡 Java Interview Question How do you find the common elements from three lists in Java? Here’s a simple example: ✅ Two approaches: Using retainAll() with Set Using Java 8 Streams public class CommonElementFrom3List { public static void main(String[] args){ List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7); List<Integer> list3 = Arrays.asList(5, 6, 7, 8, 3); Set<Integer> common = new HashSet<>(list1); common.retainAll(list2); common.retainAll(list3); System.out.println(common); List<Integer> list = list1.stream() .filter(list2::contains) .filter(list3::contains) .distinct() .collect(Collectors.toList()); System.out.println(list); } } 📌 Output: [3, 5] ❓ Question for you: Which approach would you prefer in a real-world scenario and why? Also, how would you handle duplicate elements efficiently? #Java #CodingInterview #JavaDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
Interview Question: What happens inside the JVM when you create a String in Java? When a String is created in Java, the JVM handles memory allocation and storage differently depending on how the String is defined. 🔹 Case 1: Using String Literal String s1 = "Hello"; String s2 = "Hello"; 👉 Here’s what happens: JVM checks the String Constant Pool If "Hello" already exists → it reuses the same object No new object is created for s2 👉 Both s1 and s2 point to the same memory location 🔹 Case 2: Using new Keyword String s3 = new String("Hello"); 👉 Here’s what happens: JVM creates a new object in heap memory It also ensures "Hello" exists in the String Pool So now there are two objects: One in Heap One in String Pool 🔹 Case 3: Using intern() String s4 = new String("Hello").intern(); 👉 What happens: JVM returns the reference from the String Pool Avoids duplicate objects Main Points To Remember: String literals are stored in the String Constant Pool new String() always creates a new object in heap The String Pool optimizes memory by reusing values intern() ensures reference from the pool #Java #JVM #InterviewQuestions #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
To view or add a comment, sign in
-
🌟 Hello Shining Stars!!! 🙏 💡 Java Type Promotion Hierarchy (Must-Know for Developers) Understanding type promotion is key to avoiding subtle bugs in Java 👇 🔼 Hierarchy (Widening Conversion): byte → short → int → long → float → double char → int → long → float → double ⚡ Golden Rules: 👉 byte, short, and char are automatically promoted to int in expressions 👉 Result = largest data type in the expression 👉 ✅ Promotion (widening) is automatic 👉 ❌ De-promotion (narrowing) is NOT automatic — requires explicit casting 🚨 Edge Case Examples (Tricky but Important): byte a = 10; byte b = 20; byte c = a + b; // ❌ Compilation Error // a + b becomes int → cannot store in byte without casting int x = 130; byte b = (byte) x; // ⚠️ Explicit cast (data loss) // Output will be -126 due to overflow char ch = 'A'; System.out.println(ch + 1); // Output: 66 // 'A' → 65 → promoted to int 🧠 Method vs Constructor Promotion (Important Interview Point): void test(int x) { System.out.println("int method"); } void test(double x) { System.out.println("double method"); } test(10); // Calls int method (exact match preferred over promotion) 👉 In methods, Java allows type promotion during overload resolution 👉 But constructors don’t “prefer” promotion the same way — exact match is prioritized, and ambiguous cases can lead to compilation errors 🎯 Takeaway: Java silently promotes smaller types, but it never automatically demotes them — and overload resolution can surprise you! #Java #Programming #Developers #Coding #InterviewPrep #TechTips 👍 Like | 🔁 Repost | 🔄 Share | 💬 Comment | 🔔 Follow | 🤝 Connect to grow together
To view or add a comment, sign in
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
To view or add a comment, sign in
-
-
🔹 Java Interview Question 🔹 👉 Why is 100% abstraction possible using an Interface but not with an Abstract Class? 📖 Answer: 👉 Interface: An interface contains only method declarations (no implementation). It defines what to do, not how to do it. ✔ Therefore, it provides 100% abstraction (conceptually). 👉 Abstract Class: An abstract class can contain: ✔ Abstract methods (without body) ✔ Concrete methods (with implementation) Because it includes some implementation, it provides only partial abstraction, not 100%. 🔧 Example: interface A { void show(); // no implementation } abstract class B { abstract void display(); // abstract method void print() { // implemented method System.out.println("Hello"); } } 🎯 Conclusion: ✔ Interface → Only method declarations → 100% abstraction ✔ Abstract Class → Declarations + implementation → Partial abstraction 💡 Note: From Java 8 onwards, interfaces can have default and static methods. So technically, they are not purely 100% abstract, but conceptually they are still used to achieve abstraction. #Java #OOP #InterviewPreparation #Programming #AutomationTesting #Learning
To view or add a comment, sign in
-
Explore related topics
- Java Coding Interview Best Practices
- Advanced Programming Concepts in Interviews
- Mock Interviews for Coding Tests
- Approaches to Array Problem Solving for Coding Interviews
- Common Algorithms for Coding Interviews
- Common Coding Interview Mistakes to Avoid
- Amazon SDE1 Coding Interview Preparation for Freshers
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