Here are some fun basic Java code snippets to refresh the fundamental understanding. Guess the output! How many did you get right? 1.➡️ public class OverloadExample { public void show(Object obj) { System.out.println("Cat"); } public void show(String str) { System.out.println("Dog"); } public static void main(String[] args) { OverloadExample example = new OverloadExample(); example.show(null); } } 2.➡️ public class ConstructorTest { void ConstructorTest() { System.out.println("Hello"); } public static void main(String[] args) { ConstructorTest ct = new ConstructorTest(); } } 3.➡️ public class IncrementTest { public static void main(String[] args) { int x = 5; System.out.println(x++ + ++x); } } 4.➡️ public class LoopTest { public static void main(String[] args) { int i = 0; for(; i < 3; i++); System.out.println(i); } } 5.➡️ public class BooleanTest { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; System.out.println(b1 & b2); System.out.println(b1 && b2); } } 6.➡️ class Main { public static void main(String[] args) { boolean b = false; System.out.println(b & test()); System.out.println("============================"); System.out.println(b && test()); } public static boolean test() { System.out.println("Called"); return false; } } 7.➡️ public class CastTest { public static void main(String[] args) { double d = 9.78; int i = (int) d; System.out.println(i); } } 8.➡️ public class PrePostTest { public static void main(String[] args) { int x = 2; int y = x++ * 3 + ++x; System.out.println(y); } } 9.➡️ public class CharTest { public static void main(String[] args) { char c = 'A'; c += 1; System.out.println(c); } } 10. ➡️public class LogicalTest { public static void main(String[] args) { int a = 5, b = 10; System.out.println(a < b || b++ < 15); System.out.println(b); } }
Java Code Snippets: Guess the Output
More Relevant Posts
-
🚀 Day 15 of 30 Days Java Challenge — StringBuilder vs StringBuffer in Java 💡 🔹 What’s the problem with normal Strings? In Java, Strings are immutable — that means once created, their value cannot be changed. Whenever you modify a string (like concatenating or replacing text), Java actually creates a new String object, which can be inefficient when you do it many times. 📘 Example: String name = "John"; name = name + " Doe"; Here, Java creates two String objects: "John" "John Doe" If you do this in a loop, it wastes both memory and time. 🔹 Enter StringBuilder and StringBuffer Both are mutable classes — meaning you can change the content without creating new objects. Feature StringBuilder StringBuffer Mutability ✅ Mutable ✅ Mutable Thread-safe ❌ No ✅ Yes Performance 🚀 Faster 🐢 Slightly slower Use case Single-threaded code Multi-threaded code 💡 Real-world Example Imagine you’re building an app that generates usernames for a list of users. Using StringBuilder: public class UsernameGenerator { public static void main(String[] args) { String[] names = {"Alice", "Bob", "Charlie"}; StringBuilder sb = new StringBuilder(); for (String name : names) { sb.append("user_").append(name.toLowerCase()).append(" "); } System.out.println(sb.toString()); } } ✅ Output: user_alice user_bob user_charlie Here, we only used one StringBuilder object to build the final string efficiently — no extra objects were created in the process. 💡 Thread-safe Example (StringBuffer) If multiple threads are updating the same string, use StringBuffer to avoid data corruption. StringBuffer sb = new StringBuffer(); sb.append("Processing "); sb.append("data..."); System.out.println(sb); 🎯 Key Takeaways Use StringBuilder → when working in a single-threaded environment (most common). Use StringBuffer → when working in multi-threaded environments. Both are more efficient than using normal String for repeated concatenations. 🧩 Real-life Analogy Think of String as a sealed envelope — if you want to change the message, you must write a new letter. But StringBuilder is like a whiteboard — you can erase and rewrite easily! 💬 What’s your pick? Do you mostly use StringBuilder or StringBuffer in your code? Share your thoughts below 👇 #Java #CodingChallenge #LearningJourney #StringBuilder #StringBuffer #JavaBeginners
To view or add a comment, sign in
-
-
"🚀Day 43 of 50 – Java LeetCode Challenge" Today’s challenge was "20. Valid Parentheses" — a fundamental stack-based problem that strengthens your understanding of bracket matching and data structure usage. The goal is to determine whether a given string of parentheses is valid based on correct opening and closing order. ⏱ Today’s Task – Valid Parentheses 📝 Problem Statement: Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. ✅ A string is valid if: 1️⃣ Every open bracket has a corresponding closing bracket of the same type. 2️⃣ Brackets are closed in the correct order. 3️⃣ Every close bracket must have an open bracket before it. 🧪 Examples: Input: s = "()" Output: true ✅ Input: s = "()[]{}" Output: true ✅ Input: s = "(]" Output: false ❌ Input: s = "([])" Output: true ✅ Input: s = "([)]" Output: false ❌ 🔧 Constraints: 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}' 💻 My Java Solution: import java.util.*; class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put('}', '{'); map.put(']', '['); for (char c : s.toCharArray()) { if (map.containsKey(c)) { char top = stack.isEmpty() ? '#' : stack.pop(); if (top != map.get(c)) return false; } else { stack.push(c); } } return stack.isEmpty(); } } 🔍 Takeaways: ✅ Efficient use of a stack for bracket matching ✅ Clean implementation using a HashMap for bracket pairs ✅ Time complexity O(n) — single traversal through the string ✅ Space complexity O(n) — in worst case (all open brackets) 💡 Core Concepts: Stack data structure HashMap for mapping bracket pairs Iterative traversal and validation Balanced parenthesis logic 🎯 Day 43 completed — 7 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Stack #DataStructures #Day43 #JavaProgramming #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
Java 2025: Smart, Stable, and Still the Future 💡Perfect 👩💻 ☕ Day 5: Tokens in Java In Java, tokens are the smallest building blocks of a program — like words in a sentence. When you write any Java code, the compiler breaks it into tokens to understand what each part means. There are 6 main types of tokens in Java 👇 🔑 1️⃣ Keywords Definition: Keywords are predefined, reserved words that Java uses for specific purposes. They tell the compiler how to interpret parts of the code. Key Points: 1. Keywords cannot be used as identifiers (like variable or class names). 2. All keywords are written in lowercase (e.g., public, class, if, return). 💡 Example: public class Example { int num = 10; } Here, public, class, and int are keywords. 🏷️ 2️⃣ Identifiers Definition: Identifiers are names given to variables, methods, classes, or objects — created by the programmer. Key Points: 1. They must start with a letter, underscore _, or dollar sign $. 2. Java is case-sensitive, so Name and name are different identifiers. 💡 Example: age, StudentName, calculateTotal() 🔢 3️⃣ Literals Definition: Literals represent fixed values that don’t change during program execution. Key Points: 1. They define constant values like numbers, text, or booleans. 2. Java supports different literal types — integer, float, string, char, and boolean. 💡 Example: int a = 10; String name = "Sneha"; boolean isJavaFun = true; ➕ 4️⃣ Operators Definition: Operators are symbols that perform actions on variables and values — like calculations or comparisons. Key Points: 1. They help in arithmetic, logical, and relational operations. 2. Operators simplify expressions and control decision-making in programs. 💡 Example: int sum = a + b; if (a > b) { ... } 🧱 5️⃣ Separators Definition: Separators are special symbols that separate and structure code elements in Java. Key Points: 1. They organize code blocks, statements, and method calls. 2. Common separators include (), {}, [], ;, and ,. 💡 Example: int arr[] = {1, 2, 3}; System.out.println(arr[0]); 💬 6️⃣ Comments Definition: Comments are non-executable text in a program used to describe, explain, or document the code. Key Points: 1. Comments improve code readability and maintenance. 2. They come in three types — single-line, multi-line, and documentation. 💡 Example: // This is a single-line comment /* This is a multi-line comment */ /** Documentation comment */ 🧠 In Summary Token Type Purpose Example Keyword Predefined reserved word public, class Identifier User-defined name name, add() Literal Constant value 10, "Hello" Operator Performs operation +, == Separator Structures code (), {} Comment Adds explanation // note #Day5OfJava #JavaLearning #JavaTokens #LearnJava #CodeDaily #JavaBasics #ProgrammersJourney #100DaysOfCode #JavaConcepts #CodingWithSneha
To view or add a comment, sign in
-
-
Java ke parallel universe ke secrets! 🔥 --- Post 1: Java ka "Hidden Class" API - Java 15+ ka best kept secret!🤯 ```java import java.lang.invoke.*; public class HiddenClassMagic { public static void main(String[] args) throws Throwable { MethodHandles.Lookup lookup = MethodHandles.lookup(); byte[] classBytes = getClassBytes(); // Bytecode bytes // Hidden class banayi jo reflection mein visible nahi hogi! Class<?> hiddenClass = lookup.defineHiddenClass(classBytes, true).lookupClass(); MethodHandle mh = lookup.findStatic(hiddenClass, "secretMethod", MethodType.methodType(void.class)); mh.invoke(); // ✅ Chalega but Class.forName() se nahi milegi! } } ``` Secret: Hidden classes reflection mein visible nahi hoti, par perfectly work karti hain!💀 --- Post 2: Java ka "Thread Local Handshakes" ka JVM level magic!🔥 ```java public class ThreadHandshake { static { // JVM internally sab threads ko pause kiye bina // single thread ko stop kar sakta hai! // Ye Java 9+ mein aaya for better profiling // -XX:ThreadLocalHandshakes=true } } ``` Internal Use Cases: · Stack sampling without stopping all threads · Lightweight performance monitoring · Better garbage collection Secret: JVM ab single thread ko individually manipulate kar sakta hai! 💡 --- Post 3: Java ka "Contended" annotation for false sharing prevention!🚀 ```java import jdk.internal.vm.annotation.Contended; public class FalseSharingFix { // Ye do variables different cache lines mein store honge! @Contended public long value1 = 0L; @Contended public long value2 = 0L; } ``` JVM Option Required: ``` -XX:-RestrictContended ``` Performance Impact: Multi-threaded apps mein 30-40%performance improvement! 💪 --- Post 4: Java ka "CDS Archives" - Application startup 10x faster!🔮 ```java // Kuch nahi karna - bas JVM options use karo: // Dump CDS archive: // -Xshare:dump -XX:SharedArchiveFile=app.jsa // Use CDS archive: // -Xshare:on -XX:SharedArchiveFile=app.jsa ``` Internal Magic: · Pre-loaded classes shared memory mein · Startup time dramatically kam · Memory footprint reduce Result: Spring Boot apps 3-4 seconds se 400-500ms startup!💀 ---
To view or add a comment, sign in
-
🎯 Modern Java Null Handling: DTO vs Domain Objects - The Right Way! NullPointerException is still the #1 runtime error in Java applications. Let me share a battle-tested approach 👇 📌 The Problem We All Face: Your API receives JSON with nullable fields: { "userId": "123", "email": "user@example.com", "phoneNumber": null, "address": null } Traditional approach? Null checks everywhere! 😫 if (user.getPhone() != null) { if (!user.getPhone().isEmpty()) { sendSMS(user.getPhone()); } } 🎯 The Modern Solution: Layer 1️⃣ - DTO Layer (API Boundary) Keep it nullable for flexibility: public record UserRequest( String userId, String email, String phoneNumber, // nullable AddressDTO address // nullable ) Layer 2️⃣ - Domain Layer (Business Logic) Use Optional for clarity: public class User { private final String userId; private final String email; private final Optional<String> phoneNumber; private final Optional<Address> address; public void sendNotification(NotificationService service) { phoneNumber.ifPresent(phone -> service.sendSMS(phone, "Welcome!") ); address.ifPresentOrElse( addr -> service.sendMail(email, "Delivery: " + addr), () -> service.sendMail(email, "Add delivery address") ); } } Layer 3️⃣ - Safe Conversion public User toDomain() { return new User( userId, email, Optional.ofNullable(phoneNumber) .filter(p -> !p.isBlank()), Optional.ofNullable(address) .map(AddressDTO::toDomain) ); } 🚀 Real-World Benefits: ✅ No Null Checks: Code remains clean and readable ✅ Type Safety: Compiler tells you what's optional ✅ Self-Documenting: Optional clearly means "may not exist" ✅ Stream-Friendly: flatMap(Optional::stream) filters empties elegantly ✅ Testability: Mock-free unit tests, no null edge cases 💡 Golden Rules I Follow: 1️⃣ DTOs can be nullable (API contracts need flexibility) 2️⃣ Domain objects use Optional (business logic clarity) 3️⃣ Never return null from domain methods 4️⃣ Use Optional.ofNullable() at conversion boundaries 5️⃣ Combine with Stream API for powerful filtering ⚡ Power Combo Example: List<String> validPhones = users.stream() .map(User::getPhoneNumber) .flatMap(Optional::stream) // Magic! Filters empties .filter(phone -> phone.startsWith("+91")) .toList(); 🎓 Key Takeaway: The pattern isn't just about Optional - it's about separating concerns: DTOs handle external world (nulls exist) Domain handles business rules (Optional expresses intent) Conversion layer bridges them safely This follows DDD principles while keeping APIs backward-compatible! #Java #CleanCode #SoftwareArchitecture #DomainDrivenDesign #NullSafety #BestPractices #SpringBoot #BackendDevelopment #EnterpriseJava #CodeQuality #Optional #DTO #DDD #JavaDevelopers #SoftwareEngineering #TechTips #Programming #FullStackDevelopment
To view or add a comment, sign in
-
"🚀 Day 44 of 50 – Java LeetCode Challenge" Today’s challenge was “228. Summary Ranges” — a neat array-based problem that enhances your understanding of iteration, range detection, and string manipulation in Java. The goal is to summarize continuous sequences of numbers into compact range strings. ⏱ Today’s Task – Summary Ranges 📝 Problem Statement: You are given a sorted unique integer array nums. A range [a, b] is defined as all integers from a to b (inclusive). Return the smallest sorted list of ranges that covers all numbers in the array exactly. Each range should be represented as: "a->b" if a != b "a" if a == b 🧪 Examples: Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] ✅ Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] ✅ 🔧 Constraints: 0 <= nums.length <= 20 -2³¹ <= nums[i] <= 2³¹ - 1 All values are unique and sorted in ascending order 💻 My Java Solution: import java.util.*; class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int start = nums[0]; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1] + 1) { if (start == nums[i - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[i - 1]); } start = nums[i]; } } if (start == nums[nums.length - 1]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[nums.length - 1]); } return result; } } 🔍 Takeaways: ✅ Efficient handling of continuous integer sequences ✅ Smart use of loop tracking and condition checks ✅ Clean, readable implementation with O(n) time complexity ✅ Handles edge cases gracefully (like empty arrays or single elements) 💡 Core Concepts: 📘 Array traversal and pattern detection 📘 String concatenation and list building 📘 Conditional logic for sequence grouping 🎯 Day 44 completed — 6 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #DataStructures #JavaProgramming #Day44 #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
🚗 Tricky Java Bug — “When Ola’s Cache Broke Serialization: The serialVersionUID Mystery 🧩” 🎬 The Scene At Ola, a backend dev cached user data using Java serialization. Everything ran perfectly in staging. But the moment they deployed a new version… 💥 java.io.InvalidClassException: com.ola.user.UserInfo; local class incompatible: stream classdesc serialVersionUID = 124578, local class serialVersionUID = 987654 Suddenly, users vanished from cache faster than an Ola cab during rain 😅 💣 The Root Cause When Java serializes an object, it stores a unique identifier — serialVersionUID. If you don’t explicitly declare it, JVM generates one automatically based on class structure (fields, methods, etc.). So when someone adds or removes a field later, boom — the calculated ID changes, and deserialization fails because the stored bytes no longer match the “current version” of the class. ⚙️ The Problem Code public class UserInfo implements Serializable { private String name; private int age; private String city; } Then one fine day… someone adds a new field: private String gender; 💣 Old cache data can’t deserialize anymore. ✅ The Fix Always define a fixed serialVersionUID to maintain compatibility: public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; private String city; private String gender; // newly added } 🧩 Quick Debugging Tips 🔍 Check the exception message — it always mentions both stream and local IDs. 🧠 Use serialver tool to generate UID for older class versions. 🚫 Don’t rely on JVM-generated IDs if your class might evolve over time. 💾 When backward compatibility isn’t needed — clear the cache before redeploy. 🔄 Consider using JSON-based cache (like Redis with Jackson) for human-readable, version-tolerant data. ✅ Quick Checklist ☑️ Always declare serialVersionUID manually. ☑️ Avoid unnecessary structural changes in serializable classes. ☑️ For distributed cache, prefer JSON serialization over Java native. ☑️ Be aware that adding/removing fields changes serialization compatibility. 💬 Real Talk At Ola, one dev said: > “My cache invalidated itself before I could even write the logic for it!” 😅 Lesson: In Java, serialVersionUID isn’t just a number — it’s your backward compatibility insurance policy. #Java #Serialization #Ola #TrickyBugs #Cache #BackendDevelopment #SpringBoot #Debugging #Developers #TechHumor #Concurrency #Microservices #JavaInterview #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Arrays, Loops, or Streams: Which One Is Faster in Java? When working with Java, one question appears again and again: “What’s faster for iterating and processing data: arrays, traditional loops, or streams?” Here’s the straight answer: 👉 Arrays with a traditional for loop are almost always the fastest. 👉 Streams are slower, but offer readability and easy parallelization. Let’s break it down. 🧠 1. Arrays — The Fastest Option Arrays are the simplest and most direct structure in the JVM. They live in a continuous block of memory and allow direct index access. ✔ Why are arrays faster? ✅Direct access via array[i] ✅Zero iterator or object overhead ✅No boxing/unboxing ✅Excellent CPU cache locality Best for: 🟢 High-performance scenarios 🟢Large datasets 🟢Fixed-size collections 🔁 2. Traditional Loops — The Best Balance Using for or enhanced for on an ArrayList is extremely fast and predictable. The JVM heavily optimizes these loops during JIT compilation. ✔ Why are loops fast? ✅ Minimal overhead ✅No extra object allocation ✅Very friendly to JVM optimizations Best for: 🟢Most general Java applications 🟢Dynamic-sized collections 🟢Scenarios needing both speed and readability 🌊 3. Streams — Modern, Clean, but Not Always Fast Streams bring functional style, expressiveness, and powerful transformations. But they pay for it with overhead. ✔ Why are streams slower? 📛 Create internal objects (Stream, lambdas, iterators) 📛Pipeline stages add layers of abstraction 📛Can trigger boxing/unboxing (e.g., Stream<Integer>) ✔ When streams shine 🟢Complex transformations 🟢Data filtering and mapping 🟢Readable, declarative code 🟢Easy parallelization with .parallel() ⚠ When to avoid streams 📛Hot code paths 📛Low-level performance-critical loops 📛Very small operations where abstraction cost dominates 🥇 So… Which One Is Actually Faster? StructurePerformanceBest Use CaseArray + for loop 🥇 FastestHigh-performance, fixed-size structuresArrayList + for loop 🥈 Very fastGeneral-purpose programmingStreams 🥉 SlowerReadability & functional transformationsParallel Streams⚡ 🏆 Fast for large workloadsCPU-heavy, large datasets 📌 Final Conclusion If performance is your priority: 👉 Use arrays with traditional loops. If you want clean, expressive code: 👉 Use streams. If you’re processing large CPU-intensive workloads: 👉 Consider parallelStream() — it may outperform everything else. 🔖 #Java #SpringBoot #Array #BackendDevelopment #SoftwareEngineering #APIDevelopment #JavaDeveloper #BackendEngineer
To view or add a comment, sign in
-
-
Java Has Evolved — Here’s What Changed from JDK 8 to JDK 17 🚀 ☕ JDK 8 (2014) — The Modern Java Revolution Major Features: ✅ Lambda Expressions → Functional programming style ✅ Stream API → Process collections efficiently ✅ Functional Interfaces → @FunctionalInterface, Predicate, Function, etc. ✅ Default & Static Methods in Interfaces ✅ Optional Class → Avoid NullPointerException ✅ Date and Time API (java.time) → New modern date/time handling ✅ Nashorn JavaScript Engine ⚙️ JDK 9 (2017) — Modular Java Key Features: 🧩 Module System (Project Jigsaw) → module-info.java JShell (REPL) → Interactive Java shell Stream API Enhancements → takeWhile(), dropWhile(), iterate() Private Methods in Interfaces Factory Methods for Collections → List.of(), Set.of(), Map.of() ⚙️ JDK 10 (2018) — Developer Productivity Key Features: 🔹 Local Variable Type Inference → var keyword Garbage Collector Improvements (G1) Application Class-Data Sharing Parallel Full GC for G1 ⚙️ JDK 11 (2018) — LTS Release (Long-Term Support) Key Features: 🌐 New HttpClient API → Replaces old HttpURLConnection String Methods → isBlank(), lines(), strip(), repeat() Lambda Parameter Type Inference Removed Java EE & CORBA modules Single-file Source Code Execution → java Hello.java ⚙️ JDK 12 (2019) Key Features: 🧮 Switch Expressions (Preview) → switch usable as an expression JVM Constants API Shenandoah GC (low-pause-time GC) ⚙️ JDK 13 (2019) Key Features: 📜 Text Blocks (Preview) → Multi-line strings using """ Switch Expression Enhancements Reimplementation of Legacy Socket API ⚙️ JDK 14 (2020) Key Features: 🧱 Records (Preview) → Immutable data carriers (record Point(int x, int y)) 🕵️ Pattern Matching for instanceof (Preview) 🧍♂️ Helpful NullPointerException Messages Switch Expressions (Standardized) ⚙️ JDK 15 (2020) Key Features: 🧩 Sealed Classes (Preview) → Restrict which classes can extend a class Text Blocks (Standard) Hidden Classes EdDSA Algorithm Support (New Crypto) ⚙️ JDK 16 (2021) Key Features: 🧱 Records (Standard) 🕵️ Pattern Matching for instanceof (Standard) JEP 391: macOS/AArch64 support (Apple M1) Vector API (Incubator) Strong Encapsulation of JDK Internals ⚙️ JDK 17 (2021) — LTS Release Key Features: 🧩 Sealed Classes (Standard) 🕵️ Pattern Matching for switch (Preview) 🧱 Enhanced Pseudo-Random Number Generators (PRNG) Foreign Function & Memory API (Incubator) New macOS Rendering Pipeline (Metal API) Removed Deprecated RMI Activation, Applet API, etc.
To view or add a comment, sign in
More from this author
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
For 1- Cat hoping null is object 2-hello 3-11 4-i i i 5- no idea for bitwise operation False 7- 9 8-9 9- B 10- true 11 Let me know who many has correct outbof 9🤩