🔢 Why Does 0123 Print as 83 in Java? 🤔 While working on constructors today, I came across an interesting behavior in Java that reminded me how subtle details in syntax can completely change what your code does! When I wrote this line 👇 Student objectTwo = new Student(0123); I expected it to print 123. But instead, the console output was: 83 So what’s happening here? 💡 In Java, when a number starts with a leading zero (0), it is interpreted as an octal (base 8) number — not a decimal one. Let’s decode it: 0123 (octal) = 1×8² + 2×8¹ + 3×8⁰ = 64 + 16 + 3 = 83 (decimal) Hence, Java prints 83! --- 🧩 Takeaway: ✅ 123 → Decimal (Base 10) ✅ 0123 → Octal (Base 8) ✅ 0x123 → Hexadecimal (Base 16) ✅ 0b1010 → Binary (Base 2) --- 💬 Lesson: Tiny syntax details can make a big difference. Always watch out for leading zeros in numeric literals — they might silently convert your values to something unexpected! --- 🔖 #Java #ProgrammingTips #Developers #CodeLearning #JavaBasics #CodingCommunity #SoftwareEngineering #TechLearning
Why Java Interprets 0123 as 83: A Subtle Syntax Trap
More Relevant Posts
-
✨ Throw vs Throws In Java, exception handling is a critical part of writing robust and reliable applications. Understanding when to use throw and throws ensures cleaner code, better error handling. 🔹 throw Keyword throw is used inside a method to explicitly create and throw an exception. It is typically used for custom or conditional exception handling. ✅ Use case: Throwing a specific exception when a condition fails. throw new IllegalArgumentException("Invalid Input"); 🔹 throws Keyword throws is used in the method signature to declare that a method may throw one or more exceptions. It simply informs the caller to handle or propagate those exceptions. ✅ Use case: Declaring checked exceptions that the method does not handle internally. void readFile() throws IOException 🚀 Key Differences at a Glance ▪️ throw → Actively throws an exception. ▪️ throws → Declares possible exceptions. ▪️ throw → Used inside a method. ▪️ throws → Used in method declaration. ▪️ throw → Can throw only one exception at a time. ▪️ throws → Can declare multiple exceptions. #CoreJava #exceptionhandling #throwvsthrows #Programming
To view or add a comment, sign in
-
-
💡 Anonymous Classes vs Lambda Expressions in Java Ever wondered why we rarely see anonymous inner classes in modern Java code anymore? That’s because lambdas quietly took their place. ⚡ Let’s rewind a bit — Before Java 8, if you wanted to provide a short implementation for an interface or override a method just once, you had to write an anonymous inner class. Example 👇 Runnable r = new Runnable() { public void run() { System.out.println("Running with anonymous class..."); } }; new Thread(r).start(); Clean? Not really 😅 Now enter Lambda Expressions in Java 8 — A simpler, shorter way to express the same logic: Runnable r = () -> System.out.println("Running with lambda!"); new Thread(r).start(); ✅ Both achieve the same result. The difference? Lambdas made our code concise, readable, and closer to functional programming. 💬 Key takeaway: Anonymous classes still have their place — especially when you need to extend a class or override multiple methods — but for single-method interfaces, lambdas are the clean, modern choice. Write less. Read more. Think functional. #Java #LambdaExpressions #AnonymousClasses #CleanCode #JavaDeveloper #ProgrammingTips
To view or add a comment, sign in
-
-
Method References in Java 8: Clean, Readable Ways to Wire Methods 📚 In Java 8, method references (the :: syntax) offer a clean shorthand for lambdas that simply call an existing method. They cover static methods, instance methods, and constructors, letting you reduce boilerplate while keeping the intent clear. 💡 They shine when a lambda would just delegate to a single method. For example, instead of x -> x.toString(), you can write Object::toString; instead of s -> s.length(), you can use String::length. 🚀 Common patterns and quick wins: - Static method reference: list.sort(String::compareToIgnoreCase) - Instance method reference on a specific object: System.out::println - Instance method reference for any object of a type: String::toUpperCase (as a Function<String, String>, e.g., list.stream().map(String::toUpperCase)) - Constructor reference: ArrayList::new (as Supplier<List<T>>), or Person::new (as Function<Args, Person>) ⚡ Why it matters: method references reduce boilerplate, improve readability, and pair nicely with streams and collections. The caveat: not every lambda can be replaced, and overusing them can hurt clarity if the method call chain becomes opaque. Always ensure the functional interface matches. 🎯 What’s your take? Where have you found method references most valuable in production code, and where did you prefer a lambda for clarity? #Java8 #JavaTips #SoftwareEngineering #Programming #CodeQuality
To view or add a comment, sign in
-
Reverse of a number : To reverse a given number in Java, use a loop to extract digits from the number one by one and build the reversed number. Here’s a clear Java program using a while loop, commonly recommended for beginners. import java.util.Scanner; public class ReverseNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number to reverse: "); int number = scanner.nextInt(); int reverse = 0; while (number != 0) { int digit = number % 10; // Get last digit reverse = reverse * 10 + digit; // Shift and add number /= 10; // Remove last digit } System.out.println("Reversed Number: " + reverse); } } Explanation: The loop extracts the last digit using number % 10.It multiplies the reversed number by 10 and adds the extracted digit.The original number is divided by 10 in each iteration to remove the last digit. #JavaProgramming #LearnJava #JavaBasics #CodingChallenge #ProgrammingTips #CodeNewbie #DeveloperLife #100DaysOfCode #JavaDeveloper #SoftwareDevelopment #CodingPractice #TechLearning #ProgrammingCommunity
To view or add a comment, sign in
-
☕ Understanding final, finally, and finalize() in Java These three keywords may sound similar, but they serve completely different purposes in Java! Let’s clear the confusion 👇 🔹 final (Keyword) Used for declaring constants, preventing inheritance, or stopping method overriding. final variable → value can’t be changed final method → can’t be overridden final class → can’t be inherited 👉 Example: final int MAX = 100; 🔹 finally (Block) Used in exception handling to execute important code whether or not an exception occurs. Perfect for closing files, releasing resources, or cleaning up memory. 👉 Example: try { int a = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("This will always execute"); } 🔹 finalize() (Method) It’s a method called by the Garbage Collector before an object is destroyed. Used to perform cleanup operations before object removal (though it’s deprecated in newer Java versions). 👉 Example: protected void finalize() { System.out.println("Object destroyed"); } --- 💡 Quick Summary: Keyword Used For Level final Restriction (variable, method, class) Compile-time finally Cleanup code block Runtime finalize() Object cleanup (GC) Runtime --- #Java #Programming #FinalFinallyFinalize #JavaDeveloper #ExceptionHandling #TechLearning #Coding
To view or add a comment, sign in
-
-
#Day-66) LeetCode 474. Ones and Zeroes – Java DP Solution Just tackled a classic knapsack-style problem using 2D Dynamic Programming in Java. 🧩 Problem: Given a list of binary strings and limits on the number of 0s (m) and 1s (n), find the largest subset such that the total number of 0s and 1s stays within bounds. 🧠 Java Approach: Count 0s and 1s for each string Use a dp[m+1][n+1] table to track the max subset size Iterate backwards to preserve previous states and avoid reuse 💡 Why It Works: This mirrors the 0/1 knapsack pattern — each string is like an item with a cost (0s and 1s) and a value (1). Reverse iteration ensures we don’t double-count. #Java #DynamicProgramming #LeetCode #CodingChallenge #TechPrep #ProblemSolving #PranshuCodes #LinkedInLearning 😊
To view or add a comment, sign in
-
-
Today, I explored one of the most important concepts in Java — the Collection Framework. It plays a major role in handling and manipulating groups of objects efficiently. Here’s what I learned 👇 ✅ Collection Interface – The root interface for working with groups of objects. ✅ List Interface – Allows duplicate elements and maintains insertion order. Examples: ArrayList, LinkedList, Vector ✅ Set Interface – Does not allow duplicate elements. Examples: HashSet, LinkedHashSet, TreeSet ✅ Queue Interface – Used to hold elements in FIFO (First In, First Out) order. Examples: PriorityQueue, LinkedList ✅ Map Interface – Stores key-value pairs. Examples: HashMap, TreeMap, LinkedHashMap 💬 What I found interesting: ArrayList is great for fast access but slower in insert/delete. LinkedList is better for frequent insertions/deletions. HashSet and HashMap provide excellent performance for lookups. 📚 The Java Collection Framework makes data handling more flexible, powerful, and clean — a must-know for every Java developer. #Java #Collections #1000010000 Coders#Programming #Learning #SoftwareDevelopment #CodingJourney
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