Java Strings

Java Strings

A String in Java is a sequence of characters, used for storing text.
Strings in Java are objects, not primitive data types.

Example:

String name = "John";

โœ… Creating Strings

There are two common ways to create strings:

1. Using String Literal (Recommended)

String name = "Java";

2. Using new Keyword

String name = new String("Java");

๐Ÿงต String Output Example

public class Main {
public static void main(String[] args) {
String name = "Vipul";
System.out.println(name);
}
}

๐Ÿ”น String Length

Use .length() method:

String txt = "Hello World";
System.out.println(txt.length()); // Output: 11

๐Ÿ”น String Methods

Uppercase and Lowercase

String txt = "Hello";
System.out.println(txt.toUpperCase()); // HELLO
System.out.println(txt.toLowerCase()); // hello

Finding Characters

Use .indexOf() to find character or word position:

String text = "Hello Java";
System.out.println(text.indexOf("Java")); // Output: 6

๐Ÿ”น Concatenation (Joining Strings)

Method 1: Using +

String first = "Hello";
String last = "Java";
System.out.println(first + " " + last);

Method 2: Using .concat()

String first = "Hello";
String last = "Java";
System.out.println(first.concat(" ").concat(last));

๐Ÿ”น Special Characters (Escape Characters)

Character Meaning
\" Double quote
\\ Backslash
\n New line
\t Tab

Example:

String txt = "She said, \"Hello!\"";
System.out.println(txt);

๐Ÿ”น Strings Are Immutable

Once created, a string cannot be changed.
Example:

String name = "Java";
name = name + " Programming"; // Creates a NEW string in memory
System.out.println(name);

๐Ÿ”น Comparing Strings

Use .equals() instead of ==.

String a = "Java";
String b = "JAVA";

System.out.println(a.equals(b)); // false
System.out.println(a.equalsIgnoreCase(b)); // true


๐Ÿ”น String Formatting

String name = "Vipul";
int age = 22;

System.out.printf("My name is %s and I am %d years old.", name, age);


โญ Complete Example

public class Main {
public static void main(String[] args) {
String name = "Vipul";
System.out.println("Name: " + name);
System.out.println("Length: " + name.length());
System.out.println("Uppercase: " + name.toUpperCase());
System.out.println("Contains 'V'? " + name.contains("V"));
}
}

๐Ÿ“Œ Summary

Feature Details
Type Non-Primitive
Mutable? No (Strings are immutable)
Stored in String Pool (for literals)
Important Methods length(), toUpperCase(), toLowerCase(), indexOf(), concat(), equals(), contains()

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *