Java String

Java String

Java String

Java String:

In Java, a String is a sequence of characters used to represent textual data. Here are some examples of how to work with Strings in Java:

  1. Creating a String

To create a String, you can either use double quotes or the String constructor:

				
					String myString1 = "Hello, World!"; // using double quotes
String myString2 = new String("Hello, World!"); // using String constructor

				
			
  1. Concatenating Strings

You can concatenate two or more Strings using the + operator:

				
					String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;

				
			

 

  1. Comparing Strings

You can compare two Strings using the equals() method:

				
					String str1 = "Hello";
String str2 = "World";
if (str1.equals(str2)) {
System.out.println("The two strings are equal.");
} else {
System.out.println("The two strings are not equal.");
}

				
			
  1. Getting Substrings

You can get a substring from a String using the substring() method:

				
					String myString = "Hello, World!";
String substring = myString.substring(7); // returns "World!"

				
			
  1. Converting to Uppercase or Lowercase

You can convert a String to uppercase or lowercase using the toUpperCase() and toLowerCase() methods, respectively:

				
					String myString = "Hello, World!";
String uppercase = myString.toUpperCase(); // returns "HELLO, WORLD!"
String lowercase = myString.toLowerCase(); // returns "hello, world!"

				
			
  1. Splitting Strings

You can split a String into an array of substrings using the split() method:

				
					String myString = "John,Doe,30";
String[] parts = myString.split(",");
String firstName = parts[0]; // returns "John"
String lastName = parts[1]; // returns "Doe"
String age = parts[2]; // returns "30"

				
			

These are just a few examples of the many things you can do with Strings in Java. Strings are a fundamental data type in Java and are used extensively in many Java applications.

 

Join To Get Our Newsletter
Spread the love