STRINGS
A single letter can be stored in ‘char’ data type whereas a word or a set of letters are stored in ‘string’ data type within double quotes. In two methods, a string can be printed.
System.out.println("xoxo waves");
String blog_name="xoxo waves";
System.out.println(blog_name);
Concatenation
String blog_name="xoxo waves + blog";
System.out.println(blog_name);
Length Calculation
System.out.println(blog_name.length());
EndsWith command
System.out.println(blog_name.endsWith("g"));
StartsWith command
System.out.println(blog_name.startsWith("o"));
isEmpty command
System.out.println(word_1.isEmpty());
toUppercase command
System.out.println(word_1.toUpperCase());
Trim command
This command trims out the extra spaces at the beginning and the end of the string. The spaces present in the middle of two words are not removed.
import java.util.Locale;
class reference{
public static void main(String args[]){
String word_1="xoxo waves ";
System.out.println(word_1);
System.out.println(word_1.trim());
}
}
Output using
trim operator
Java program using strings
There are still many commands which can be done using strings and these are some basic commands which can be used for mini and bigger projects.
import java.util.Locale;
class reference{
public static void main(String args[]){
//printing a string directly
System.out.println("Welcome to");
//assigning a string to a variable and then printing it
String blog_name="xoxo waves";
System.out.println(blog_name);
//adding 2 strings
System.out.println("Welcome to " + blog_name);
//Calculating length of the string
System.out.println(blog_name.length());
//Checking whether the string ends with 's'
System.out.println(blog_name.endsWith("s"));
//Checking whether the string starts with 'x'
System.out.println(blog_name.startsWith("x"));
//Checks whether the string is empty
System.out.println(blog_name.isEmpty());
//Converting the string to uppercase
System.out.println(blog_name.toUpperCase());
String word_1=" xoxo waves ";
//Removing front and back spaces in a string
String word=" Thank you ";
System.out.println(word);
System.out.println(word.trim());
}
}
Output
Online compiler execution
The same code is executed in an online compiler and the same results were obtained successfully. Paste the same code and click execute to check the results. In case of error, add the keyword ‘public’ before ‘class’.





0 Comments