This video tutorial will explain all about Java String data type, how to create it, immutability, string buffer, and builder with examples:
Since String is a non-primitive data type, we will also lay down the difference between primitive and non-primitive data types.
Apart from this, the Java String format() method will be explained along with the method signature, implementation, return type, parameters, and examples. These examples will be sufficient to understand the topic in detail.
Some frequently-asked questions will be provided as a part of the tutorial just to illustrate the trending questions on the topic i.e. Java String data type.
We will also briefly explore:
- How to create a string
- Immutability of string
- How to create String Buffer and String Builder
- Difference between string and StringBuffer, string builder.
=> Check ALL Java Tutorials Here
Table of Contents:
Video Tutorial On Java String
Java String Data Type
A String in Java comes under non-primitive data type. In general terms, a String is nothing but a collection of characters i.e. the String data type stores a sequence of characters. Given below is the way in which a typical String is initialized.
The syntax of String in Java is given below.
Syntax:
String str_name = "str_value";
Example:
String name = "Saket"; System.out.println(name);
The above code snippet in the example section will give you the output as – Saket.
Primitive Vs Non-Primitive Data Type
This section will list out the difference between a primitive data type and a non-primitive data type.
Primitive | Non-Primitive |
---|---|
Primitive data types are predefined in Java. | Non-Primitive data types are defined by the user. They are not defined by Java. However, String is defined by Java, so it is an exception. |
These data types don’t refer to objects. | These data types do refer to objects, so they are also known as reference types. |
There are eight primitive data types which are - byte, int, short, long, float, boolean, char, and double. | String and Array come under non-primitive data type. |
It starts with a lower case. | It starts with an upper case. |
Each of these data type sizes differs from the other. For example - the size of an int will be less than long but greater than short. | It has the same size. |
Printing A String Variable
This is the most commonly used program when we are dealing with the String. In this example, we will create a variable of String data type and then try to print that variable.
public class example { public static void main(String[] args) { String str = "This is an example of String"; System.out.println(str); } }
Output:
Java String Format
This is a method of String that returns the formatted output. The formatting is done according to the given locale, arguments, and the type of format. However, the locale is optional.
If you don’t specify the locale in the “String.format() method”, then it will use the default locale by calling the “Locale.getDefault() method”.
Parameters
- Locale: It specifies the locale that has to be applied to the format() method.
- Argument: Zero or more than zero arguments that will be for the format String.
- Format: It specifies the format of the String.
Method Signature
public static String format(String format, Object… args)
and,
public static String format(Locale locale, String format, Object… args)
Implementation
public static String format(String format, Object… args) {
return new Formatter().format(format, args).toString();
}
Return type
The return type is also a String but a formatted one.
Exceptions
- NullPointer: If the format is NULL, then a NullPointerException will be thrown.
- IllegalFormat: If the format is not correct then IllegalFormatException will be thrown.
Java String Format Example
Before we start, we must know that in the format, %d is for Integer, %f is for floating-point number, %s is for String, %x is for hexadecimal, and %c is for the character.
In the below example, we have initialized a variable of String data type and used String.format() Java method to concatenate. Then, we have also used String.format() method to decide the number of places (after the decimal) up to which the given floating-point number will be printed.
Also, we have used Java String.format() method to define the whitespace between the format and the argument.
public class example { public static void main(String[] args) { String str = "Programming"; // The below line will simply concatenate the output String concat = String.format("I love %s", str); // This will display the output up to 10 places after the decimal String decimal = String.format("Decimal upto 10 place %.10f", 97.25); /* * Here, 2 defines the total count of places up to which the * number will be printed and 10 defines the space between "must be" and "22.50" */ String spaces = String.format("Spaces must be %10.2f", 22.50); System.out.println(concat); System.out.println(decimal); System.out.println(spaces); } }
Output:
More About Strings In Java
Assigning String literals:
String s = “STH”; In this way, the compiler will check if there is any “STH” literal available in the string pool.
If it is available, then a reference will be made to String s.
Creating a new Object:
String s=new(“STH”); In this way, the new string object will be created in the heap.
Example Program:
public class DemoString { public static void main(String[] args) { String s1="STH"; String s2="STH"; String s3=new String("STH"); String s4=new String("STH"); System.out.println("s1=="+System.identityHashCode(s1)); System.out.println("s2=="+System.identityHashCode(s2)); System.out.println("s3=="+System.identityHashCode(s3)); System.out.println("s4=="+System.identityHashCode(s4)); } }
OUTPUT:
From the output, we can see, that the string created using new will have a different unique hash code though it had the same value.
Immutability of String:
A string is immutable as you cannot change the value.
Example:
public class Immutablestring { public static void main(String[] args) { String str="software"; str.concat("engineering"); System.out.println(str); } }
From the above example, we understand that we cannot change the string value. If we perform any string operations using string methods (like concat, substring ) a new string will be created. And the original string won’t change.
Several string methods are available to perform the string operations.
Some of the methods include:
Substring() – Returns the substring of the string.
Concat() – Concatenates the string.
Length () – Returns the length of the string
valueOf – Convert to string from other data types.
Example:
public class StringMethods { public static void main(String[] args) { int i=5; String str="software"; String str1="tester"; str.concat("engineering"); System.out.println("str.length()=="+str.length()); System.out.println("str.substring=="+str.substring(2, 4)); System.out.println("String.valueOf(i)=="+String.valueOf(i)); String sf=String.valueOf(1.1); System.out.println("sf=="+sf); System.out.println("str.equals(str1)=="+str.equals(str1)); System.out.println(str.toUpperCase()); System.out.println("str.contains=="+str.contains("of")); } }
OUTPUT:
How To Create StringBuffer And StringBuilder
Both StringBuffer and StringBuilder are mutable.
StringBuffer bf=new StringBuffer();
StringBuilder sb=new StringBuilder();
Example:
package demoofoop; public class DemoBuffer { public static void main(String[] args StringBuffer sb =new StringBuffer("one_"); sb.append("two"); System.out.println(sb); StringBuilder stb=new StringBuilder("firststring_"); stb.append("appendstring"); System.out.println("stb==="+stb); } }
OUTPUT:
Key Points to be noted:
- A string is immutable, hence the length is fixed and you cannot change the value.
- StringBuffer and StringBuilder value are mutable and you can change the value.
- StringBuffer is thread safe and StringBuilder is not synchronized. Hence, it is not thread-safe.
Frequently Asked Questions
Q #1) What is String in Java?
Answer: String is a non-primitive data type in Java. A collection of characters is known as String.
Q #2) What is String used for in Java?
Answer: String is used for collecting a number of characters in Java and then you can perform various actions on them through a list of inbuilt String methods.
Q #3) Is String a data type in Java?
Answer: Java String is a primitive data type.
Q #4) When is String used in Java?
Answer: Whenever you feel the need of operating on the collection of characters or a word or a sentence, you can use a String in your program.
Conclusion
In this tutorial, we have learned String data type in Java. The syntax, description, and examples were provided along with the difference between the two types (primitive and non-primitive) of data-type.
Also, we have provided a description of the Java String format() method along with the parameter, method signature, implementation, return type, and exceptions that are thrown by this method.
A detailed example of the Java String format() method is also provided with a proper explanation of the program. Lastly, few frequently asked questions are also included as a part of this tutorial.
=> Visit Here To Read Through The FREE Java Guide