A String in Java is an immutable object of the java.lang.String class that stores a sequence of characters. You can create one using a string literal or the new keyword. Because strings cannot be changed after creation, any modification produces a brand-new String object rather than altering the original.
A String in Java is one of the most-used data types in the language, handling everything from user names to file paths. What makes Java strings special is that they’re immutable, meaning once a String object is created, its value can’t be changed. Any operation that appears to modify a string actually creates a new one. The class is defined in java.lang.String and is automatically available in every Java program.
- Key Takeaway 1: In Java, a String is an object of the
java.lang.Stringclass, not a primitive data type. - Key Takeaway 2: You can create strings two ways: using a string literal (stored in the string pool) or using the
newkeyword (stored on the heap). - Key Takeaway 3: Strings are immutable in Java. Every apparent change creates a brand-new String object.
- Key Takeaway 4: When you need a string you can actually modify in place, use
StringBuilder(single-threaded) orStringBuffer(thread-safe). - Key Takeaway 5: Use
Scannerto read string input from the user at runtime.
What is String in Java
When beginners ask what is string in java, the short answer is: it’s an object that holds text. Unlike int or char, which are primitive types, String is a full class in the java.lang package. That means a String object comes with built-in methods like length(), toUpperCase(), substring(), and dozens more.
Java automatically imports java.lang, so you never need to write an explicit import statement for String. That’s one reason the string concept in java feels natural to beginners from day one. According to the JetBrains State of Developer Ecosystem 2023, Java is used by 48% of developers surveyed worldwide, making string handling one of the most universally practised programming skills in the industry.
How Java Stores Strings Internally
Internally, a String in Java is backed by a char array (before Java 9) or a byte array with a charset flag (Java 9 and later, under the Compact Strings optimisation). The Oracle Java SE documentation confirms that the String class is final, which is precisely why you can’t subclass it or change its core behaviour.
According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most-used programming languages globally, used by around 30% of professional developers. String manipulation is at the heart of almost every Java program those developers write.
Why String in Java Looks the Way It Does
You’ll see code like String s = "Hello"; in virtually every Java tutorial. The capital S in String is not a typo. It signals that you’re working with a class, not a primitive. Compare it with int n = 5; where the keyword is lowercase because int is a primitive. This distinction matters when you’re debugging Java exceptions and common runtime errors like NullPointerException, which can occur when a String variable is declared but never assigned a value.
Declaring and Creating Strings in Java
There are two main ways to create a string in Java, and they behave differently at the memory level. Knowing which one to use, and why, is the kind of detail that separates a prepared candidate from an unprepared one in a technical interview — particularly in assessments like TCS NQT, Infosys InfyTQ, and AMCAT, where Java string questions appear consistently.
Method 1: String Literal
The most common approach is to assign a string literal directly:
String city = "Mumbai";
When Java sees this, it checks the string pool in Java (a special area inside the heap, managed by the JVM) to see if the value "Mumbai" already exists. If it does, Java simply points your variable to that existing object. If it doesn’t, Java creates a new entry. This is called string interning, and it saves memory when the same string value appears multiple times in your program.
Method 2: Using the new Keyword
You can also write:
String city = new String("Mumbai");
This forces Java to create a fresh object on the heap, completely bypassing the string pool check. You get a new object every time, even if "Mumbai" already exists in the pool. This approach uses more memory and is generally avoided unless you have a specific reason for it.
String Declaration Syntax at a Glance
| Method | Syntax Example | Stored In | Reuses Pool? |
|---|---|---|---|
| String literal | String s = "Hello"; |
String Pool (Heap) | Yes |
| new String() | String s = new String("Hello"); |
Heap (outside pool) | No |
| char array conversion | char[] c = {'H','i'}; String s = new String(c); |
Heap | No |
How to Take String Input in Java
Reading a string from the user requires the Scanner class. Here’s the pattern you’ll use constantly:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
Use nextLine() to capture the full line including spaces. If you use next() instead, it stops at the first whitespace, which catches out a lot of beginners when they type a full name like “Priya Sharma” and only get “Priya” back. That’s a real bug that shows up in college lab assignments across BTech and BSc Computer Science programmes every semester — and it’s a standard question in Anna University and Mumbai University practical exams.
If you’re coming from C and want to compare how input and compilation work at a lower level, our guide on how to write, compile and run a C program gives useful context for understanding why Java’s approach is more structured.
Immutability and the String Pool in Java
Immutability is the single most misunderstood part of the string definition in java. When you write String s = "cat"; and then write s = s + "s";, you haven’t changed the original "cat" object. Java created a brand-new string "cats" and pointed s at it. The old "cat" object still exists in memory until the garbage collector cleans it up.
Why Java Made Strings Immutable
There are three concrete reasons the Java designers went with immutability:
- Security: Strings are used for class names, file paths, network URLs, and database queries. If a string could be changed after being validated, an attacker could swap in a malicious value after the security check passes. This is a real concern in secure coding, something you’ll study deeply in certifications like the CEH v13 AI online course.
- String pool efficiency: The string pool in Java only works because multiple references can safely point to the same object. If strings were mutable, changing one reference’s value would corrupt every other reference pointing to the same pool object.
- Thread safety: Immutable objects are inherently safe to share across threads without synchronisation. This is a significant performance win in multi-threaded Java applications.
A Practical Mistake to Avoid in String Concatenation in Java
A very common mistake, especially in interview coding rounds, is concatenating strings inside a loop using the + operator:
String result = "";
for (int i = 0; i < 1000; i++) { result = result + i; }
This creates 1000 throwaway String objects. On large datasets, this tanks performance. The fix is to use StringBuilder, which is covered in the next section. Interviewers at product companies like Infosys, Wipro, and TCS consistently test candidates on exactly this scenario — and NASSCOM’s 2023 industry skills report identifies string handling and memory efficiency as among the top gaps in entry-level Java developer hires in India.
The Oracle Java SE documentation explicitly states that the String class is designed to be immutable, and the JVM takes advantage of this guarantee at multiple levels of optimisation.
Mutable Strings: StringBuilder and StringBuffer
When you need a string you can actually modify without creating new objects every time, Java gives you two alternatives: StringBuilder and StringBuffer. Both live in the java.lang package and offer methods like append(), insert(), delete(), and reverse().
StringBuilder vs StringBuffer: Key Differences
| Feature | StringBuilder | StringBuffer | String |
|---|---|---|---|
| Mutable | Yes | Yes | No |
| Thread-safe | No | Yes (synchronised) | Yes (immutable) |
| Performance (10k iterations) | ~2 ms (no sync overhead) | ~8 ms (sync overhead) | ~900 ms (new object each time) |
| Introduced in Java | Java 5 | Java 1.0 | Java 1.0 |
| Best used for | Single-threaded loops | Multi-threaded environments | Fixed, read-only text |
StringBuilder in Practice
The correct version of the loop from the previous section looks like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) { sb.append(i); }
String result = sb.toString();
This modifies the same internal buffer each time. No throwaway objects, no GC pressure. According to a benchmark study cited in the Java Performance Tuning Guide (O’Reilly, 2023), StringBuilder can be 10x to 100x faster than repeated String concatenation in tight loops, depending on the JVM version and loop count.
When to Use Which
In practice, use StringBuilder for almost everything, unless you’re writing code that multiple threads will access simultaneously, in which case StringBuffer is the safer pick. For most student projects, Android apps, and backend APIs, StringBuilder is the right default.
Understanding these tradeoffs is part of building the programming foundation that full stack developers and software developers both need, regardless of which path you choose. If you’re mapping out your overall learning path, our guide on software development tools to learn first is a good companion read.
For students weighing their career options after a postgraduate programme, our breakdown of jobs and salary after MCA shows how strong Java fundamentals translate directly into hiring outcomes in the Indian IT market.
Frequently Asked Questions
What is a String in Java?
A String in Java is an object of the java.lang.String class that stores a sequence of characters. It’s not a primitive type. Strings are immutable, meaning their content cannot be changed after the object is created. Any operation that appears to modify a string actually produces a new String object.
Is String a class or a primitive data type in Java?
String is a class in Java, not a primitive data type. It belongs to the java.lang package and is written with a capital S. Primitive types like int, char, and boolean are lowercase and have no methods. Because String is a class, String objects come with built-in methods such as length(), substring(), and toUpperCase().
How do I create a string in Java?
You can create a string in Java using a literal: String s = "Hello";, which stores the value in the string pool. You can also use String s = new String("Hello");, which creates a new heap object outside the pool. The literal approach is preferred in most cases because it’s memory-efficient.
Why are strings immutable in Java?
Strings are immutable in Java for three reasons: security (so values can’t be tampered with after validation), string pool efficiency (multiple references can safely share one object), and thread safety (immutable objects need no synchronisation). The String class is declared final, which prevents subclassing and enforces this guarantee.
What is the difference between == and .equals() for string comparison in Java?
The == operator checks whether two String variables point to the exact same object in memory. The .equals() method checks whether two strings have the same character content, regardless of whether they are the same object. For string comparison in Java, always use .equals() to compare values. Using == can return false even when two strings contain identical text, if they were created as separate heap objects.
What is the difference between mutable and immutable strings in Java?
An immutable string, like String, cannot be changed after creation. Every modification creates a new object. A mutable string, like StringBuilder or StringBuffer, can be changed in place without creating new objects. Use StringBuilder for single-threaded scenarios and StringBuffer when thread safety is required.
How do I take string input in Java?
Use the Scanner class: create a Scanner object with System.in, then call sc.nextLine() to read a full line of text including spaces. Avoid sc.next() if the input contains spaces, since it stops reading at the first whitespace character and will silently drop part of the user’s input.
The core idea is simple: String in Java is immutable, stored efficiently in a pool, and is the foundation for nearly every real-world Java application you’ll build or maintain. Getting this right early saves hours of debugging later.
- This week: Write a small Java program that compares two strings using
==and.equals(), then trace which objects are in the pool and which are on the heap. The difference will click immediately. - Next: Rewrite a loop that concatenates strings with
+usingStringBuilderand measure the difference usingSystem.currentTimeMillis(). - Then: If you want to apply these programming fundamentals in cybersecurity, secure coding, or AI development, explore 3.0 University’s full catalogue of online certification courses or start directly with the CEH v13 AI online course, where string handling and input validation are core concepts in understanding how attackers exploit poorly written code.
Last updated: May 2025. Reviewed by the 3University editorial team.