×

What is String in Java?

What is String in Java?

Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings.

Creating Strings

The normal way to create a string in Java is to simply write:-

String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way to create a string is:-

String s = new String (“Hello World”);

String Builder:

The char value, which is a one-character string, is represented by a String class object. We can't use an ASCII value in this case.

Syntax:

StringBuilder str = new StringBuilder();
str.append("GFG");

String Buffer:-

StringBuffer is a String companion class that provides a lot of the same functionality as strings. StringBuffer shows growable and writable character sequences, whereas string represents fixed-length, immutable character sequences.

Syntax:

StringBuffer s = new StringBuffer("Hello World");

String Tokenizer:-

The StringTokenizer class in Java is used to tokenize a string.

String Joiner:-

String Joiner is a java.util package class that is used to build a sequence of characters divided by a delimiter and optionally starting with a transferred prefix and finishing with a transferred suffix.

Syntax:

public StringJoiner(CharSequence delimiter);

As we study in the above part, we have sufficient knowledge about replacing a character in a string

So, there are three ways to replace character in a string:

String Builder:

In contrast to the String Class, the StringBuilder class includes a built-in function for this — setCharAt (). By calling this function and giving the character and the index as parameters, you can replace the character at a given index.

What is Switch in Java?

A switch statement makes it possible to compare a variable to a list of values. Each value is referred to as a case, and each case is compared to the variable that is being turned on.

Syntax:

switch(expression) {
case value :
break; 
case value :
break;
default :
}

String in Switch:

  • In Java, we may utilize a switch statement with Strings.  You should keep the following considerations in your mind while doing that.
  • A NullPointerException will be produced if the argument in the switch cases is null during Run-time.
  • If the data you're interacting with is also Strings, it's best to utilize String values in a switch statement.
  • The case is taken into account when comparing Strings in a switch statement. i.e., the String you provided and the String in the case must be similar and in the same upper or lower case.

Example:

public class SwitchStringExample {
public static void main(String[] args) {
printColorUsingSwitch("Green");
printColorUsingIf("Green");
printColorUsingSwitch("Green");
printColorUsingSwitch(null);
}
private static void printColorUsingIf(String color) {
if (color.equals("yellow")) {
System.out.println("yellow");
} else if (color.equals("Green")) {
System.out.println("Green");
} else {
System.out.println("INVALID COLOR ");
}
}
private static void printColorUsingSwitch(String color) {
switch (color) {
case "yellow":
System.out.println("yellow");
break;
case "green":
System.out.println("Green");
break;
default:
System.out.println("INVALID COLOR ");
}
}
}

OUTPUT:

Green
Green
INVALID CODE

KEY POINTS:

  • By eliminating several if-else-if linked conditions, the Java switch case string makes code better understandable.
  • The output of the above example indicates that the Java switch case string is case-sensitive.
  • To prevent a NullPointerException, the Java Switch case employs the String.equals() function to match the provided value with case values, therefore make sure to include a NULL check.
  • In a Switch statement, the Java compiler produces more effective byte code for String than chained if-else-if expressions.

Example 2:

public class GFG {
public static void main(String[] args)
{
String str = "Hello";
switch (str) {
// Case 1
case "World":
System.out.println("World");
break;
// Case 2
case "Hello":
System.out.println("Hello");
break;
// Case 3
case "UMAR":
System.out.println("UMAR");
break;
// Case 4
// Default case
default:
System.out.println("no match");
}
}
}


OUTPUT:

Hello

Example 3:

public class GFG {



public static void main(String[] args)
{
String str = "";


switch (str) {


// Case 1
case "one":
System.out.println("FIRST");
break;


// Case 2
case "two":
System.out.println("SECOND");
break;


// Case 3
case "three":


// Print statement corresponding case
System.out.println("THIRD");
break;


// Case 4
// Default case
default:


// Print statement corresponding case
System.out.println("NO MATCH");
}
}
}

OUTPUT:

NO MATCH

Related Topics

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.