Java Strings (Beginner Guide with Examples)
Java Strings: Complete Beginner Guide (With Examples)
✨ Quick Summary
In this post, you’ll learn what Strings are in Java and how to work with text. We will cover creating strings, string methods, comparison, and common examples in a simple beginner-friendly way.
In our previous post, we learned about Java Arrays and how to store multiple values in one variable.
Now let’s learn about another super important topic in Java: Strings.
A String in Java is used to store text like names, sentences, passwords, emails, etc.
1) Creating a String in Java
There are two main ways to create a string:
- Using String Literal
- Using new Keyword
Example
public class StringCreateExample {
public static void main(String[] args) {
String name1 = "The Logic Byte Tech";
String name2 = new String("Java Programming");
System.out.println(name1);
System.out.println(name2);
}
}
2) String Length
You can find the length of a string using .length()
public class StringLengthExample {
public static void main(String[] args) {
String text = "Hello Java";
System.out.println("Length: " + text.length());
}
}
3) Access Characters using charAt()
You can access a character in a string using charAt(index).
public class CharAtExample {
public static void main(String[] args) {
String word = "Coding";
System.out.println(word.charAt(0));
System.out.println(word.charAt(3));
}
}
4) Convert String to Uppercase and Lowercase
Java provides:
- toUpperCase()
- toLowerCase()
public class CaseExample {
public static void main(String[] args) {
String name = "Java Programming";
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
}
}
5) Trim Spaces using trim()
trim() removes extra spaces from the beginning and end of the string.
public class TrimExample {
public static void main(String[] args) {
String text = " Hello Java ";
System.out.println(text.trim());
}
}
6) Compare Strings in Java
In Java, never compare strings using == in real projects. Use:
- equals()
- equalsIgnoreCase()
public class CompareExample {
public static void main(String[] args) {
String a = "Java";
String b = "java";
System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));
}
}
7) Common String Methods
Here are some useful string methods you will use often:
Conclusion
Strings are used everywhere in Java, and learning them is extremely important because they help you work with:
- ✅ Names, passwords, emails
- ✅ User input and text
- ✅ Real-world applications
In the next post, we will learn about Java Methods and how to create reusable code in Java!
Easiest way to understand strings
ReplyDeletestraightforward and smooth to understand
ReplyDelete