Today, I revised one of the most fundamental and interview-critical topics in Java — Strings. This cheat sheet covers the complete academic understanding of Java Strings, including: 🔹 Definition & Types Strings as objects in Java Immutable vs Mutable Strings String class usage 🔹 Ways to Create Strings Using new keyword Without new (String Literal) Using Character Array 🔹 Memory Concepts (Core Understanding) Heap Area String Constant Pool (SCP) Difference between SCP and Heap How duplicates are handled Memory behavior with new vs literals 🔹 String Comparison Techniques == (Reference comparison) .equals() (Value comparison) .equalsIgnoreCase() .compareTo() (Returns +ve / -ve / 0 based on lexicographical order) 🔹 Concatenation Using + operator Using .concat() Memory behavior during concatenation 🔹 Important In-Built Methods length() charAt() toLowerCase() / toUpperCase() indexOf() / lastIndexOf() startsWith() / endsWith() substring() split() toCharArray() 🔹 Key Concepts Immutability behavior Why strings cannot be modified directly How methods create new objects Character-by-character comparison logic Unicode-based comparison in compareTo() Understanding Strings deeply is not just about syntax — it’s about memory behavior, object handling, and method mechanics, which are frequently tested in technical interviews. Consistency in revising fundamentals builds confidence and clarity in coding. 🚀 #Java #JavaProgramming #CoreJava #JavaDeveloper #Programming #CodingLife #SoftwareEngineering #TechLearning #ComputerScience #Developers #InterviewPreparation #JavaStrings #LearningJourney #CodeNewbie #TapAcademy #codingdaily
Mastering Java Strings: Definition, Types, and Memory Concepts
More Relevant Posts
-
Day 22: Built-in Methods in Strings & compareTo() in Java 🔤 Today’s learning focused on powerful String built-in methods and how Java performs string comparison using compareTo(). 🔹 Built-in Methods in String Class Java provides many useful methods to manipulate strings: length() → Returns the length of the string charAt(index) → Returns character at specified index substring(start, end) → Extracts part of a string indexOf() → Returns first occurrence index lastIndexOf() → Returns last occurrence index replace() → Replaces characters replaceAll() → Replaces using regex toLowerCase() → Converts to lowercase toUpperCase() → Converts to uppercase trim() → Removes leading & trailing spaces split() → Splits string into array 📌 These methods make string manipulation easy and efficient in Java. 🔹 String Comparison using compareTo() The compareTo() method compares two strings lexicographically (alphabetical order) based on ASCII/Unicode values. It performs a three-way comparison: ✅ Returns 0 → if both strings are equal ➕ Returns positive value → if first string is greater ➖ Returns negative value → if first string is smaller ✨ Unlike equals() (two-way comparison), compareTo() helps in sorting strings in ascending or descending order. #Day22 #Java #StringsInJava #CompareTo #CoreJava #Programming #LearningJourney #TAPAcademy
To view or add a comment, sign in
-
-
Day 22 – Reference Variables in Java Today I explored an important concept in Object-Oriented Programming — Reference Variables. Unlike primitive variables, reference variables store the address of an object, not the actual value. 🔹 What is a Reference Variable? A reference variable is a non-primitive variable that refers to an object created from a class. It is declared using the class name. Syntax: ClassName referenceVariable; Initialization- referenceVariable = new ClassName(); Or both together: ClassName referenceVariable = new ClassName(); Here: ClassName → Name of the class referenceVariable → Object reference new → Keyword used to create an object ClassName() → Constructor 🔹 Example class Demo5 { int x = 100; int y = 200; } class MainClass3 { public static void main(String[] args) { Demo5 d1 = new Demo5(); System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); System.out.println("modifying x & y"); d1.x = 300; d1.y = 400; System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); } } Output: x = 100 y = 200 modifying x & y x = 300 y = 400 🔹 Important Observation When we write: Demo5 d1 = new Demo5(); Java performs three things: 1️⃣ Creates a reference variable (d1) 2️⃣ Creates a new object in memory 3️⃣ Stores the object reference in the variable #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 5/30 – Java DSA Challenge 🔎 Problem 42: 1248. Count Number of Nice Subarrays (LeetCode – Medium) Today’s problem helped me understand one of the most powerful Sliding Window counting patterns 🔥 🧠 Problem Summary Given an integer array nums and an integer k, a subarray is called nice if it contains exactly k odd numbers. 🎯 Return the total number of such subarrays. 💡 Key Insight Instead of directly counting subarrays with exactly k odd numbers, we use this powerful formula: ✅ Exactly(K) = AtMost(K) − AtMost(K − 1) This converts a difficult counting problem into two simpler sliding window problems. 🔄 Approach 1️⃣ Write a helper function to count subarrays with at most k odd numbers 2️⃣ Use sliding window: Expand right pointer If odd count exceeds k, shrink from left Add (window size) to answer 3️⃣ Final answer = atMost(k) - atMost(k - 1) ⏱ Time Complexity O(n) – Each element is processed at most twice 📦 Space Complexity O(1) – No extra data structures used 📌 Pattern Learned ✔ Sliding Window – Variable Size ✔ Subarray Counting Pattern ✔ Exactly K = AtMost(K) − AtMost(K−1) This pattern is extremely important for interview problems like: Subarrays with exactly K distinct elements Binary subarrays with sum K Nice subarrays 🔥 42 Problems Completed Day 5 = Advanced Sliding Window Concepts Strengthened Consistency + Pattern Recognition = DSA Growth 🚀 #Day5 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 11/30 – Java DSA Challenge 🔎 Problem 57: 1011. Capacity To Ship Packages Within D Days (LeetCode – Medium) Day 11 focused on understanding one of the most important interview patterns — Binary Search on Answer 🔥 🧠 Problem Summary You are given an array weights[] representing package weights placed on a conveyor belt and an integer days. 🎯 The goal is to find the minimum ship capacity required to ship all packages within the given number of days. ⚠️ Constraint: Packages must be shipped in order Ship capacity cannot be exceeded on any day 💡 Key Insight Instead of trying every possible capacity sequentially, we observe: ✅ Higher ship capacity → fewer days needed ✅ Lower ship capacity → more days required This monotonic behavior allows us to apply: ✅ Binary Search on Minimum Possible Answer 🔄 Approach 1️⃣ Minimum capacity = maximum weight in array 2️⃣ Maximum capacity = sum of all weights 3️⃣ Apply Binary Search between this range 4️⃣ For each capacity: Simulate shipping process Check if packages can be shipped within given days 5️⃣ If possible → try smaller capacity 6️⃣ Else → increase capacity ⏱ Time Complexity O(N log(Sum of Weights)) 📦 Space Complexity O(1) 📌 Pattern Learned ✔ Binary Search on Answer ✔ Greedy Simulation ✔ Optimization Problems ✔ Capacity Allocation Logic 🔥 Binary Search Progress So Far Understanding when to apply Binary Search beyond sorted arrays is a major milestone in DSA preparation. Problems like this improve intuition for real interview-level optimization questions 💪 🔥 57 Problems Completed ✅ Day 11 Completed — Binary Search Concepts Strengthened Consistency + Pattern Recognition = Growth 🚀 #Day11 #30DaysOfCode #Java #DSA #LeetCode #BinarySearch #ProblemSolving #InterviewPrep #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 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
-
-
Spend a little time comparing Strings in Java and you’ll quickly run into behavior that doesn’t line up with intuition. Literal reuse, hidden pooling, new objects, silent interning… it all adds up to results that look identical but definitely aren’t. If you’ve ever seen two Strings with the same value behave completely differently, this article explains why. https://bit.ly/4tvWSxF
To view or add a comment, sign in
-
Day 42 of My DSA Journey 🚀 | Basic String Operations in Java 🧠 Summary: Demonstrate common string operations in Java such as comparison, length calculation, substring extraction, case conversion, and character traversal. 💡 Key Concepts: • String immutability • == vs .equals() comparison • Case-insensitive comparison • Built-in string methods • Character iteration 🧠 Approach: This program explores several commonly used String methods. Step-by-step operations: • Declaration Two ways to create strings: → Using string literal → Using the new keyword • String Comparison → == checks if two references point to the same object. → .equals() compares actual string values. → .equalsIgnoreCase() compares values ignoring case differences. • String Methods → length() returns number of characters. → charAt(index) retrieves character at given position. → substring(start,end) extracts part of a string. → toUpperCase() converts characters to uppercase. → toLowerCase() converts characters to lowercase. → contains() checks if a substring exists. • String Traversal → Iterate through the string using a loop and access characters using charAt(). 🔧 Practical Usage / Why This Matters: • Processing user input in applications • Validating text-based data • Parsing messages or logs • Formatting and transforming text data 🌱 What I Learned Today: I strengthened my understanding of Java String methods and how object comparison differs from value comparison. 🙌 If you're preparing for placements, let’s connect and grow together! #dsa #datastructures #algorithms #java #javadeveloper #javaprogramming #dsainjava #strings #stringalgorithms #codinginterview #leetcode #geekforgeeks #codingpractice #interviewpreparation #100daysofcode #developerjourney #softwaredeveloper #problemSolving
To view or add a comment, sign in
-
-
🚀 Day 25 – Core Java | Method Overloading & Compile-Time Polymorphism Today’s session was not just about syntax. It was about understanding how Java actually thinks. We deeply explored one of the most important OOP concepts: 🔹 Method Overloading ✔ Multiple methods ✔ Same method name ✔ Within the same class ✔ Different parameter list But we didn’t stop at the definition. 🔎 What Really Happens Internally? We understood the 3 Rules Java Compiler Follows: 1️⃣ Method Name 2️⃣ Number of Parameters 3️⃣ Type of Parameters And this happens during Compilation Phase, not execution. That’s why method overloading is called: Compile-Time Polymorphism Static Binding Early Binding False Polymorphism 🔹 Type Promotion If an exact match is not found, Java performs implicit type casting (type promotion) and selects the closest possible method. Example: int can promote to long or float. Understanding this prevents major confusion in interviews. 🔹 Ambiguity If two methods are equally eligible after type promotion → Java throws: “Method is ambiguous” That means even the compiler gets confused. This is where most candidates fail in interviews. 🔹 Real Example of Method Overloading in Java We discovered something powerful: System.out.println() itself is overloaded. It accepts: int float double char String Object We were using overloading from Day 1 — but never realized it. That realization changes perspective. 💡 Biggest Takeaway Anyone can say: “Method overloading means multiple methods with same name.” But very few can explain: Compiler rules Type promotion Ambiguity Real-world example Internal behavior That difference is what creates interview impact. Day 25 strengthened OOP fundamentals before moving deeper into Object-Oriented Programming pillars. Consistency + Clarity + Practice = Confidence 🚀 #Day25 #CoreJava #MethodOverloading #Polymorphism #JavaInterview #OOPS #DeveloperJourney
To view or add a comment, sign in
-
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
To view or add a comment, sign in
-
Explore related topics
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