In this blog, we will cover in depth knowledge of strings in java using this table of content…
So let us jump in to understanding String functions in java, starting with the strings in javaโฆStrings In Java
A string is a sequence of characters or sentences or words, enclosed between double-quotes. To define a string, use a variable with String data type. String in java is present at java.lang.String class and hence it is an object.
There are two ways to create a string in java A string can be created by enclosing the characters in double-quotes which creates only one object as follows:
String str = โHi there, how is it going?โ;
String str = new String(โHi there, how is it going?โ);
You might get a question, What is String Pool and Heap Memory? well, the string pool is a collection of all the defined strings, and heap memory has all the unique values of those strings. Whenever you define a new string with a previously saved value, the string pool will address the previously stored same value instead of creating a new one or allocating memory in the heap for the new string.
Hope you understood, what are strings in java, let us now learn about strings as an array in java.String as an Array
Strings in java are immutable and shareable, that is they cannot be changed because a string is the same as an array of characters and as the size of the array cannot be changed after definition, the strings cannot be changed as well.
ย Here is an example
String data = 'Helloo';
// is as same as
char string[] = {'H','e','l','l','o','o'};
String str = new String(string);
The java.lang.String class applies the three interfaces, Serializable interface, Comparable interface, and CharSequence interface.
If you want to create mutable strings, StringBuilder and StringBuilder classes and a StringTokenizer class can be used to divide the string into tokens.
Check out this Complete Online Java Course by FITA. FITA provides a complete Java course where you will be building real-time applications using Servlets, Hibernate Framework, and Spring with Aspect Oriented Programming (AOP) architecture,Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, to make you an industry-certified java developer.
Methods for Strings In Java
There are many built-in methods for strings in java for calculating the length, removing spaces for replacing characters from the string, converting to lower or upper case, etc, so let’s discuss a few of them, starting with the length() method in java.
This function or method returns the size of a string. You might get confused with the length variable. The length variable works on arrays to return size such as array.length whereas the length() method works with strings to return the size of the string. Let me clear with an example
// Example program for demonstrating length() method
import java.util.*;
public class Main {
// driver method
public static void main(String args[]) {
char string[] = {'H','e','l','l','o','o'};
System.out.println(string.length);
String str = "Hi there everybody";
System.out.println(str.length());
}
}
6
18
This method compares the two strings with case sensitivity and returns 0 if both are equal, -n for the number of additional characters and n (positive) for the number of missing characters.Here is an example
// Example program for demonstrating compareTo() method
import java.util.*;
public class Main{
public static void main(String args[]){
String s_1="hi there";
String s_2="HiThere";
String s_3 = "hi there everybody";
String s_4="hola";
System.out.println(s1.compareTo(s_2));
System.out.println(s1.compareTo(s_3));
System.out.println(s4.compareTo(s_3));
}}
-32
-10
6
String str_1 = "FITA";
String str_2 = ""; //empty string
//Returns the length of str_1 in positive
str_1.compareTo(str_2); //ย outputs 4
// Returns the length of str_1 in negative
str2.compareTo(str1); // outputs -4
Hope you understood the compareTo() method of strings in java for comparing two strings, let us now learn the concat() method of string in java.
The concat() method concatenates or joins two strings, and returns a single string. Here is an example
// Example program for demonstrating concat() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s_1 = "Hi there, ";
s_1 = s_1.concat("how is it going?");
System.out.println(s_1);
}
}
Hi there, how is it going?
// Example program for demonstrating isEmpty() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s_1 = "";
String s_2 = "following?";
System.out.println(s_1.isEmpty()); // true
System.out.println(s_2.isEmpty()); // false
}
}
true
false
// Example program for demonstrating trim() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s1 = "ย hola ย ";
// without the trim method
System.out.println(s1 + "where have you been");
// with the trim method
System.out.println(s1.trim() + "where have you been");
}
}
ย hola ย where have you been
holawhere have you been
// Example program for demonstrating toLowerCase() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s1 = "It's been raining since morning";
String low_s1 = s1.toLowerCase();
System.out.println(low_s1);
}
}
it's been raining since morning
// Example program for demonstrating toUpperCase() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s1 = "It's been raining since morning";
String low_s1 = s1.toUpperCase();
System.out.println(low_s1);
}
}
IT'S BEEN RAINING SINCE MORNING
// Example program for demonstrating ValueOf() method
import java.util.*;
public class Main {
public static void main(String[] args) {
int i = 4;
long lng = -2363861L;
float flt = 613.2f;
double dbl = 713.433d;
char chrs[] = { 'J', 'a', 'v', 'a',',', 'J', 'a', 'v', 'a' };
// convert values to strings
System.out.println(String.valueOf(i));
System.out.println(String.valueOf(lng));
System.out.println(String.valueOf(flt));
System.out.println(String.valueOf(dbl));
// convert character array to string
System.out.println(String.valueOf(chrs));
}
}
4
-2363861
613.2
713.433
Java, Java
// Example program for demonstrating replace() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String str = "How is your day going?";
String rep_str = str.replace('H', 'W');
System.out.println(rep_str);
}
}
Wow is your day going?
// Example program for demonstrating replace() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String str = "How is your day going?";
String rep_str = str.replace("is", "was");
System.out.println(rep_str);
}
}
How was your day going?
// Example program for demonstrating contains() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String name = "Get the best of trainings at FITA Academy";
System.out.println(name.contains("training"));
System.out.println(name.contains("expensive"));
System.out.println(name.contains("FITA Academy"));
}
}
true
false
true
Hope you understood the contains() method of strings in java to check if the given string is present in the other string, let us now learn the equals() and equalsIgnoreCase() method of string in java.
The equals() method returns true if the given two arguments or strings are equal, else false with case sensitivity whereas equalsIgnoreCase() method will true without case sensitivity for the matched strings.
// Example program for demonstrating equals() and equalsIgnoreCase() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String str_1 = "Best JAVA Training at FITA";
String str_2 = "best java training at fita";
System.out.println(s1.equals(str_2));
System.out.println(s1.equalsIgnoreCase(str_2));
}
}
true
false
Hope you understood the equals() method and equalsIgnoreCase() method of strings in java to check if the two strings are equal with and without case sensitivity, let us now learn the toCharArray() method of string in java.
This method will convert the passed argument or string, to a character array as follows;
// Example program for demonstrating toCharArray() method
import java.util.*;
public class Main {
public static void main(String args[]) {
String s1 = "Best Java Training at FITA";
char[] ch = s1.toCharArray();
System.out.print(ch);
}
}
Best Java Training at FITA
// Example program for demonstrating endWith() method
import java.util.*;
public class Main{
public static void main(String args[]) {
String str="On Campus Java Training in Chennai and Bangalore";
System.out.println(str.endsWith("e"));
System.out.println(str.endsWith("Chennai"));
System.out.println(str.endsWith("Bangalore"));
}
}
true
false
true
Hope you understood the endWith() method of strings in java to check if the string ends with the given string, let us now learn the split() method of string in java.
This method can take upto two arguments a regex and an optional limit, and will return an array of substrings of the given string, divided at the specified regex, with size of limit (if specified).
// Example program for demonstrating split() method
import java.util.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String str = "a,e,i,o,u,1,2,3,3";
String[] ch = str.split(",");
System.out.println("result = " + Arrays.toString(ch));
}
}
result = [a, e, i, o, u, 1, 2, 3, 3]
// Example program for demonstrating charAt() method
import java.util.*;
class Main {
public static void main(String[] args) {
String str_1 = "Learn Java With FITA";
for (int i = 0; i < str_1.length(); i++) {
System.out.println(str_1.charAt(i));
}
}
}
L
e
a
r
n
ย
J
a
v
a
ย
W
i
t
h
ย
F
I
T
A
There are many more string methods available, and I would recommend you to practice these problems on strings in java.
This was all about strings and methods in java with example programs. To get in-depth knowledge of core Java and advanced java, J2EE along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework,and Struts through JDBC you can enroll in Java Training in Chennai or Java Training in Bangalore by FITA at an affordable price, bundled with real-time projects, certification, support, and career guidance assistance with an active placement cell, to make you an industry required certified java developer.
ย FITAโs courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.