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
Java Mutable Strings: StringBuffer, StringBuilder & StringTokenizer
More Relevant Posts
-
DAY 18: CORE JAVA TAP Academy 🚀 Understanding Method Overloading in Java Method Overloading is one of the core concepts of Compile-Time Polymorphism in Java. It allows a class to have multiple methods with the same name but different parameter lists. Let’s break down how method overloading is observed and identified 👇 🔹 1. Method Name The method name must be the same. Example: add() can have multiple definitions within the same class. 🔹 2. Number of Parameters If the number of parameters is different, the method is overloaded. int add(int a, int b) int add(int a, int b, int c) 🔹 3. Type of Parameters Even if the number of parameters is the same, changing the data type makes it overloaded. int add(int a, int b) double add(double a, double b) 🔹 4. Order of Parameters If parameter types are the same but in a different order, it is still valid overloading. void display(int a, String b) void display(String b, int a) 🔹 5. Type Conversion (Implicit Casting) Java follows method matching rules: Exact match Widening (int → long → float → double) Autoboxing Varargs Example: void show(int a) void show(double a) If we call show(5), Java chooses the most specific match (int). 🔹 6. Ambiguity in Method Overloading Ambiguity occurs when Java cannot determine which method to call. Example: void test(int a, float b) void test(float a, int b) Calling test(10, 10) creates confusion because both methods are possible after type conversion. ⚠️ The compiler throws an error in such cases. 📌 Important Terms Related to Method Overloading ✔️ Compile-Time Polymorphism ✔️ Static Binding ✔️ Early Binding ✔️ Method Signature (method name + parameter list) ✔️ Implicit Type Promotion ✔️ Varargs ✔️ Autoboxing 💡 Key Rule to Remember Changing only the return type does NOT achieve method overloading. int sum(int a, int b) double sum(int a, int b) ❌ (Invalid) ✨ Method overloading improves code readability, flexibility, and reusability. It allows developers to perform similar operations in different ways without changing method names. Mastering this concept is essential for cracking Java interviews and writing clean object-oriented code. #Java #OOPS #Programming #SoftwareDevelopment #Coding #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 127 of My Java Learning Journey 🤩 Hi Friends, Today I learned how to join two lists using Stream API in Java in a clean and modern way. Instead of using loops, we can use Stream.concat() to combine two lists easily. ------------------------------------------------------------------------------------------- 💻 Code ------------> import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class JoinTwoList { public static void main(String[] args) { List<Integer> list1 = List.of(1, 2, 3); List<Integer> list2 = List.of(4, 5, 6); List<Integer> joinList = Stream .concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); System.out.println("Lists are Joined: " + joinList); } } ------------------------------------------------------------------------------------------- 🖥️ Output Lists are Joined: [1, 2, 3, 4, 5, 6] 🔎 Output Explanation list1.stream() converts first list into stream list2.stream() converts second list into stream Stream.concat() merges both streams Collectors.toList() converts the combined stream back into a list So both lists are joined into a single list. 📌 Important Concept 👉 Stream.concat(Stream s1, Stream s2) It is used to combine two streams into one stream. This method is very useful when working with collections in a functional programming style. 💡 Important Tip List.of() creates an immutable list. You cannot modify it (add/remove elements). If you need a modifiable list, wrap it like this: new ArrayList<>(List.of(1,2,3)); 🤔 Have You Tried This? Do you prefer: Using loops to join lists? Or using Stream API? Let me know your approach in the comments 👇 I am consistently improving my Java skills step by step. If you are also learning Java, let’s grow together 💪 #Java #JavaDeveloper #StreamAPI #Programming #CodingJourney #DevOps #BackendDevelopment #LearningEveryday #day127 #codewithyuvi #Logicalworld
To view or add a comment, sign in
-
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
Day 12 – Java Arrays, Wrapper Classes & Literals. Today I learned some powerful core Java concepts that strengthen the foundation of programming. Disadvantages of Arrays Arrays store homogeneous data only (same data type). Array size is fixed once created. Arrays require contiguous memory allocation. They cannot grow or shrink dynamically. Example: Java Copy code int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; // arr[5] = 60; ArrayIndexOutOfBoundsException Wrapper Classes in Java Java is not purely object-oriented because it supports primitive data types. Primitive types are NOT objects. Wrapper classes convert: Primitive ➝ Object Object ➝ Primitive Example: Java Copy code int x = 10; Integer obj = Integer.valueOf(x); // Boxing int y = obj.intValue(); // Unboxing Makes Java more object-oriented Required for Collections (ArrayList, etc.) Primitive → Wrapper Mapping: Primitive Wrapper int Integer double Double char Character boolean Boolean Literals in Java A literal is a constant value assigned to a variable. Java Copy code int year = 2000; Here: int → datatype year → variable 2000 → literal Numeric literals Character literals Boolean literals String literals Why Arrays Were Introduced? Using multiple variables: int a, b, c, d, e; Problems: Hard to manage Difficult to access dynamically Not scalable Solution: Java Copy code int[] ages = new int[10]; Types of Arrays 1-D Array Java Copy code int[] a = new int[10]; 2-D Array (Rectangular) Java Copy code int[][] a = new int[2][5]; Jagged Array Java Copy code int[][] a = new int[2][]; a[0] = new int[3]; a[1] = new int[5]; Key Takeaways Arrays are objects Created at runtime Stored in heap memory Length is fixed Require contiguous memory
To view or add a comment, sign in
-
-
Day 25 – Understanding Blocks in Java (Static & Non-Static) One interesting concept I learned today in Core Java is Initialization Blocks. Blocks are special members of a class used to initialize variables automatically during program execution. There are mainly two types of blocks in Java: 🔹 Static Block 🔹 Non-Static Block (Instance Initialization Block) ---------------------------------------------- 🔹 Static Block A static block is used to initialize static variables of a class. Key points: ✔ Executed only once ✔ Runs during class loading ✔ Executes before the main() method Example: class Employee { static int x; static { x = 20; } public static void main(String[] args) { System.out.println(Employee.x); } } 📌 Static block executes automatically when the class is loaded into memory. ---------------------------------------------- 🔹 Non-Static Block (Instance Block) A non-static block is used to initialize non-static (instance) variables. Key points: ✔ Executes every time an object is created ✔ Can run multiple times ✔ Runs before the constructor Example: class Employee { int id; String name; { id = 1; name = "Raj"; } } Whenever we create a new object: Employee e1 = new Employee(); Employee e2 = new Employee(); The non-static block runs twice because two objects are created. ---------------------------------------------- 🔹 Order of Execution in Java Understanding execution order is important: 📌 Static Block → main() → Non-Static Block → Constructor This explains how Java initializes classes and objects internally. 📌 Key Takeaway Initialization blocks help in automatic setup of variables before objects start working. Understanding this concept helps build strong fundamentals in Java memory behavior and object creation. Every day I’m learning something new about how Java actually works behind the scenes. #Java #CoreJava #JavaProgramming #JavaDeveloper #Programming #SoftwareDevelopment #LearningInPublic #CodingJourney #BackendDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
𝐉𝐚𝐯𝐚 𝐂𝐨𝐝𝐢𝐧𝐠 𝐐𝐀 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐨𝐧/ 𝐒𝐃𝐄𝐓 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐁𝐚𝐬𝐞𝐝 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🔹 BASIC JAVA CODING QUESTIONS 1. How do you reverse a string in Java? 2. How do you check if a string is a palindrome? 3. How do you count vowels and consonants in a string? 4. How do you reverse a number in Java? 5. How do you check whether a number is a palindrome? 6. How do you swap two numbers with and without using a third variable? 7. How do you find the largest of three numbers? 8. How do you print the Fibonacci series? 9. How do you check whether a number is prime? 10. How do you find the factorial of a number? 🔹 STRING-BASED QUESTIONS (VERY COMMON) 11. How do you count the occurrence of each character in a string? 12. How do you find duplicate characters in a string? 13. How do you find the first non-repeated character in a string? 14. How do you reverse each word in a sentence? 15. How do you check whether two strings are anagrams? 16. How do you remove duplicate characters from a string? 17. How do you remove special characters from a string? 18. How do you convert a string to lowercase or uppercase without using built-in methods? 19. How do you count the number of words in a sentence? 20. How do you replace spaces in a string with a special character? 🔹 ARRAY-BASED QUESTIONS 21. How do you find the maximum and minimum elements in an array? 22. How do you sort an array without using built-in sort methods? 23. How do you find duplicate elements in an array? 24. How do you remove duplicates from an array? 25. How do you find the second largest number in an array? 26. How do you find the sum of all elements in an array? 27. How do you check if an array is already sorted? 28. How do you reverse an array? 29. How do you move all zeros to the end of an array? 30. How do you compare two arrays for equality? 🔹 NUMBER & LOGICAL QUESTIONS 31. How do you check whether a number is an Armstrong number? 32. How do you check whether a number is a perfect number? 33. How do you find the sum of digits of a number? 34. How do you reverse the digits of a number? 35. How do you count the number of digits in a number? 36. How do you check whether a number is even or odd without using the modulo operator? 37. How do you generate a random number within a given range? 38. How do you find a missing number in an array? 39. How do you print star and number patterns? 40. How do you calculate the power of a number? Comment “𝐉𝐀𝐕𝐀” if you want clean, interview-ready solutions for these questions. #sdet #java #testautomation
To view or add a comment, sign in
-
🚀 Mastering Java Stream API – Write Cleaner, Smarter Code If you're still writing verbose loops in Java, it's time to rethink your approach. The Stream API (introduced in Java 8) is not just a feature—it’s a paradigm shift toward functional-style programming in Java. It allows you to process collections of data in a declarative, concise, and efficient way. 🔍 What is Stream API? A Stream is a sequence of elements that supports various operations to perform computations. Unlike collections, streams: Don’t store data Are immutable (operations don’t modify the source) Support lazy evaluation Enable parallel processing effortlessly ⚙️ Core Concepts 1. Stream Creation List<String> names = Arrays.asList("John", "Jane", "Jack"); Stream<String> stream = names.stream(); 2. Intermediate Operations (Lazy) filter() map() sorted() These return another stream and are not executed until a terminal operation is invoked. names.stream() .filter(name -> name.startsWith("J")) .map(String::toUpperCase); 3. Terminal Operations (Trigger Execution) forEach() collect() count() List<String> result = names.stream() .filter(name -> name.length() > 3) .collect(Collectors.toList()); 💡 Why Use Stream API? ✅ Readable & Declarative Code Focus on what to do, not how to do it ✅ Less Boilerplate Goodbye nested loops ✅ Parallel Processing names.parallelStream().forEach(System.out::println); ✅ Functional Programming Power Lambdas + Streams = Clean pipelines 🔥 Real-World Example Traditional Approach List<String> filtered = new ArrayList<>(); for (String name : names) { if (name.length() > 3) { filtered.add(name.toUpperCase()); } } Stream API Approach List<String> filtered = names.stream() .filter(name -> name.length() > 3) .map(String::toUpperCase) .collect(Collectors.toList()); 👉 Less code. More clarity. Better maintainability. ⚠️ Common Pitfalls Overusing streams can hurt readability Avoid complex nested streams Be cautious with parallel streams (thread-safety matters) 🧠 Pro Tip Think of streams as a data pipeline: Source → Intermediate Operations → Terminal Operation 📌 Final Thoughts The Stream API is a must-have skill for modern Java developers. It helps you write clean, scalable, and expressive code, especially in microservices and data-heavy applications. If you're building backend systems with Java, mastering streams is not optional—it's essential. 💬 How often do you use Stream API in your projects? Any advanced patterns you rely on? #Java #StreamAPI #BackendDevelopment #Java8 #CleanCode #FunctionalProgramming #SoftwareEngineering
To view or add a comment, sign in
-
Understanding Multithreading in Java 🔹 In this example, I explored two approaches for creating threads: • Extending the Thread class • Implementing the Runnable interface package multithreading; /* 1️⃣ Extending Thread Class When a class extends the Thread class, it becomes a thread class. Objects of this class can run in a separate thread. However, the actual task that the thread executes must be written inside the run() method. When start() is called, the JVM creates a new thread and internally invokes the run() method. */ class CommonResource extends Thread { public void commonResource(String t){ System.out.println("common resources " + t); } @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } /* 2️⃣ Creating a Common Resource using the Runnable interface. Instead of extending Thread, it is generally recommended to implement the Runnable interface. Advantages: • The task is separated from the thread. • The class can still extend another class (Java doesn't support multiple inheritance). • This approach is widely used in industry (especially with thread pools). */ class CommonResource1 implements Runnable { public void commonResource(String t){ System.out.println("common resources " + t); } /* Multiple threads will share the same object of this class. Because the run() method is synchronized, only one thread can execute it at a time for this shared object. */ @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } public class ThreadsUsesCommonResource { public static void main(String[] args){ // Creating a shared resource object CommonResource1 commonResource1 = new CommonResource1(); // Creating multiple threads that use the same resource Thread t1 = new Thread(commonResource1); t1.setName("kalia"); Thread t2 = new Thread(commonResource1); t2.setName("bheem"); Thread t3 = new Thread(commonResource1); t3.setName("raju"); // start() → JVM creates a new thread → run() method executes t1.start(); t2.start(); t3.start(); } } #Java #Multithreading #Synchronized #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 39 – Core Java | Polymorphism, Upcasting & Downcasting Today’s session focused on understanding the third pillar of Object-Oriented Programming — Polymorphism and how it works internally in Java. 🔹 What is Polymorphism? The word Polymorphism comes from Greek: Poly → Many Morph → Forms Meaning: One entity behaving in multiple forms. In Java, this is achieved mainly using method overriding and inheritance. 🔹 Example Used A Plane parent class with a method: fly() Three child classes: CargoPlane PassengerPlane FighterPlane Each class overrides the fly() method and behaves differently. Example: Cargo Plane → flies at low height Passenger Plane → flies at medium height Fighter Plane → flies at high altitude This demonstrates one method → multiple behaviors. 🔹 Tight Coupling vs Loose Coupling Tight Coupling Child reference → Child object CargoPlane cp = new CargoPlane(); cp.fly(); Here both reference and object are child type. Loose Coupling (Used for Polymorphism) Parent reference → Child object Plane ref = new CargoPlane(); ref.fly(); Here: Parent reference Child object This allows polymorphic behavior. 🔹 Types of Methods in Inheritance 1️⃣ Inherited Method Method comes directly from parent. 2️⃣ Overridden Method Child modifies the parent method. 3️⃣ Specialized Method Method exists only in child class. Example: carryCargo() carryPassengers() carryWeapons() 🔹 Important Rule Using parent reference, we can access: ✔ Inherited methods ✔ Overridden methods ❌ Cannot access specialized methods. 🔹 Downcasting To access child-specific methods: Parent reference must behave like a child. Example: ((CargoPlane) (ref)).carryCargo(); This process is called Downcasting. 🔹 Upcasting Plane ref = new CargoPlane(); Child object assigned to parent reference. This is called Upcasting and it happens automatically in Java. 🔹 Advantages of Polymorphism 1️⃣ Code Reduction Common logic can be reused instead of repeating code. 2️⃣ Code Flexibility One method can handle multiple object types. Example: airport.permit(plane) The same method can accept: CargoPlane PassengerPlane FighterPlane 💡 Key Takeaway Polymorphism allows one interface to perform multiple behaviors, making Java programs: More flexible Easier to maintain Less repetitive It is one of the most powerful concepts used in real-world Java applications and interviews. #CoreJava #Polymorphism #JavaOOP #MethodOverriding #Upcasting #Downcasting #JavaLearning #DeveloperJourney #InterviewPreparation
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