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
Java String Methods & compareTo() Explained
More Relevant Posts
-
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
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
-
-
Journey Today I solved the Anagram String Problem in Java. An anagram means two strings contain the same characters with the same frequency, just arranged in a different order. Example: listen → silent ✅ triangle → integral ✅ 🔍 What I practiced today: String traversal Converting String to char[] using toCharArray() Using Arrays.sort() for comparison Understanding character frequency logic Improving problem-solving thinking 💡 One important learning: Small mistakes like case sensitivity (toCharArray() not tocharArray()) can break the entire program. Attention to detail matters! Consistency is teaching me more than talent ever could. Every day I understand Java a little deeper. 36 days completed. No breaks. Just progress. 💪 #Day36 #CodingJourney #Java #Anagram #ProblemSolving #100DaysOfCode #Consistency #Learning My code ===== //import java.util.Arrays; class Solution { public static boolean areAnagrams(String s1, String s2) { // code here char a[]=s1.toCharArray(); char b[]=s2.toCharArray(); Arrays.sort(a); Arrays.sort(b); if(a.length!=b.length) { return false; } for(int i=0;i<a.length;i++) { if(a[i]!=b[i]) { return false; } } return true; } }
To view or add a comment, sign in
-
-
Day 37 - 🚀 Rules of Method Overriding in Java Method Overriding is a key concept in Object-Oriented Programming (OOP) that allows a subclass to provide a specific implementation of a method already defined in its superclass. It helps achieve Runtime Polymorphism in Java. 📌 Important Rules of Method Overriding: 🔹 1. Same Method Name The method in the subclass must have the same name as in the superclass. 🔹 2. Same Method Parameters The number, type, and order of parameters must be exactly the same. 🔹 3. Return Type The return type must be the same or a covariant type (subtype) of the parent method. 🔹 4. Access Modifier Rule The subclass method cannot reduce visibility. Example: ✔ protected → public ✔ default → protected ❌ public → private 🔹 5. Final Methods Cannot Be Overridden If a method is declared final, it cannot be overridden. 🔹 6. Static Methods Cannot Be Overridden Static methods belong to the class and are method hidden, not overridden. 🔹 7. Private Methods Cannot Be Overridden Private methods are not inherited, so they cannot be overridden. 🔹 8. Exception Handling Rule The child class method cannot throw broader checked exceptions than the parent method. 🔹 9. Use @Override Annotation Using @Override helps the compiler check whether the method is correctly overridden. 💡 Conclusion: Method Overriding enables runtime polymorphism, making Java programs more flexible, maintainable, and scalable. #Java #OOP #MethodOverriding #JavaProgramming #ProgrammingConcepts #SoftwareDevelopment
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 22 - Built-in Methods in Strings & compareTo() in Java Strings in Java are immutable, but the String class provides powerful built-in methods for efficient text handling. ✅ Commonly Used Methods in String length() → returns string length charAt(index) → access character by index substring() → extract part of a string toUpperCase() / toLowerCase() → case conversion trim() → remove leading & trailing spaces replace() → replace characters or substrings contains() → check substring presence startsWith() / endsWith() → prefix & suffix checks equals() / equalsIgnoreCase() → content comparison 🔹 compareTo() Method Used to compare strings lexicographically (dictionary order). String a = "Apple"; String b = "Banana"; a.compareTo(b); // negative value 🔸 Return Values 0 → both strings are equal > 0 → first string is greater < 0 → first string is smaller 📌 Comparison is based on Unicode values and checks characters one by one. 🔹 compareTo() vs equals() compareTo() → ordering & sorting equals() → equality check 🔑 Key Takeaway ✔ Use equals() to check equality ✔ Use compareTo() for sorting and ordering logic #Java #String #CoreJava #Programming #JavaDeveloper #Coding #SoftwareEngineering
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
-
-
Day 38 - 🚀 Understanding toString() in Java In Java, the toString() method is used to return a string representation of an object. It belongs to the Object class, which means every Java class inherits it by default. 📌 Default Behavior If you don't override toString(), Java prints a combination of class name + hashcode. class Person { String name; int age; } Person p = new Person(); System.out.println(p); Output: Person@1a2b3c This output is usually not very useful for users or developers. 📌 Overriding toString() To display meaningful object information, we override the toString() method. class Person { String name; int age; @Override public String toString() { return "Person[name=" + name + ", age=" + age + "]"; } } Output: Person[name=John, age=25] 📌 Why toString() is Important ✔ Provides a human-readable representation of objects ✔ Useful for debugging and logging ✔ Makes object data easier to print and understand 💡 Pro Tip Always use the @Override annotation when implementing toString() to ensure the method is correctly overridden. ✅ Conclusion The toString() method helps convert an object into a clear and readable string format, making debugging and displaying data much easier in Java applications. #Java #OOP #JavaProgramming #ToString #ProgrammingConcepts #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
-
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