🚀 Day 14 at Tap Academy – Difference Between Regular Arrays and Jagged Arrays in Java ☘️Today’s concept is one of the most important topics in arrays: Regular Arrays vs Jagged Arrays. Understanding this helps you work efficiently with multi-dimensional data. Let’s explore in simple words 👇 🔷 What is a Regular Array? A Regular Array is also called a Rectangular Array because it forms a rectangle shape. 👉 In this type of array: All rows have the same number of columns Structure is uniform Memory looks like a perfect rectangle 📌 Example (2D Regular Array): int[][] regularArray = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} }; 🧠 Explanation: Rows = 3 Columns = 3 in each row All rows have equal columns → Regular Array 📍 Note: 1D Array is always regular because it has only one dimension 2D and 3D arrays can be regular or jagged 🔶 What is a Jagged Array? A Jagged Array is an array where each row can have a different number of columns. 👉 In this type of array: Rows have different column sizes Structure is not uniform Does not form a rectangle 📌 Example (Jagged Array): int[][] jaggedArray = { {10, 20}, {30, 40, 50}, {60} }; 🧠 Explanation: Row 1 → 2 elements Row 2 → 3 elements Row 3 → 1 element Different column sizes → Jagged Array 📊 Key Observations About Arrays 1️⃣ Dimensionality Arrays can be: 1D Array 2D Array 3D Array Jagged arrays exist only in 2D and 3D arrays 2️⃣ Homogeneous Data Arrays store only same type of data Example: int[] numbers = {10, 20, 30}; // Only integers Cannot store: {10, "Hello", 20.5} ❌ 3️⃣ Regular and Jagged Arrays Regular → Equal columns in all rows Jagged → Unequal columns in rows 4️⃣ Can Objects Be Stored in Arrays? ✅ Yes, arrays can store objects Example: String[] names = {"Ram", "Sita", "Krishna"}; ⚠️ Disadvantages of Arrays ❌ 1. Stores only homogeneous data Array can store only one type of data. Example: int[] arr = {10, 20, 30}; // Only integers allowed ❌ 2. Fixed Size Array size cannot increase or decrease after creation. Example: int[] arr = new int[5]; Size will always remain 5 ❌ 3. Contiguous Memory Allocation Arrays require continuous memory location in RAM If continuous memory is not available → Array cannot be created → Memory error occurs 🆚 Difference Summary Feature. Regular Array. Jagged Array Shape. Rectangle. Irregular Structure. Uniform. Non-uniform Example Matrix. Uneven data 🎯 Real-Life Example Regular Array → Classroom with equal benches in each row 🪑🪑🪑 Jagged Array → Parking lot with different vehicles in each row 🚗🚗 🚗 🚗🚗🚗 💡 Conclusion ✔ Regular Arrays have equal columns and form a rectangle ✔ Jagged Arrays have unequal columns and flexible structure ✔ Arrays store homogeneous data ✔ Arrays have fixed size and require contiguous memory #Java #TapAcademy #LearningJava #Arrays #JaggedArray #RegularArray #Programming #JavaDeveloper #CodingJourney
Java Arrays: Regular vs Jagged Explained
More Relevant Posts
-
🚀 TAP Academy – Day 15 | Introduction to Strings in Java ☕ Today’s concept is one of the most important topics because nearly 70% of real-world data is handled in String format such as names, emails, passwords, addresses, etc. 📌 What is a String? A String is a sequence of characters enclosed within double quotation marks (" "). Ex: String name = "Java"; String email = "student@gmail.com"; 👉 In Java, String is not a primitive data type 📌 Strings are Objects in Java Here, the class name is String 📌 Types of Strings Strings are divided into two types: 1️⃣ Immutable String Immutable means cannot be changed after creation. Ex:(real world) Date of Birth Gender ID number In Java: String s = "Java"; s.concat(" Programming"); System.out.println(s); output: Java Explanation: The original string is NOT changed A new object is created instead 2️⃣ Mutable String Mutable means can be changed after creation. In Java, mutable strings are created using: StringBuilder StringBuffer Example: StringBuilder sb = new StringBuilder("Java"); sb.append(" Programming"); System.out.println(sb); output: Java Programming 📌 3 Ways to Create Immutable Strings ✅Method 1: Using new keyword 🖋️Object is created in Heap memory 🖋️Duplicate objects are allowed 🖋️Creates a new object every time Ex: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); // false Because both have different memory locations. ✅Method 2: Without using new keyword 🖋️Stored in String Constant Pool (SCP) inside heap 🖋️Duplicate objects are NOT allowed 🖋️Memory efficient Ex: String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true Because both refer to same memory location. ✅Method 3: Using Character Array char[] ch = {'J','a','v','a'}; String s = new String(ch); System.out.println(s); Output:Java 👉Converts character array into String object 📌 String Comparison Methods 1️⃣ Using == operator Compares reference (memory address) String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true 2️⃣ Using equals() method Compares values String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1.equals(s2)); // true 3️⃣ Using compareTo() method Compares character by character String s1 = "Java"; String s2 = "Jaya"; System.out.println(s1.compareTo(s2)); Output:-21 4️⃣ Using equalsIgnoreCase() method Compares values ignoring case String s1 = "JAVA"; String s2 = "java"; System.out.println(s1.equalsIgnoreCase(s2)); Output:true 📌 Key Summary Points ✅ String = Collection of characters ✅ == compares address ✅ equals() compares values ✅ compareTo() compares character by character ✅ equalsIgnoreCase() ignores case 📌 Real-World Importance Strings are used everywhere: Login systems Emails Banking systems Student records Web applications Without Strings, real-world software cannot exist. 💼#TAP Academy #Java #String #JavaProgramming #LearningJourney #SoftwareDevelopment #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
📘 Java Learning – Collections Framework (Part 8: SortedMap, TreeMap, Hashtable & Properties) 🗺️🚀 Continuing my Java Collections journey, today I explored Map implementations where ordering, synchronization, and configuration matter. 🔰 SortedMap (I) • Child interface of Map • Stores entries in sorted order of keys (not values) • Sorting can be: • Natural order • Custom order (Comparator) 📌 Key methods: • firstKey(), lastKey() • headMap(), tailMap(), subMap() • comparator() 🔰 TreeMap (C) • Underlying data structure: Red-Black Tree • Entries sorted based on keys • Duplicate keys ❌, duplicate values ✅ • Values can be heterogeneous & non-comparable 📌 Key rules: • Natural sorting → keys must be homogeneous & Comparable • Custom sorting → handled by Comparator 📌 Null behavior: • modern Java, TreeMap does NOT allow null keys • After that → NullPointerException • Null values allowed anytime 📌 Constructors: TreeMap t1 = new TreeMap(); // Natural sorting TreeMap t2 = new TreeMap(Comparator c); // Custom sorting TreeMap t3 = new TreeMap(Map m); TreeMap t4 = new TreeMap(SortedMap m); 🧪 Short Example: TreeMap tm = new TreeMap(); tm.put(3, "Java"); tm.put(1, "Spring"); tm.put(2, "Boot"); tm.put("1", "Program") //ClassCastException tm.put(null, "Demo") // NullPointerException System.out.println(tm); // {1=Spring, 2=Boot, 3=Java} 🔰 Hashtable (C) • Legacy Map class • Fully synchronized → thread-safe • No null key or null value allowed • Slower due to synchronization 📌 Constructors: Hashtable h1 = new Hashtable(); Hashtable h2 = new Hashtable(int capacity); Hashtable h3 = new Hashtable(int capacity, float loadFactor); Hashtable h4 = new Hashtable(Map m); 🧪 Short Example: Hashtable ht = new Hashtable(); ht.put(1, "Java"); ht.put(2, "Spring"); System.out.println(ht); 🔰 Properties (C) • Child class of Hashtable • Used for external configuration • Keys and values must be String • Common use: DB URL, username, password, config values 📌 Advantage: • Change configuration without recompiling code • Only redeployment needed → minimal business impact 📌 Constructor: Properties p = new Properties(); 📌 Important methods: • getProperty() • setProperty() • load(), store() 🧪 Short Example: Properties p = new Properties(); p.setProperty("user", "admin"); p.setProperty("url", "localhost"); System.out.println(p.getProperty("user")); ⭐ Key Takeaways • SortedMap → Sorted keys • TreeMap → Sorted + navigable Map • Hashtable → Thread-safe legacy Map • Properties → Externalized configuration Understanding Maps deeply helps build scalable, configurable, and maintainable Java applications 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #SortedMap #TreeMap #Hashtable #Properties #JavaCollections #LearningJourney
To view or add a comment, sign in
-
📘 Java Learning – Collections Framework (Final Part: Collections Class & Arrays Class) 🚀🎯 Wrapping up my Java Collections journey with two powerful utility classes from java.util package: 👉 Collections class 👉 Arrays class These classes provide utility methods for sorting, searching, reversing, and converting data structures efficiently. 🔰 Collections Class A utility class that provides methods for Collection implemented classes. 📌 Sorting a List Collections.sort(List l); // Natural sorting Collections.sort(List l, Comparator c); // Custom sorting ✔ Elements must be homogeneous & Comparable (for natural sorting) ✔ Null elements not allowed (NullPointerException) 📌 Searching in a List Collections.binarySearch(List l, Object obj); Collections.binarySearch(List l, Object key, Comparator c); ⚠ Important Rules: • List must be sorted before searching • Uses Binary Search algorithm • Successful search → returns index • Unsuccessful search → returns insertion point • Must use same Comparator used for sorting 📌 Reversing a List Collections.reverse(List l); // Reverses list Collections.reverseOrder(); // Returns Comparator (descending) ✔ reverse() → works on List ✔ reverseOrder() → returns Comparator 🔰 Arrays Class Utility class for array operations (primitive & object arrays). 📌 Sorting Arrays Arrays.sort(int[] arr); // Primitive (natural order) Arrays.sort(Object[] arr); // Natural order Arrays.sort(Object[] arr, Comparator c); // Custom sorting ✔ Primitive arrays → only natural sorting ✔ Object arrays → natural or custom sorting 📌 Searching in Arrays Arrays.binarySearch(int[] arr, key); Arrays.binarySearch(Object[] arr, key); Arrays.binarySearch(Object[] arr, key, Comparator c); ✔ Same rules as Collections.binarySearch() 🔰 Converting Array to List List list = Arrays.asList(Object[] arr); ⚠ Important: • Creates a List view, not independent list • Changes in list reflect in array & vice versa • Cannot change size (add/remove → UnsupportedOperationException) • Replacement allowed but type must match (else ArrayStoreException) 🧪 Combined Example Integer[] arr = {30, 10, 20}; Arrays.sort(arr); // Sorting array System.out.println(Arrays.toString(arr)); // [10, 20, 30] int index = Arrays.binarySearch(arr, 20); System.out.println(index); // 1 List list = Arrays.asList(arr); Collections.reverse(list); System.out.println(list); // [30, 20, 10] ⭐ Final Takeaways • Collections → Utility methods for List • Arrays → Utility methods for Arrays • Always sort before binarySearch • asList() creates a fixed-size list view This completes my Java Collections Framework journey 🎯 Understanding these utilities makes data handling more efficient and interview-ready 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #CollectionsClass #ArraysClass #JavaCollections #LearningJourney
To view or add a comment, sign in
-
What actually happens when we use Runnable vs Thread. While studying Java Multithreading, I explored how the Runnable interface works and some interesting cases. Let me Breakdown to you, I. Creating a Thread using Runnable Instead of extending the Thread class, we can implement the Runnable interface. Steps: 1. Create a class that implements Runnable 2. Override the run() method 3. Pass the Runnable object to a Thread 4. Call start() Example: class MyRunnable implements Runnable { public void run() { System.out.println("Child Thread"); } } class ThreadDemo { public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); } } Once start() is called, a new thread is created and the run() method executes. But things become interesting when explore different cases. Case 1: t.start() A new thread is created. The run() method executes in that new thread while the main thread continues running. Case 2: t.run() No new thread is created. run() behaves like a normal method call, and everything runs in the main thread. Case 3: r.run() Again, no thread is created. This simply executes the method like a normal function. Case 4: r.start() This causes a compile-time error. Why? Because the Runnable interface does not contain the start() method. Only the Thread class has it. Why Runnable is Preferred? Java supports single inheritance. If we extend the Thread class, our class cannot extend any other class. But when we implement Runnable: • We still get multithreading • We can extend another class • The design becomes more flexible That’s why the Runnable approach is recommended in real-world applications. II. Thread Names in Java Every thread has a default name like: main Thread-0 Thread-1 We can get or change the name using: • getName() • setName() Example: Thread.currentThread().getName(); Thread.currentThread().setName("MyMainThread"); III. Getting the Current Thread To know which thread is currently executing: Thread.currentThread() This is very useful while debugging multithreaded programs. #Day5 #Java #Multithreading #BackendDevelopment #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 124 of My Java Learning Journey Hi Guys, Today I practiced an important string logical problem — 👉 Finding the occurrence of each character in a String (including spaces) using Java Streams. This type of logic is very common in interviews and improves your understanding of Streams and Collections. ------------------------------------------------------------------------------------------- 💻 Code: -------------> import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class OccurrenceAndNonRepeatingChar { public static void main(String[] args) { String name = "yuvraj singh kushwah"; // Occurrence of all character with spaces Map<Character, Long> charCount = name.chars() .mapToObj(x -> (char) x) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println("Occurrence of all characters with spaces: " + charCount); } } ------------------------------------------------------------------------------------------- 🖥 Output: -------------> Occurrence of all characters with spaces: { =2, a=2, g=1, h=2, i=1, j=1, k=1, n=1, r=1, s=2, u=2, v=1, w=1} 🔎 Output Explanation: • Space " " is counted → appears 2 times • Characters like g, i, j, k appear only 1 time • Characters like a, s, u appear 2 times Since we didn’t remove spaces, they are treated like normal characters. ⭐ Important Concept: ✔ chars() → Converts String into IntStream ✔ mapToObj() → Converts int to Character ✔ groupingBy() → Groups identical characters ✔ counting() → Counts frequency This is a clean Java 8+ approach instead of manually using loops and HashMap. 💡 Important Tip: If you don’t want to count spaces, add: .filter(ch -> ch != ' ') before collect(). 🔥 Why This Is Important? ✔ Frequently asked in interviews ✔ Builds strong Stream knowledge ✔ Improves logical thinking ✔ Real-world text processing use case Consistency > Motivation 💪 Day 124 done ✅ What should I practice tomorrow — more Stream problems or interview-based tricky logic? #Java #JavaDeveloper #JavaStreams #CodingPractice #ProblemSolving #InterviewPreparation #DevOps #LearningInPublic #124day #CodeWithYuvi
To view or add a comment, sign in
-
-
📘 Java Learning – Collections Framework (Part 6: Map Interface & HashMap) 🗺️🚀 Continuing my Core Java Collections journey, today I started exploring Map, which stores data as key–value pairs. 🔰 Map Interface • Used to represent data as key–value pairs • Both keys and values are objects • Duplicate keys not allowed, values can be duplicated • Each key–value pair is called an Entry • Map is NOT a child of Collection 📌 Difference • Collection → group of individual objects • Map → group of key–value pairs Example: 101 → "Java" (Entry) 101 = key, Java = value 🔰 Important Map Methods • put(key, value) – adds / replaces value • get(key) • remove(key) • containsKey(), containsValue() • size(), isEmpty(), clear() 🔰 Collection Views of Map • keySet() → Set of keys • values() → Collection of values • entrySet() → Set of entries 🔰 Map.Entry Interface • Each key–value pair is an Entry • Entry exists only inside Map Key methods: • getKey() • getValue() • setValue() 🔰 HashMap (C) • Underlying data structure: Hash Table • No duplicate keys, values can repeat • Insertion order not preserved • One null key allowed, multiple null values allowed • Not synchronized → not thread-safe 🧪 Short Example HashMap m = new HashMap(); m.put(101, "Java"); m.put(102, "Python"); m.put(103, "Programming"); m.put(102, "Spring"); // replaces value System.out.println(m); Set s = m.keySet(); System.out.println(s); // [101, 102, 103] Collection c = m.values(); System.out.println(c); // [Java, Spring, Programming] Set s1 = m.entrySet(); Iterator itr = s1.iterator(); while (itr.hasNext()) { Map.Entry m1 = (Map.Entry) itr.next(); if (m1.getKey().equals(102)) { m1.setValue("Python"); } } System.out.println(m); // {101=Java, 102=Python, 103=Programming} ⭐ Key Takeaway • Map is for relationships (key → value) • HashMap is fast but not thread-safe Building strong Java fundamentals, one Map at a time ☕💻 #Java #CoreJava #CollectionsFramework #Map #HashMap #JavaCollections #LearningJourney
To view or add a comment, sign in
-
⚫One of the most important concepts in Java: Arrays. When we use traditional variables like: Java 👇 int a1, a2, a3, a4, a5; 📍It becomes difficult to manage and access data efficiently. 👉 That’s where Arrays come into the picture. 🔹 What is an Array? An array is an object in Java that stores multiple values of the same data type in a single variable. ✔ Homogeneous data (same data type) ✔ Fixed size ✔ Index starts from 0 ✔ Stored in Heap memory (array is an object) 📌 1️⃣ One-Dimensional Array (1D) Used to store a list of values. Example: Store ages of 5 students. Java 👇 int[] a = new int[5]; a[0] = 16; a[1] = 18; a[2] = 20; a[3] = 22; a[4] = 21; 📌 Important Points: Index starts from 0 Size must be defined Default values: 0 (for int) 📌 2️⃣ Two-Dimensional Array (2D) Used to store data in rows and columns (matrix format). 📌Real-Time Example: Store ages of students in 2 classrooms, each having 5 students. Java 👇 int[][] a = new int[2][5]; Think of it like: 🏫 2 Classes 👩🎓 5 Students per class Access using: Java 👇 a[i][j] ✔ Useful for tables ✔ Useful for marksheets ✔ Used in matrix operations 📌 3️⃣ Three-Dimensional Array (3D) 📍Used when data has three levels. Real-Time Example: Store ages of students in: 🏢 2 Schools 🏫 3 Classes per school 👩🎓 5 Students per class Java 👇 int[][][] a = new int[2][3][5]; 💻Access using: Java 👇 a[i][j][k] This is like: School → Class → Student 🔁 Array Traversal (Using Loops) Instead of writing values manually, we use loops: Java 👇 for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { for(int k = 0; k < 5; k++) { System.out.print(a[i][j][k] + " "); } } } 📌 Important: 👉 Loops make code clean and efficient 👉 Avoid repetitive code 👉 Helps in dynamic data input 🎯 Key Observations ✅ Arrays are objects in Java ✅ Stored in Heap memory ✅ Index always starts from 0 ✅ Used for structured data ✅ Supports multi-dimensional storage ✅ Best for managing large similar datasets 💡 Why Arrays Are Important in Real World? ✔ Student management systems ✔ Banking transaction lists ✔ E-commerce product lists ✔ Attendance tracking ✔ Data analytics processing Understanding arrays from 1D → 2D → 3D helped me visualize how structured data is managed in real applications. What topic should I explore next — ArrayList or Collections Framework? 🚀 TAP Academy #Java #CoreJava #Arrays #Programming #LearningJourney #WomenInTech
To view or add a comment, sign in
-
-
🚀 Day 128 of My Java Learning Journey 😆 --- Hi Friends, Today I practiced a simple but powerful logical program using Java 8 Streams — calculating the sum of squares of array elements 💡 Instead of using a traditional loop, I used map() and sum() to make the code clean and readable. ------------------------------------------------------------------------------------------- 💻 Code: ------------> import java.util.Arrays; public class ArraySquareSumByJava8 { public static void main(String[] args) { int[] a = {3, 5, 7, 6, 8}; int sumOfSquares = Arrays.stream(a) .map(y -> y * y) .sum(); System.out.println("Sum of all array squares: " + sumOfSquares); } } ------------------------------------------------------------------------------------------- 🖥 Output: -------------> Sum of all array squares: 183 📖 Output Explanation: Each number in the array is squared: 3² = 9 5² = 25 7² = 49 6² = 36 8² = 64 Then all squared values are added: 9 + 25 + 49 + 36 + 64 = 183 🔎 Important Concept: ✅ Arrays.stream() converts array into a Stream ✅ map() transforms each element ✅ y -> y * y is a Lambda Expression ✅ sum() adds all elements of IntStream Java 8 Streams help us write cleaner and more functional-style code. 💡 Important Tip: When working with int[], Java automatically creates an IntStream, so we can directly use .sum() without extra conversion. Streams make code: ✔ Shorter ✔ More readable ✔ More expressive Are you using Java 8 Streams in your projects? Or still comfortable with traditional loops? 🤔 Let’s grow together 🚀 #Java #JavaLearning #JavaDeveloper #Java8 #Streams #LambdaExpression #CodingJourney #BackendDeveloper #DevOps #100DaysOfCode #CodeWithYuvi #LogicallyJourney #day128
To view or add a comment, sign in
-
-
🚀 Day 129 of My Java Learning Journey 😉 Hello LinkedIn family, Today I practiced a logical program to find all vowels from a list of strings using nested loops in Java 💡 This helped me understand how to work with: List of Strings Converting String to char array Checking characters using indexOf() ------------------------------------------------------------------------------------------- 💻 Code: =======> import java.util.*; public class VowelFind { public static void main(String[] args) { List<String> listOfString = Arrays.asList("aab", "xyz", "iiu"); List<Character> vowels = new ArrayList<>(); for (String str : listOfString) { for (char cha : str.toCharArray()) { if ("aeiou".indexOf(cha) != -1) { vowels.add(cha); } } } System.out.println("vowels :" + vowels); } } ------------------------------------------------------------------------------------------- 🖥 Output: =========> vowels : [a, a, i, i, u] 📖 Output Explanation: Input List: ["aab", "xyz", "iiu"] Step 1️⃣ → Convert each string into characters Step 2️⃣ → Check if character exists in "aeiou" Step 3️⃣ → If yes, add to vowels list From: "aab" → a, a "xyz" → no vowels "iiu" → i, i, u Final list: [a, a, i, i, u] 🔎 Important Concept: ✅ toCharArray() → Converts String into character array ✅ "aeiou".indexOf(cha) → Checks if character exists ✅ != -1 → Means character is found ✅ Nested loops → Loop inside loop 💡 Important Tip: Instead of writing multiple OR conditions like: if(cha=='a' || cha=='e' || cha=='i' ...) Using indexOf() makes code cleaner and more readable. This logic can be used in: ✔ Password validation ✔ Text processing ✔ Data filtering ✔ Interview questions What would you improve in this code? 🤔 Should I convert this into Java 8 Stream version next? 😄 Let’s keep learning 🚀 #Java #JavaLearning #CodingJourney #JavaDeveloper #BackendDeveloper #Streams #ProblemSolving #DevOps #Day129 #codewithyuvi #logicalworld
To view or add a comment, sign in
-
-
DAY 17: CORE JAVA TAP Academy 🚀 Understanding Mutable Strings in Java – StringBuffer, StringBuilder & StringTokenizer In Java, String objects are immutable. That means once a string is created, it cannot be changed. Every modification creates a new object in memory. But what if we need frequent modifications? 🤔 That’s where mutable strings come into play! 🔹 1️⃣ StringBuffer StringBuffer is a mutable, thread-safe class used to modify strings dynamically. ✅ Key Features: Thread-safe (synchronized) Slower than StringBuilder (due to synchronization) Ideal for multi-threaded environments 📌 Important Methods: append() → Adds data to the existing string capacity() → Returns current buffer capacity trimToSize() → Reduces capacity to match current string length 💻 Example: StringBuffer sb = new StringBuffer("Hello"); System.out.println("Capacity: " + sb.capacity()); // Default 16 + length sb.append(" World"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 2️⃣ StringBuilder StringBuilder is also mutable but not thread-safe. ✅ Key Features: Faster than StringBuffer Best for single-threaded applications Preferred in most cases 📌 Important Methods: append() capacity() trimToSize() 💻 Example: StringBuilder sb = new StringBuilder("Java"); System.out.println("Capacity: " + sb.capacity()); sb.append(" Programming"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 3️⃣ StringTokenizer StringTokenizer is used to break a string into tokens based on delimiters. 📌 Example: String str = "Java,Python,C++"; StringTokenizer st = new StringTokenizer(str, ","); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } ⚠ Note: StringTokenizer is considered a legacy class. Modern alternatives include: String.split() Pattern and Matcher classes 🎯 Quick Comparison Feature StringBuffer StringBuilder Mutable ✅ ✅ Thread-Safe ✅ ❌ Performance Slower Faster Recom mended Multi- Single- threaded threaded --- 💡 Key Takeaway: Use StringBuilder for better performance in most applications. Use StringBuffer when thread safety is required. Avoid StringTokenizer in modern development; prefer split() or regex. #Java #JavaProgramming #CoreJava #StringHandling #Programming #Developers
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