Most of us, when we started Competitive Programming in Java, understood that using the Scanner class for taking inputs and System.out.print() for outputs can make our programs slower, so we quickly switched to BufferedReader and BufferedWriter by following a standard template, which improved the execution time. I decided to understand both to see how they differ and what makes the latter one faster. Honestly, the logic was simple. BufferedReader and BufferedWriter use a buffer to store a large chunk of an input stream in a single I/O operation, then break it up internally according to the needs, using a StringTokenizer or any other means. Scanner does internal parsing and reads input token by token. It performs extra processing like regex matching, which makes it convenient but slower. It also takes care of token validation internally. BufferedReader works differently. It reads a large chunk of data into memory at once (a buffer) and then processes it. Instead of interacting with the input stream repeatedly, it reduces the system calls made. It just reads the stream and does not do any special parsing. Moreover, Scanner is also not thread safe. This doesn’t mean Buffered Reader is better than Scanner in any way, though; it depends on specific use cases and what we want. I decided to learn Java I/O properly and tried to understand how input/output streams and reader/writer classes work. It was fun. 😊 It fascinates me how engineers have tailored systems with clever techniques for several use cases. Happy Coding :) #Java #Coding #CompetitiveProgramming #SoftwareEngineering
BufferedReader vs Scanner in Java: Performance Comparison
More Relevant Posts
-
🚀 Day 14/30 – Java DSA Challenge 🔎 Problem 64: 1614. Maximum Nesting Depth of the Parentheses (LeetCode – Easy) Continuing Day 14 with another fundamental problem focused on Stack usage and Parentheses Processing, which is a very common interview pattern. 🧠 Problem Summary Given a valid parentheses string, the task is to determine the maximum nesting depth. 👉 Nesting depth represents how many parentheses are open simultaneously at any point. Example: (1+(2*3)+((8)/4))+1 Here, digit 8 lies inside 3 nested parentheses, so the answer is 3. 💡 Key Insight Every time we encounter: "(" → Depth increases ")" → Depth decreases So, tracking currently open parentheses helps us determine the maximum depth reached during traversal. A Stack naturally models this behavior. 🔄 Approach Used 1️⃣ Traverse the string character by character 2️⃣ Push '(' into stack when opening bracket appears 3️⃣ Pop when closing bracket appears 4️⃣ Track maximum stack size during traversal 5️⃣ Maximum stack size = Maximum nesting depth ⏱ Complexity Analysis Time Complexity: 👉 O(N) — Single traversal of string Space Complexity: 👉 O(N) — Stack storage in worst case 📌 Concepts Strengthened ✔ Stack Data Structure ✔ Parentheses Validation Logic ✔ Depth Tracking ✔ String Traversal ✔ Simulation Technique 📈 Learning Reflection Problems like this highlight how simple data structures elegantly solve structural problems. Understanding stack behavior builds strong foundations for: Expression evaluation Compiler parsing Balanced parentheses problems ✅ Day 14 Progress Update 🔥 64 Problems Solved — Still Consistent Small daily improvements → Long-term mastery 🚀 #Day14 #30DaysOfDSA #Java #LeetCode #Stack #DSAJourney #ProblemSolving #CodingConsistency #InterviewPreparation #LearningEveryday
To view or add a comment, sign in
-
-
Day 14 of Programming - 🚀 Sorted Arrays in Java – Quick Guide Sorting arrays is one of the most common tasks in programming. Java provides a simple way to sort arrays using the Arrays.sort() method from the java.util package. 🔹 Example: Sorting an Integer Array import java.util.Arrays; public class SortArray { public static void main(String[] args) { int[] numbers = {5, 3, 8, 1, 2}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); } } ✅ Output: [1, 2, 3, 5, 8] 🔹 Key Points ✔ Arrays.sort() sorts elements in ascending order by default ✔ Works with int, double, char, String, and objects ✔ For objects, implement Comparable or Comparator 🔹 Example: Sorting a String Array String[] days = {"Saturday", "Monday", "Wednesday", "Thursday", "Tuesday"}; Arrays.sort(days); 📌 Output: [Monday, Saturday, Thursday, Tuesday, Wednesday] 💡 Tip: Sorting is often used in searching, data analysis, and algorithm optimization. #Java #Programming #Coding #JavaDeveloper #DataStructures #Arrays #TechLearning #SoftwareDevelopment
To view or add a comment, sign in
-
-
Day 40 - 🚀 Polymorphism in Java – One Interface, Many Forms Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) in Java. It allows an object to take many forms, meaning the same method name can perform different tasks depending on the object. 📌 Definition Polymorphism is the ability of a method or object to behave differently based on the context, even though it has the same name. Types of Polymorphism in Java 🔹 Compile-Time Polymorphism (Method Overloading) Multiple methods with the same name but different parameters. class Calculator { int add(int a, int b){ return a + b; } int add(int a, int b, int c){ return a + b + c; } } 🔹 Runtime Polymorphism (Method Overriding) A child class provides a specific implementation of a method defined in the parent class. class Animal { void sound(){ System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound(){ System.out.println("Dog barks"); } } Animal a = new Dog(); a.sound(); // Output: Dog barks Key Points ✔ Achieved through method overloading and method overriding ✔ Helps in code reusability and flexibility ✔ Uses inheritance and dynamic method dispatch 💡 Polymorphism makes Java programs more flexible, scalable, and maintainable. #Java #OOP #Programming #Polymorphism #JavaDeveloper #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚫 Why Java Doesn’t Allow Implicit Narrowing (and that’s a good thing!) While working with data types in Java, one interesting design decision stands out. ✅ Java allows implicit type casting (widening) Example: int → long Because there’s no risk of data loss, Java handles it automatically. ❌ But when it comes to narrowing (large → small data type) Example: long → int Java does NOT allow it implicitly. 💡 Reason? To prevent unintentional data loss. Instead, Java forces you to be explicit — putting the responsibility on the developer. A small feature, but a big reason why Java is considered a safe and reliable language 💻 #Java #Programming #Developers #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Java Casting: Upcasting vs Downcasting Understanding type casting in Java is essential for mastering Object-Oriented Programming and Polymorphism. 🔹 Upcasting (Child → Parent) When a child class object is referenced using a parent class reference. Example: Parent ref = new Child(); ✔ Done implicitly by the compiler ✔ Used to achieve runtime polymorphism ⚠ Child-specific methods cannot be accessed directly. 🔹 Downcasting (Parent → Child) When a parent reference is cast back to a child type. Example: Child c = (Child) ref; ✔ Done explicitly by the developer ✔ Allows access to child-specific methods ⚠ Must be used carefully to avoid ClassCastException at runtime. 💡 Key Takeaway: Upcasting = Moving up the class hierarchy (safe & automatic) Downcasting = Moving down the hierarchy (manual & needs caution) Mastering these concepts helps in writing flexible, reusable, and polymorphic Java code. #Java #JavaProgramming #OOP #Polymorphism #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
💡 Why does System.out.print(); sometimes give a compile-time error? While learning Java, you might write something like this: System.out.println("A"); System.out.print(); System.out.println("X"); and get a compile-time error. Why does this happen? 🤔 ✔️ The reason: System.out.print(); prints output without moving to a new line, but this method requires an argument. When you leave it empty, the compiler doesn’t know what it should print, so it throws a compile-time error. In simple words 👉 print() must be given something to print. ✔️ How to fix it: 📍 If you want a blank line: System.out.println(); 📍 If you want to print a space: System.out.print(" "); Small mistakes like this help us understand how Java methods really work 💻✨ What other small Java mistakes helped you understand programming better? Drop them in the comments 👇 #Java #Programming #LearningJava #CodingBasics #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 15/30 – Java DSA Challenge 🔎 Problem 66: 20. Valid Parentheses (LeetCode – Easy) Continuing Day 15 with one of the most fundamental and frequently asked interview problems — Valid Parentheses. This problem strengthens understanding of: ✅ Stack Data Structure ✅ Balanced Bracket Validation ✅ Order-Based Matching Logic 🧠 Problem Summary You are given a string containing only: '(', ')', '{', '}', '[' , ']' A string is valid if: ✔ Open brackets are closed by the same type ✔ Brackets are closed in correct order ✔ Every closing bracket has a corresponding opening bracket 🎯 Goal: Return true if the string is valid, otherwise false. 💡 Key Insight This is a classic LIFO (Last-In-First-Out) problem. Opening brackets → Push into stack Closing brackets → Check top of stack If mismatch → Invalid At the end: ✔ Stack must be empty for the string to be valid. 🔄 Approach Used 1️⃣ Traverse the string 2️⃣ Push opening brackets into stack 3️⃣ For closing bracket: If stack empty → invalid Pop and check if matching type 4️⃣ After traversal → check if stack is empty ⏱ Complexity Analysis Time Complexity: 👉 O(N) Space Complexity: 👉 O(N) 📌 Concepts Strengthened ✔ Stack Fundamentals ✔ Parentheses Matching ✔ LIFO Principle ✔ Conditional Validation Logic ✔ Edge Case Handling 📈 Learning Reflection This problem may be Easy level, but it builds the foundation for: Expression evaluation Syntax validation Compiler parsing logic Advanced stack problems Strong fundamentals → Strong problem-solving ability. ✅ Day 15 Progress Update 🔥 66 Problems Solved in 30 Days DSA Challenge Consistency + Strong Basics = Long-Term Growth 🚀 #Day15 #30DaysOfDSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #InterviewPreparation #Consistency #DSALearning
To view or add a comment, sign in
-
-
🚀 Day 16/30 – Java DSA Challenge 🔎 Problem 69: 150. Evaluate Reverse Polish Notation (LeetCode – Medium) Today’s problem focused on evaluating expressions written in Reverse Polish Notation (RPN) — also known as Postfix Expression. This problem strengthens: ✅ Stack fundamentals ✅ Expression evaluation ✅ Operator handling ✅ Order of operations without parentheses 🧠 Problem Summary We are given an array of strings representing a mathematical expression in Reverse Polish Notation. We must evaluate the expression and return the result. Key Points: Valid operators: +, -, *, / Division truncates toward zero No division by zero Expression is always valid 💡 Why Stack is Perfect Here? In RPN: Operands come first Operator comes after its operands Example: ["2","1","+","3","*"] Which translates to: ((2 + 1) * 3) = 9 Core Logic: 1️⃣ If token is a number → Push to stack 2️⃣ If token is an operator → Pop top two numbers Apply operation Push result back to stack At the end, the stack contains the final result. ⏱ Complexity Analysis Time Complexity: O(N) Space Complexity: O(N) Each token is processed exactly once. 📌 Concepts Reinforced ✔ Stack-based expression evaluation ✔ Understanding postfix notation ✔ Order of operand handling (important for subtraction & division) ✔ Clean and structured operator handling 📈 Learning Reflection This problem shows how powerful stacks are when dealing with expressions. Unlike infix expressions (which require precedence rules and parentheses), postfix expressions simplify evaluation — making stack the ideal data structure. Mastering these fundamentals builds strong foundations for: Expression parsing Compiler design basics Advanced algorithm problems ✅ Day 16 Progress Update 🔥 69 Problems Solved in 30 Days DSA Challenge Consistency. Logic. Growth. 🚀 #Day16 #30DaysOfDSA #Java #LeetCode #Stack #Algorithms #ProblemSolving #CodingJourney #InterviewPreparation
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
-
-
I learned a surprising Java concept. Two Java keywords exist… But we can’t actually use them. They are: • goto • const Both are reserved keywords in Java. But if you try to use them, the compiler throws an error. So why do they exist? Let’s start with goto. In older languages like C and C++, goto allowed jumping to another part of the code. Sounds powerful, right? But it often created messy and confusing programs — commonly called “spaghetti code.” When Java was designed, the creators decided to avoid this problem completely. Instead of goto, Java encourages structured control flow using: break continue return This makes programs easier to read and maintain. Now the second keyword: const. In languages like C/C++, const is used to declare variables whose value cannot change. Java handles this differently using the final keyword. Example: final int x = 10; Once declared final, the value cannot be modified. And here’s the interesting part Java kept goto and const as reserved words so developers cannot accidentally use them as identifiers. Sometimes the smartest design decision in a programming language is what it chooses NOT to include. Learning programming isn’t just about syntax. It’s about understanding why the language was designed this way. A special thanks to my mentor Syed Zabi Ulla for explaining programming concepts with such clarity and always encouraging deeper understanding rather than just memorizing syntax. #Java #Programming #Coding #LearnToCode #DeveloperJourney
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
Thanks for sharing 😊👍🏻