- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Strings
In Java, strings are objects that represent sequences of characters. Here's an overview:
String Class:
- String in Java is represented by the java.lang.String class.
- It is immutable, meaning once created, the content of a string cannot be changed.
String Literals:
- Strings can be created using string literals enclosed in double quotes (").
- Example: "Hello, Java!".
String Concatenation:
- Strings can be concatenated using the + operator.
- Example: "Hello" + ", " + "Java!" results in "Hello, Java!".
String Methods:
- The String class provides various methods for manipulating strings, such as length(), charAt(), substring(), indexOf(), toUpperCase(), toLowerCase(), trim(), etc.
String Comparison:
- Strings can be compared using the equals() method for content comparison and the compareTo() method for lexicographical comparison.
- Example: "hello".equals("world") returns false.
Example
public class StringsExample {
public static void main(String[] args) {
// String literal
String message = "Hello, Java!";
// String concatenation
String greeting = "Hello";
String name = "Java";
String sentence = greeting + ", " + name + "!";
// String methods
int length = message.length();
char firstChar = message.charAt(0);
String substring = message.substring(7);
int index = message.indexOf(",");
boolean startsWithHello = message.startsWith("Hello");
boolean endsWithJava = message.endsWith("Java");
// String comparison
boolean isEqual = message.equals("Hello, Java!");
int comparisonResult = message.compareTo("Hello, World!");
}
}
Summary
Java strings are represented by the String class and are immutable. They can be created using string literals, concatenated using the + operator, and manipulated using various methods provided by the String class. Understanding strings is essential for handling text data in Java programs.