×

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

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

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.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 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.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.