- String in Java
- Which approach I should prefer to declare a string, «» or new keyword ?
- String class program in Java
- Why java uses a special memory for string ?
- What is string literal in java ?
- How can I check if two string variables or literal have same reference(address) ?
- String concatenation in java
- Java program to concatenate two string
- String is immutable in Java.
- Why string is immutable in Java ?
- Declare a Constant String in Java
- Declare a Constant String in Java
- Related Article - Java String
- Constants in Java | Types, Example
- Integer Constants in Java
- Decimal Integer:
- Octal Integer:
- Hexadecimal Integer:
- Real (Floating-point) Constants in Java
- Single Character Constants in Java
- String Constants
- Backslash Character Constants
String in Java
String is one of the most widely used data type by java programmers. Things that we normally use in conversations like «hello» , «refresh java» , «Hello world» , «It’s easy to learn java» , name of a person, address of a person etc are some of the examples of string in java.
In java a string is basically a sequence of characters, for example the string «hello» is a sequence of characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ . Similarly each string in java is a sequence of characters. Java language provides String class to create and manipulate strings in your programs. This class is defined in java.lang package which comes automatically in your java software(JDK or JRE).
Since a class in java acts as a non primitive data type, so String is also a non primitive data type. You can use String class as a data type to store string values. The Syntax of declaring a string is :
String var_name ="refresh java"
; String var_name =new
String("Hello World"
);
Here String is the data type, var_name is the name of variable which is given as per the programmers choice and the value of string variable is given inside «» . You need to use the double quotes( «» ) to create string values in java.
Which approach I should prefer to declare a string, «» or new keyword ?
Though you can use any of the above approach but creating a string using new operator is not commonly used and is not recommended as it creates an extra object inside heap memory.
String class program in Java
class
StringDemo <public static void
main(String args[]) <// Creating String variables
String strVar ="refresh java";
String strVar2 =new
String("Hello World"
); char[] charArray = 'h', 'e', 'l', 'l', 'o'>; String strVar3 =new
String(charArray); String strVar4 = strVar;// Printing the values of String variables
System.out.println("strVar string">"strVar2 string">"strVar3 string">"strVar4 output-h">Output:
strVar = refresh java
strVar2 = Hello World
strVar3 = hello
strVar4 = refresh javaJava string memory allocation
String values in java are stored inside a special memory known as string pool or string constant pool which exist inside the heap memory. This memory is used to allocate space for string values only. String values given inside
""
in your program are created inside string pool. To understand memory allocation of strings, let's consider we have following string variables declared inside a program.1. String s1 ="refresh java"
; 2. String s2 =new
String("Hello World"
); 3. String s3 =new
String("hello"
); 4. String s4 ="refresh java"
; 5. String s5 ="hello"
;Let's understand how java assigns memory for above strings variables.
- Line 1, java checks if string literal "refresh java" is already in string pool or not, since it's not there, java creates this string literal in string pool and assigns the reference(address) of this in s1 .
- Line 2 is creating object s2 using new keyword, so java will create it inside the heap memory with value as "Hello World" and it will also create the string literal( "Hello World" ) inside the string pool as well.
- Line 3 is also creating object s3 using new keyword, so it will also be created inside the heap memory with value as "hello" and the same string literal( "hello" ) would also be created inside string pool.
- Line 4, java again checks the string literal "refresh java" inside the string pool, since it's already there in pool, so it won't create it again. Java assigns the reference of existing string literal in s4 .
- Line 5, java again checks the string literal "hello" inside string pool, since it's already there in pool, so it won't create it again. Java assigns the reference of existing string literal in s5 .
Why java uses a special memory for string ?
Since String is one of the most useful data type, to improve the memory usage and application performance java usage string pool memory as it doesn't create unnecessary or duplicate objects, instead it uses the existing string objects.
What is string literal in java ?
A series of characters in your program that is enclosed in double quotes( "" ) is a string literal. For example "hello world" , "refresh java" , "java is easy to learn" are string literals in java. Whenever it encounters a string literal in your code, the compiler creates a String object with its value in string constant pool. String literals are string constants in java.
How can I check if two string variables or literal have same reference(address) ?
You can use == operator to compare if two string variables or literals have same address. For example s1==s2 , s1==s4 etc. You can refer next tutorial for more details about this.
String concatenation in java
This is also used very often by java programmers. String concatenation is a way of concating(adding) two or more string values. Java provides the feature of adding two or more string variable or values using plus( + ) operator. For example you can add two string values "refresh" and "java" as "refresh" + "Java" which results as a new string "refreshJava" . Java also provides the concat method in String class to concat two string variables or values. You can refer next tutorial about this method.
Java program to concatenate two string
s1 = refreshJava
s2 = refreshJava tutorialString is immutable in Java.
Immutable simply means something that is not changeable, once a string value in java is created, you can not change that value. For example in above program the code s1+s2 will create a new string "refreshJava" and assigns the reference of this in s1 but the original string "refresh" will still be there in string pool memory, that is why string in java is immutable.
Why string is immutable in Java ?
Since immutable strings can not be changed, the same string can be referenced in multiple programs or applications which significantly improves the memory usage and application performance.
- String pool, string constant pool and string literal pool and string intern pool are same things.
- Digits can also be stored as string in java, for example String str = "12345"; is a valid string.
- The '+' operator, which performs addition on primitives (such as int and double), is overloaded to perform concatenation on String objects. The compiler, internally uses the append method of StringBuffer/StringBuilder class to implement string concatenation.
Declare a Constant String in Java
This tutorial demonstrates how to declare a constant string in Java.
Declare a Constant String in Java
A constant string is declared when it is required to be immutable, which means once any data is defined as constant, it cannot be changed.
Constant strings are declared as private static final String in Java. These strings are initialized in the class and used in the different methods.
public class Constant_String //Declaring a Constant String private static final String DEMO="Welcome To Delftstack!"; public static void main(String args[]) //Print the Constant String System.out.println(DEMO); > >
The code above declares DEMO as a constant string that cannot be changed again.
If we try to re-declare the constant string, Java will throw an error in the output.
public class Constant_String //Declaring a Constant String private static final String DEMO="Welcome To Delftstack!"; public static void main(String args[]) //Print the Constant String System.out.println(DEMO); //Re-declare the constant string DEMO = "The String is Re-declared"; System.out.println(DEMO); > >
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Constant_String.DEMO cannot be assigned at Constant_String.main(Constant_String.java:9)
The final keyword always prevents data from being redefined. We can also declare other data types as constants.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
Related Article - Java String
Constants in Java | Types, Example
A value which is fixed and does not change during the execution of a program is called constants in java.
In other words, Java constants are fixed (known as immutable) data values that cannot be changed.
Java supports various types of constants. They are as follows:
Integer Constants in Java
An integer constant is a sequence of digits without a decimal point. For example, 10 and -200 are integer constants. There are three types of integer constants. They are as follows:
Decimal Integer:
Decimal integer is a sequence of digits from 0 to 9. These constants are either positive or negative. Plus sign is optional.
For example, 24, -55, 0, and +3425 are valid examples of decimal integer constants in decimal notation.
Non-digit characters, embedded spaces, and commas are not allowed between digits. For example, 12 3450, 20.00, $1200 are illegal numbers.
Octal Integer:
An octal integer constant is a sequence of any combination of digits from 0 to 7. Octal integer always starts with 0. The digits 8 and 9 are not valid in octal notation.
The examples of valid integer constants in octal notation are 024, 0, 0578, and 0123.
Hexadecimal Integer:
Hexadecimal integer constants consist of digits 0 to 9 and alphabets “a” to “f” or “A” to “F”. These constants are preceded by 0x. Letter “A” to “F” represents the numbers 10 to 15.
The valid examples of hexadecimal integer constants are 0x23, 0x5B, 0x9F, 0x, etc. “x” can also be either small or capital.
We rarely use octal and hexadecimal integer numbers system in programming.
Let’s create a program to study decimal, octal, and hexadecimal notation for integers.
Program code 1:
package constantsPrograms; public class IntegerConst < public static void main(String[] args) < int a, b, c; a = 20; // decimal notation. b = 020; // octal notation. c = 0x20F; // hexadecimal notation. System.out.println("Decimal notation 20: " +a); System.out.println("Octal notation 020: " +b); System.out.println("Hexadecimal notation 0x20F: " +c); >>Output: Decimal notation 20: 20 Octal notation 020: 16 Hexadecimal notation 0x20F: 527Real (Floating-point) Constants in Java
Real constants consist of a sequence of digits with fractional parts or decimal points. These constants are also called floating-point constants. The valid examples of real constants are 2.3, 0.0034, -0.75, 56.7, etc.
These numbers are shown in the decimal point notation. It is also possible that the number may not have digits before decimal point or digits after the decimal point. For example, 205., .45, -.30, etc.
A real constants number can also be expressed in exponential or scientific notation. For example, the value 235.569 can also be written as 2.35569e2 in exponential notation. Here, e2 means multiply by 10^2.
It has the following general form:
mantissa is either integer number or a real number expressed in decimal notation. The term exponent is an integer with an optional plus or minus sign.
The letter “e” is used to separate mantissa and exponent which can be written in either lowercase or uppercase. The valid examples of floating points constants are 0.54e2, 12e-4, 1.5e+5, 2.13E4, -1.5E-4, etc.
Embedded (blank) space is not permitted in any numeric constants. Exponential notation is useful to represent either very small or very large number in magnitude.
For example, 250000000 can also be written as 2.5e8 or 25E7. Similarly, -0.000000021 is equivalent to -2.1e-8.
Single Character Constants in Java
A single character constant ( or simply character constant) is a single character enclosed within a pair of single quote. The example of single-character constants are as follows:
The last constant is blank space. The character constant ‘5’ is not equivalent to the number 5.
String Constants
A string constant is a sequence of characters within a pair of double-quotes. The characters can be alphabets, special characters, digits, and blank spaces. The valid examples of string constants are given below:
“Hello Java” “1924” “?…!” “2+7” “X” etc.
Backslash Character Constants
Java provides some special backslash character constants that are used in output methods. For example, the symbol ‘n’ which stands for newline character.
There are various types of backslash character constants that are supported by java. The list is given in the below table.
Table: Backslash Character Constants
Constants Meaning ‘ b ‘ back space ‘ f ‘ form feed ‘ n ‘ new line ‘ r ‘ carriage return ‘ t ‘ horizontal tab ‘ ‘ ‘ single quote ‘ ” ‘ double quote ‘ ‘ backslash Hope that this tutorial has covered almost all important points related to constants in java with example programs. I hope that you will have understood this tutorial and enjoyed it.
Thanks for reading.
Next ⇒ Operators in Java ⇐ PrevNext ⇒