In Java, there aren't specific "string operators" like you might find in languages like JavaScript or Python. Instead, Java primarily relies on methods and concatenation to perform operations on strings. Here are some common string operations and techniques in Java:
For Example:-
1.Concatenation Operator +:
You can use the + operator to concatenate (join) strings together.
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
Example:-
class Concat_Operator {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
String third = first + second;
System.out.println(third);
// yet another way to concatenate strings
first += second;
System.out.println(first);
}
}
Output
HelloWorld
HelloWorld
2.Concatenation with Other Data Types:
You can also use the + operator to concatenate strings with other data types, which automatically converts the non-string operands to strings.
int age = 30;
String message = "My age is " + ag
Example:-
public class Demo {
public static void main(String args[]){
String st1 = "Hello";
int age = 500;
String res = st1+age;
System.out.println(res);
}
}
Output
Hello500
3.String Methods:
Java provides a wide range of methods for working with strings, such as length(), charAt(), substring(), indexOf(), toUpperCase(), toLowerCase(), and many others. These methods allow you to perform various operations on strings.
String text = "Hello, World!";
int length = text.length(); // 13
char firstChar = text.charAt(0); // 'H'
String substring = text.substring(7); // "World!"
4.String Comparison:
You can compare strings in Java using the equals() method for content-based comparison and == for reference-based comparison. It's important to use equals() when comparing the contents of two strings because == checks if two string references point to the same memory location.
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = str1.equals(str2); // true
Example:-
class Test {
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
//true (because both refer to same instance)
System.out.println(s1==s2);
//false(because s3 refers to instance created in nonpool)
System.out.println(s1==s3);
}
}
Output
true
false
5.String Formatting:
Java provides the String.format() method and the printf() method for formatting strings using placeholders and format specifiers, similar to C's printf().
String formatted = String.format("Hello, %s!", "John");
System.out.println(formatted); // Hello, John!
Example:-
public class FormatExample{
public static void main(String args[]){
String name="Abhay";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
//returns 12 char fractional part filling with 0
System.out.println(sf1);
System.out.println(sf2);
}
}
Output
name is Abhay
value is 32.334340
6.StringBuilder and StringBuffer:
For efficient string manipulation, especially when you need to concatenate strings in a loop or modify them frequently, you can use the StringBuilder (not thread-safe) or StringBuffer (thread-safe) classes.
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello, ");
stringBuilder.append("World!");
String result = stringBuilder.toString();
Example:-
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
Output
hellojava
Example:-
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("Abhay");
System.out.println(builder);
}
}
Output
helloAbhay
Indeed, the Java String class offers a wide range of methods for performing various operations on strings. Some of the commonly used String methods include:
compare(): Compares two strings lexicographically.
concat(): Concatenates one string with another.
equals(): Compares two strings for equality.
split(): Splits a string into an array of substrings based on a delimiter.
length(): Returns the length (number of characters) of a string.
replace(): Replaces occurrences of a specified substring with another substring.
compareTo(): Compares two strings lexicographically and returns an integer.
intern(): Returns a canonical representation of the string.
substring(): Extracts a portion of the string based on given indices etc.
There are two ways to create String object:
By string literal
By new keyword
<String_Type> <string_variable> = "<sequence_of_string>";
1. String literal
One of the advantages of using the `intern()` method in Java is to enhance memory efficiency. This is achieved by preventing the creation of new objects if an identical string already exists in the string constant pool.
Example:
String demoString = “ctiworld”;
2. Using new keyword
In the statement String s = new String("Welcome");, the JVM operates as follows:
It creates a new string object in the regular (non-pool) heap memory, and the literal "Welcome" is placed in the string constant pool. Consequently, the variable s will point to the object in the heap (non-pool) memory.
Example:
String demoString = new String (“ctiworld”);
Interfaces and Classes in Strings in Java
CharBuffer is a class that implements the CharSequence interface. Its primary purpose is to enable the substitution of character buffers for CharSequences. An illustrative application of this capability can be found in the java.util.regex package, where CharBuffer is utilized.
A String is essentially a sequence of characters. In Java, String objects are immutable, signifying that they are constant and cannot be altered after their creation
CharSequence Interface: The CharSequence interface in Java serves as a representation for sequences of characters. Below are some of the classes that implement the CharSequence interface:
String
StringBuffer
StringBuilder
1. StringBuffer:- StringBuffer is a companion class to String in Java, and it offers extensive functionality for manipulating character sequences. While strings in Java are immutable and represent fixed-length character sequences, StringBuffer represents character sequences that can dynamically grow and be modified.
StringBuffer demoString = new StringBuffer("ctiworld");
2. StringBuilder:-In Java, the StringBuilder class represents a mutable sequence of characters. Unlike the String class, which creates immutable character sequences, StringBuilder provides an alternative that allows you to create and modify mutable character sequences
StringBuilder demoString = new StringBuilder();
demoString.append("CTI");
3. StringTokenizer:The StringTokenizer class in Java is employed for splitting a string into tokens or smaller components.
Example:-
Indeed, a StringTokenizer object in Java keeps track of an internal current position within the string that it's tokenizing. Certain operations cause this position to move forward as characters are processed. To obtain a token, the StringTokenizer object extracts a substring from the original string used to create it.
StringJoiner is a class within the java.util package in Java, designed for constructing a sequence of characters (strings) separated by a specified delimiter. It also offers the option to begin with a provided prefix and end with a supplied suffix. While similar functionality can be achieved using the StringBuilder class by manually appending a delimiter after each string, StringJoiner simplifies this process, reducing the amount of code you need to write.
Syntax:
public StringJoiner(CharSequence delimiter)
As mentioned earlier, you can create a string in Java using a string literal. A string literal is a sequence of characters enclosed within double quotation marks
String myString = "Hello, World!";
You're absolutely correct! In Java, when you create a string using a string literal, the JVM checks the String Constant Pool. If an identical string exists in the pool, it returns a reference to that existing string instead of creating a new object. This behavior is part of string interning, which helps conserve memory by reusing identical string instances.
In Java, string objects are immutable, which means they cannot be modified or changed after creation. Instead, any operations that appear to modify a string actually create a new string object with the desired changes.
class Demo {
public static void main(String[] args)
{
String name = "Sachin";
name.concat(" Tendulkar");
System.out.println(name);
}
}
Output :-
Sachin
class Demo {
public static void main(String[] args)
{
String name = "Sachin";
name = name.concat(" Tendulkar");
System.out.println(name);
}
}
Output :-
Sachin Tendulkar