Java Output Explanation: Concatenation in Java

My First Java Post on LinkedIn Starting my journey of sharing and revising Java concepts here 📘 Let’s begin with a simple output-based question 👇 public class Test { public static void main(String[] args) { String s = "Java"; s.concat(" World"); System.out.println(s); } } ❓ What will be the output and why? Drop your answer in the comments 💬 Let’s learn together 🤝 #Java #JavaDeveloper #LearningJava #FirstPost #CodingJourney

Java Strings are immutable, meaning their values cannot be changed once created. Methods like concat() do not modify the existing String; instead, they return a new String object. This behavior improves security, memory efficiency, and thread safety. To apply changes, the returned String must be reassigned. Example: String s = "Java"; s.concat(" World"); System.out.println(s); // Output: Java s = s.concat(" World"); System.out.println(s); // Output: Java World This example shows that without reassignment, the original String remains unchanged.

Java Because Strings are immutable and we can't contact them.

Java Strings are immutable

Great starting point, Harish! The output will be Java, not Java World. The key reason is that String in Java is immutable. When s.concat(" World") is called, it creates a new String object, but since the result isn’t assigned back to s, the original value remains unchanged. It’s a simple example, but it highlights a concept that often confuses beginners. Learning by revising and sharing like this is a great way to build strong fundamentals—excited to see more such posts

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories