📌 Strings, Arrays & split() in Java 🔹 String String is a class used to store a group of characters and is represented in double quotes (" "). 👉 Ways to create String: Using string literal String s = "Hello"; Using new keyword String s = new String("Hello"); 👉 Important points: Strings are immutable (cannot be changed) Stored in String Constant Pool (SCP) Using "new" → stored in heap memory Comparing objects → compares address Default value → null 🔹 String Methods Commonly used methods: length() → returns length of string toUpperCase() → converts to uppercase toLowerCase() → converts to lowercase charAt(index) → returns character equals() → compares two strings contains() → checks substring substring(start, end) → extracts part startsWith() → checks starting value endsWith() → checks ending value trim() → removes spaces 💻 Example: String s = "Hello Java"; System.out.println(s.length()); System.out.println(s.toUpperCase()); System.out.println(s.charAt(1)); 👉 Output: 10 HELLO JAVA e 🔹 split() Method Used to split a string into parts. 💻 Syntax: variable.split(" "); 💻 Example: String s = "Hi This is Java"; String[] words = s.split(" "); 👉 Output: Hi This is Java 🔹 Arrays Arrays are used to store multiple values of the same data type. 👉 Key points: Fixed size Same data type Stored in continuous memory Index starts from 0 💻 Syntax: int[] arr = new int[5]; 👉 Other ways: int[] arr = {1,2,3}; int arr[] = new int[5]; These concepts help in handling text data and storing multiple values efficiently in Java. #Java #CodingJourney #LearnJava #FullStackDeveloper
Java String and Array Handling with split() Method
More Relevant Posts
-
Ever wondered why we need a "StringBuilder" in Java when we already have "String"? 🤔 At first glance, "String" seems perfectly fine for handling text. But the real difference shows up when we start modifying or concatenating strings multiple times. 👉 The key point: Strings in Java are immutable. This means every time you concatenate a string, a new object is created in memory. Example: String str = "Hello"; str = str + " World"; str = str + "!"; Behind the scenes, this creates multiple objects: - "Hello" - "Hello World" - "Hello World!" This repeated object creation increases memory usage and puts extra load on the Garbage Collector (GC). 🚨 In scenarios like loops or heavy string manipulation, this can significantly impact performance. So where does "StringBuilder" help? "StringBuilder" is mutable, meaning it modifies the same object instead of creating new ones. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); sb.append("!"); ✅ Only one object is used and updated internally ✅ Faster performance ✅ Less memory overhead ✅ Reduced GC pressure When should you use it? ✔ When performing frequent string modifications ✔ Inside loops ✔ When building dynamic strings (logs, queries, JSON, etc.) 💡 Quick takeaway: - Use "String" for simple, fixed text - Use "StringBuilder" for dynamic or repeated modifications 💥 Advanced Tip: StringBuilder Capacity vs Length Most developers know StringBuilder is faster—but here’s something interviewers love 👇 👉 length() = actual number of characters 👉 capacity() = total allocated memory By default, capacity starts at 16 and grows dynamically when needed: ➡️ New capacity = (old * 2) + 2 💡 Why it matters? Frequent resizing creates new internal arrays and copies data → impacts performance. ✅ Pro tip: When working with loops or large data, initialize capacity in advance: StringBuilder sb = new StringBuilder(1000); Understanding this small concept can make a big difference in writing efficient Java code 🚀 #Java #Programming #Performance #CodingTips #Developers
To view or add a comment, sign in
-
-
Two Java strings look exactly the same… But sometimes == returns false. Why? The answer lies in String Pool and Heap memory. 👉 What is a String literal? A string literal is a value written directly in quotes. Example: String s1 = "hello"; 👉 What is String Pool? String Pool is a special memory area in Java where string literals are stored and reused. 👉 What is Heap memory? Heap is the memory where objects are created at runtime. 👉 Example: String s1 = "hello"; String s2 = "hello"; Java checks the pool: "hello" already exists → reuse it So: s1 == s2 → true ✅ 👉 Now this: String s3 = new String("hello"); String s4 = new String("hello"); new always creates objects in Heap. So: s3 == s4 → false ❌ (different references) s3.equals(s4) → true ✅ (same value) 👉 Important point • String Pool manages memory (reuse objects) • == compares reference (same object or not) • equals() compares value (same content or not) 👉 Simple way to remember "hello" → reused from pool new String("hello") → always new object 👉 Real-world Java example: public class Test { public static void main(String[] args) { String a = "java"; String b = "java"; String c = new String("java"); System.out.println(a == b); // true System.out.println(a == c); // false System.out.println(a.equals(c)); // true } } 👉 Conclusion String Pool helps save memory, while == and equals() behave differently based on reference vs value. Understanding this avoids common bugs in Java. Had you come across this before? #Java #BackendEngineering #JavaTips #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 6 of Java Series — Count Vowels Using Streams Ever wondered how to count vowels in a string using Java 8 in a clean and functional way? Here’s a simple yet powerful approach using Streams 👇 import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class CountOfVowels { public static void main(String[] args) { String name = "Microservices"; List<String> vowels = Arrays.asList("a", "e", "i", "o", "u"); Map<String, Long> map = Arrays.stream(name.split("")) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<Map.Entry<String, Long>> finalMap = map.entrySet().stream() .filter(entry -> vowels.contains(entry.getKey())) .toList(); System.out.println(finalMap); } } 🔍 How it works: 1️⃣ name.split("") → Converts string into individual characters 2️⃣ groupingBy(Function.identity(), counting()) → Counts frequency of each character 3️⃣ Filter step → Keeps only vowels 4️⃣ Final result → List of vowels with their count 👉 Output: [e=2, i=2, o=1] #Java #Java8 #Streams #Coding #Developers #Learning
To view or add a comment, sign in
-
💡 Why do we need forEach() in Java 8 when we already have loops? Java has always supported iteration using traditional loops. But with Java 8, forEach() was introduced to align with functional programming and stream processing. Let’s break it down 👇 🔹 1. Traditional for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Gives full control using index ✅ Supports forward & backward traversal ✅ Easy to skip elements or modify logic ⚠️ Downside: You must manage indexes manually, which can lead to errors like ArrayIndexOutOfBoundsException ------------------------------------------------------------------------------ 🔹 2. Enhanced for-each Loop for(int num : numbers){ System.out.println(num); } ✅ Cleaner and simpler syntax ✅ No need to deal with indexes ⚠️ Limitation: Only forward iteration No direct access to index ------------------------------------------------------------------------------ 🔹 3. Java 8 forEach() (Functional Approach) Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 👉 Even more concise: Arrays.stream(numbers) .forEach(System.out::println); ✅ Encourages functional programming ✅ Works seamlessly with Streams API ✅ More expressive and readable ✅ Can be used with parallel streams for better performance ------------------------------------------------------------------------------ 🔍 What happens internally? forEach() is a default method in the Iterable interface It takes a Consumer functional interface The lambda you provide is executed via: void accept(T t); ------------------------------------------------------------------------------ 🚀 Final Thought While traditional loops are still useful, forEach() brings a declarative and modern way of iterating data — especially when working with streams. #Java #Java8 #Programming #Developers #Coding #FunctionalProgramming
To view or add a comment, sign in
-
Stuck in Java 8? Here’s a 2-minute guide to the most asked LTS features! ☕️🚀 If you're preparing for a Java interview, you need to know more than just the basics. Interviewers are increasingly focusing on the evolution from Java 8 to 21. Here is a quick breakdown of the "Must-Know" features for your next technical round: 🌱 Java 8: The Functional Revolution The foundation of modern Java. Lambda Expressions: Passing behavior as a parameter. 1.list.forEach(item -> System.out.println(item)); 2.(var x, var y) -> x + y; Stream API: Declarative data processing (Filter, Map, Sort). Optional Class: Say goodbye to NullPointerException. Default Methods: Adding logic to interfaces without breaking old code. 🧹 Java 11: Modernization & Cleanup Var for Lambdas: Standardizes local variable syntax in functional code. (var x, var y) -> x + y; New HTTP Client: Finally, a modern, asynchronous way to handle web requests. String Utilities: Handy methods like .isBlank(), .strip(), and .repeat(). 🏗️ Java 17: Expressive Syntax Focuses on reducing boilerplate and better inheritance control. Sealed Classes: Restrict which classes can extend your code. public sealed class Shape permits Circle, Square {} Records: One-liner immutable data classes. public record User(String name, int id) {} Text Blocks: Clean multi-line strings without the \n mess. ⚡ Java 21: High-Performance Concurrency The current gold standard for scalability. Virtual Threads: Lightweight threads that make I/O-bound tasks incredibly fast. Pattern Matching for Switch: Cleaner type checking. switch (obj) { case Integer i -> System.out.println("Int: " + i); case String s -> System.out.println("String: " + s); default -> System.out.println("Unknown"); } Sequenced Collections: Better control over the order of elements (First/Last). #Knowledge Sharer #Learning
To view or add a comment, sign in
-
𝑫𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒄𝒆 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 "𝒕𝒉𝒓𝒐𝒘" 𝒂𝒏𝒅 "𝒕𝒉𝒓𝒐𝒘𝒔" 𝒊𝒏 𝑱𝒂𝒗𝒂 Before understanding "throw" and "throws", one important point ➡️ Throwable is the parent class of Exception ➡️ Exception is the parent class of all Exceptions in Java. 🔍what actually "𝐭𝐡𝐫𝐨𝐰𝐬" mean ➡️It is used in method declaration 📃 "throws" is used to delegate (pass) the exception from one method to the calling method (the one who calls it) and not actually handles the exception. 📃JVM also does not handle it at this stage. Calling method provides try catch blocks to handle this exception. 📃 If not handled Exception goes to JVM.JVM terminates the program ❌ 🔍 Definition of "throw" 📃 "throw" is used to explicitly throw an exception. It stops the normal execution flow. 📃It is used inside a method, The exception is then passed to caller method. 👨💻 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐢𝐨.*; 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 { 𝐅𝐢𝐥𝐞 𝐟𝐢𝐥𝐞 = 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞("𝐃://𝐟𝐢𝐥𝐞𝟏.𝐭𝐱𝐭"); 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞(); } 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐈𝐧𝐯𝐚𝐥𝐢𝐝 𝐅𝐢𝐥𝐞 𝐍𝐚𝐦𝐞"); } } } 📝𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 This method is declaring an exception using throws ⚖️“I will not handle this exception” ☎️“Whoever calls me should handle it” 📝 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); ▪️Here we are manually throwing exception using throw Important: Execution stops here immediately Control goes to calling method 📝𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞();} ▪️Calling the method which has throws Since it declared exception → ▪️We must handle it using try-catch 📝 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) Catch block handles the exception ♣️ Key Difference "throws" → delegates exception (method level) ➡️ passing responsibility "throw" → actually throws exception (statement level) ➡️ creating the problem #Java #JavaDeveloper #JavaConcepts #ExceptionHandling #Programming #TechJourney #InterviewPrep
To view or add a comment, sign in
-
⚡ map vs flatMap in Java (Stream API) Definition: map() → Transforms each element 1:1 flatMap() → Transforms and flattens nested structures 🤔 Why use? 1. map() - When output is a single value per input - Simple transformations 2. flatMap() - When each element produces multiple values (collections/streams) - Avoid nested structures like List<List<T>> 💻 Example List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6) ); // map() → creates nested structure List<Stream<Integer>> mapResult = list.stream() .map(inner -> inner.stream()) .collect(Collectors.toList()); // flatMap() → flattens into single stream List<Integer> flatMapResult = list.stream() .flatMap(inner -> inner.stream()) .collect(Collectors.toList()); 🔄 Flow map() List<List> → Stream<List> → Stream<Stream> flatMap() List<List> → Stream<List> → Stream 🧠 Rule of Thumb 👉 If your transformation returns a single value → use map() 👉 If it returns a collection/stream → use flatMap() 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Backend #Streams #Java8 #CodingInterview #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Java Strings — Part 3: Immutability You’ve heard it a hundred times: 👉 “Strings are immutable in Java” But interviews don’t stop there… they go deeper: 👉 Why? How? What actually happens internally? Let’s break it down 👇 --- ### 🔹 What does “Immutable” really mean? 👉 Once a String object is created, its value cannot be changed java String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello ❗ The original object is untouched --- ### 🔹 What actually happens in memory? java String s = "Hello"; s = s.concat(" World"); 👉 Step-by-step: 1. "Hello" created in SCP 2. "Hello World" created as a new object 3. Reference s now points to new object 💡 Old object is still there (eligible for GC later) --- ### 🔹 Internal Structure (Very Important 🔥) In Java, String is backed by: java private final byte[] value; 👉 Key points: - final → reference cannot change - No setter methods → cannot modify content 💡 That’s what enforces immutability --- ### 🔹 Why Immutability is Needed? #### ✅ 1. Security - Used in: - DB URLs - File paths - Network connections 👉 Prevents accidental/malicious changes --- #### ✅ 2. Thread Safety - No synchronization needed - Multiple threads can share same String safely --- #### ✅ 3. Performance (String Pool 🔥) - Reuse of objects in SCP - Saves memory --- #### ✅ 4. Caching (HashCode) java String s = "abc"; s.hashCode(); // cached internally 👉 Hashcode is calculated once and reused --- ### 🔹 Interview Trap Questions ⚠️ ⚠️ Q1: Is String really immutable? 👉 Yes (value is immutable) 👉 But reference can change java String s = "Hello"; s = "World"; // new object --- ⚠️ Q2: Can we break immutability? (Advanced) 👉 Yes, using Reflection (not recommended) java // Modifying internal value via reflection (hacky) 💡 This is why immutability is “by design”, not absolute enforcement --- ⚠️ Q3: Why StringBuilder is mutable but String is not? 👉 String → safety + caching 👉 StringBuilder → performance (fast modifications) --- ### 🔹 Common Mistakes Developers Make ❌ Assuming concat() modifies original String ❌ Using String in loops (performance issue) ❌ Not understanding memory impact --- ### 🔥 Real Interview Insight 👉 If interviewer asks “Why String is immutable?” Don’t just say definition ❌ Say this instead ✅: ✔ Security ✔ Thread safety ✔ Performance via String Pool ✔ Hashcode caching --- ### 🔥 Final Takeaway ✔ String immutability = design decision ✔ Every modification → new object ✔ Core reason behind many Java optimizations ✔ Frequently asked in interviews (with twists!) #Java #SDET #AutomationTesting #JavaInterview #Immutability #Programming #TechLearn
To view or add a comment, sign in
-
Records in Java — Say Goodbye to Boilerplate Code Writing simple data classes in Java used to mean creating: fields constructors getters equals() hashCode() toString() A lot of code… just to store data. With Records (introduced in Java), Java made this much simpler. Instead of writing this: class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } You can simply write: record Person(String name, int age) {} And Java automatically generates: 1. Constructor 2. Getter methods (name(), age()) 3. equals() 4. hashCode() 5. toString() Why Records matter? 1. Less boilerplate code 2. Immutable by default 3. Cleaner and more readable code 4. Perfect for DTOs, API requests/responses, and model classes Example: record Employee(String name, String department, double salary) {} Usage: Employee emp = new Employee("John", "Engineering", 90000); System.out.println(emp.name()); Records become even more powerful with modern Java features like Sealed Classes: sealed interface Shape permits Circle, Rectangle {} record Circle(double radius) implements Shape {} record Rectangle(double length, double width) implements Shape {} Modern Java is getting cleaner, safer, and more expressive. In one line: Records = Less code, more clarity. #Java #Java17 #JavaDeveloper #BackendDevelopment #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
-
Java Map.Entry Cheat Sheet: Sorted() & Max() Made Simple ------------------------------------------------------------ MAP.ENTRY SYNTAX FOR SORTED AND MAX ----------------------------------- 1. SORTED BY KEY (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) 2. SORTED BY KEY (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 3. SORTED BY VALUE (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) 4. SORTED BY VALUE (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 5. MAX BY VALUE map.entrySet() .stream() .max(Map.Entry.comparingByValue()) 6. MIN BY VALUE map.entrySet() .stream() .min(Map.Entry.comparingByValue()) 7. MAX BY KEY map.entrySet() .stream() .max(Map.Entry.comparingByKey()) 8. MIN BY KEY map.entrySet() .stream() .min(Map.Entry.comparingByKey())
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