Another commonly-used type is String, which represents texts
(a sequence of characters) such as "Hello, world". String is not a
primitive type, and will be further elaborated later. In Java, a char is
enclosed by single quotes (e.g., 'A', '0'), while a String is enclosed by
double quotes (e.g., "Hello"). For example,
String message = "Hello,
world!"; // strings are enclosed in double-quotes
char gender = 'm'; // char is enclosed in
single-quotes
In java, string is basically an object that represents
sequence of char values.
An array of characters works same as java string. For
example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is
same as:
String s="javatpoint";
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
The java String is immutable i.e. it cannot be changed but a
new instance is created. For mutable class, you can use StringBuffer and
StringBuilder class.
How to create String object?
There are two ways to create String object:
·
By string literal
·
By new keyword
|
1) String Literal
Java String literal is created by using double quotes. For
Example:
String s="welcome";
Each time you create a string literal, the JVM checks the
string constant pool first. If the string already exists in the pool, a
reference to the pooled instance is returned. If string doesn't exist in the
pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
In the above example only one object will be created.
Firstly JVM will not find any string object with the value "Welcome"
in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not
create new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area
known as string constant pool.
Why java uses concept of string
literal?
To make Java more memory efficient (because no new objects
are created if it exists already in string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in
normal(non pool) heap memory and the literal "Welcome" will be placed
in the string constant pool. The variable s will refer to the object in
heap(non pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
strings
example
.
Java String class methods
The java.lang.String class provides many useful methods to
perform operations on sequence of char values
No.
|
Method
|
Description
|
1
|
char
charAt(int index)
|
returns char value for the particular index
|
2
|
int
length()
|
returns string length
|
3
|
static
String format(String format, Object... args)
|
returns formatted string
|
4
|
static
String format(Locale l, String format, Object... args)
|
returns formatted string with given locale
|
5
|
String
substring(int beginIndex)
|
returns substring for given begin index
|
6
|
String
substring(int beginIndex, int endIndex)
|
returns substring for given begin index and end index
|
7
|
boolean
contains(CharSequence s)
|
returns true or false after matching the sequence of char
value
|
8
|
static
String join(CharSequence delimiter, CharSequence... elements)
|
returns a joined string
|
9
|
static
String join(CharSequence delimiter, Iterable<? extends CharSequence>
elements)
|
returns a joined string
|
10
|
boolean
equals(Object another)
|
checks the equality of string with object
|
11
|
boolean
isEmpty()
|
checks if string is empty
|
12
|
String
concat(String str)
|
concatinates specified string
|
13
|
String
replace(char old, char new)
|
replaces all occurrences of specified char value
|
14
|
String
replace(CharSequence old, CharSequence new)
|
replaces all occurrences of specified CharSequence
|
15
|
String
trim()
|
returns trimmed string omitting leading and trailing
spaces
|
16
|
String
split(String regex)
|
returns splitted string matching regex
|
17
|
String
split(String regex, int limit)
|
returns splitted string matching regex and limit
|
18
|
String
intern()
|
returns interned string
|
19
|
int
indexOf(int ch)
|
returns specified char value index
|
20
|
int
indexOf(int ch, int fromIndex)
|
returns specified char value index starting with given
index
|
21
|
int
indexOf(String substring)
|
returns specified substring index
|
22
|
int
indexOf(String substring, int fromIndex)
|
returns specified substring index starting with given
index
|
23
|
String
toLowerCase()
|
returns string in lowercase.
|
24
|
String
toLowerCase(Locale l)
|
returns string in lowercase using specified locale.
|
25
|
String
toUpperCase()
|
returns string in uppercase.
|
26
|
String
toUpperCase(Locale l)
|
returns string in uppercase using specified locale.
|
For examples,
String str = "Java is
cool!";
System.out.println(str.length()); // return int 13
System.out.println(str.charAt(2)); // return char 'v'
System.out.println(str.charAt(5)); // return char 'i'
// Comparing two Strings
String anotherStr = "Java
is COOL!";
System.out.println(str.equals(anotherStr)); // return boolean false
System.out.println(str.equalsIgnoreCase(anotherStr));
// return boolean true
System.out.println(anotherStr.equals(str)); // return boolean false
System.out.println(anotherStr.equalsIgnoreCase(str));
// return boolean true
// (str == anotherStr) to
compare two Strings is WRONG!!!
To check all the available
methods for String, open JDK API documentation ⇒ select
package "java.lang" ⇒ select class
"String" ⇒ choose method. For
examples,
String str = "Java is
cool!";
System.out.println(str.length()); // return int 13
System.out.println(str.charAt(2)); // return char 'v'
System.out.println(str.substring(0,
3)); // return String "Jav"
System.out.println(str.indexOf('a')); // return int 1
System.out.println(str.lastIndexOf('a')); // return int 3
System.out.println(str.endsWith("cool!")); // return boolean true
System.out.println(str.toUpperCase()); // return a new String "JAVA IS
COOL!"
System.out.println(str.toLowerCase()); // return a new String "java is
cool!"
String and '+' Operator
In Java, '+' is a special operator. It is overloaded.
Overloading means that it carries out different operations depending on the
types of its two operands.
If both operands are numbers (byte, short, int, long, float,
double, char), '+' performs the usual addition, e.g.,
·
1 + 2 → 3
·
1.2 + 2.2 → 3.4
·
1 + 2.2 → 1.0 + 2.2 → 3.2
If both operands are Strings, '+' concatenates
the two Strings and returns the concatenated String. E.g.,
·
"Hello" + "world" →
"Helloworld"
·
"Hi" + ", " +
"world" + "!" → "Hi, world!"
If one of the operand is a String and the other is numeric,
the numeric operand will be converted to String and the two Strings
concatenated, e.g.,
·
"The number is " + 5 → "The
number is " + "5" → "The number is 5"
·
"The average is " + average +
"!" (suppose average=5.5) → "The average is " +
"5.5" + "!" → "The average is 5.5!"
·
"How about " + a + b (suppose a=1,
b=1) → "How about 11"
String/Primitive
Conversion
"String" to "int/byte/short/long":
String inStr = "5566";
int number =
Integer.parseInt(inStr); // number
<- 5566
similarly,
Byte.parseByte(aByteStr)
Short.parseShort(aShortStr),
Long.parseLong(aLongStr)
Double.parseDouble(aDoubleStr)
Float.parseFloat(aFloatStr)
to convert a String (containing a floating-point
literal) into a double or float, e.g.
String inStr =
"55.66";
float aFloat =
Float.parseFloat(inStr); // aFloat
<- 55.66f
double aDouble =
Double.parseDouble("1.2345");
// aDouble <- 1.2345
aDouble =
Double.parseDouble("abc");
// Runtime Error: NumberFormatException
"String" to
"char": You can use aStr.charAt(index) to extract individual
character from a String, e.g.,
// Converting from binary to decimal
String msg =
"101100111001!";
int pos = 0;
while (pos < msg.length()) {
char binChar = msg.charAt(pos); // Extract character at pos
// Do something about the character
.......
++pos;
}
"String" to "boolean": You can use
method Boolean.parseBoolean(aBooleanStr) to convert string of "true"
or "false" to boolean true or false, e.g.,
String boolStr =
"true";
boolean done =
Boolean.parseBoolean(boolStr); // done
<- true
boolean valid = Boolean.parseBoolean("false");
// valid <- false
Primitive (int/double/float/byte/short/long/char/boolean) to
"String": To convert a primitive to a String, you can use the '+'
operator to concatenate the primitive with an empty String (""), or
use the JDK built-in methods String.valueOf(aPrimitve),
Integer.toString(anInt), Double.toString(aDouble), Character.toString(aChar),
Boolean.toString(aBoolean), etc. For example,
// String concatenation operator '+' (applicable to ALL
primitive types)
String s1 = 123 +
""; // int 123 ->
"123"
String s2 = 12.34 +
""; // double 12.34 ->
"12.34"
String s3 = 'c' +
""; // char 'c' ->
"c"
String s4 = true +
""; // boolean true ->
"true"
// String.valueOf(aPrimitive) is applicable to ALL
primitive types
String s1 =
String.valueOf(12345); // int 12345
-> "12345"
String s2 =
String.valueof(true); // boolean true
-> "true"
double d = 55.66;
String s3 =
String.valueOf(d); // double 55.66
-> "55.66"
// toString() for each primitive type
String s4 = Integer.toString(1234); // int 1234 -> "1234"
String s5 =
Double.toString(1.23); // double 1.23
-> "1.23"
char c1 = Character.toString('z'); // char 'z' ->
"z"
// char to String
char c = 'a';
String s5 = c; // Compilation Error: incompatible types
String s6 = c +
""; // Convert the char to
String
// boolean to String
boolean done = false;
String s7 = done +
""; // boolean false ->
"false"
String s8 =
Boolean.toString(done);
String s9 =
String.valueOf(done);
"char" to
"int": You can convert char '0' to '9' to int 0 to 9 by subtracting
the char with '0' (e.g., '8'-'0' → 8).
Escape sequence
Non-printable and control characters can be represented by a
so-called escape sequence, which begins with a back-slash (\) followed by a
pattern. The commonly-used escape sequences are:
Escape Sequence
|
Description
|
Unicode in Hex
(Decimal)
|
\n
|
Newline (or Line-feed)
|
000AH (10D)
|
\r
|
Carriage-return
|
000DH (13D)
|
\t
|
Tab
|
0009H (9D)
|
\"
|
Double-quote
|
0022H (34D)
|
\'
|
Single-quote
|
0027H (39D)
|
\\
|
Back-slash
|
005CH (92D)
|
\uhhhh
|
Unicode number hhhh (in hex),
e.g., \u000a is newline, \u60a8 is 您, \u597d is 好 |
hhhhH
|
Notes:
·
Newline (000AH) and Carriage-Return (000DH),
represented by the escape sequence \n, and \r respectively, are used as line
delimiter (or end-of-line, or EOL). Take note that Unixes and Mac use \n (0AH)
as EOL, while Windows use \r\n (0D0AH).
·
Horizontal Tab (0009H) is represented as \t.
·
To resolve ambiguity, characters back-slash (\),
single-quote (') and double-quote (") are represented using escape
sequences \\, \' and \", respectively. E.g.,
·
To represent a back-slash char, you need to
write '\\', instead of '\', as a back-slash begins an escape sequence.
Similarly, to include a back-slash in a double-quoted string, you need to write
\\.
·
To represent a single-quote char, you need to
write '\'' to distinguish it from the closing single-quote. But you can write
double-quote directly, i.e., '"'.
·
To place a double-quote in a double-quoted
string, you need to use \" to distinguish it from the closing
double-quote, e.g., "\"hello\"". But you can write
single-quote directly, e,g, "'hello'".
·
Other less commonly-used escape sequences are:
\a for alert or bell, \b for backspace, \f for form-feed, \v for vertical tab.
These may not be supported in some consoles.
String Literals
A String literal is composed of zero of more characters
surrounded by a pair of double quotes, e.g., "Hello, world!",
"The sum is: ". For example,
String directionMsg = "Turn
Right";
String greetingMsg =
"Hello";
String statusMsg =
""; // an empty string
String literals may contains escape sequences. Inside a
String, you need to use \" for double-quote to distinguish it from the
ending double-quote, e.g. "\"quoted\"". Single-quote inside
a String does not require escape sequence. For example,
System.out.println("Use
\\\" to place\n a \" within\ta\tstring");
Use \" to place a " within a string
boolean Literals
There are only two boolean literals, i.e., true and false.
For example,
boolean done = true;
boolean gameOver = false;
Example on Literals
/*
* Test literals for various primitive types
*/
public class LiteralTest {
public static void main(String[] args) {
String name = "Tan Ah Teck"; //
String is double-quoted
char gender = 'm'; // char is single-quoted
boolean isMarried = true; // true or false
byte numChildren = 8; // Range of byte is [-127, 128]
short yearOfBirth = 1945; // Range of short is [-32767, 32768].
Beyond byte
int salary = 88000; // Beyond the ranges of byte and
short
long netAsset = 8234567890L; // Need
suffix 'L' for long. Beyond int
double weight = 88.88; // With fractional part
float gpa = 3.88f; // Need suffix 'f' for float
// println() can be used to print value
of any type
System.out.println("Name is " +
name);
System.out.println("Gender is "
+ gender);
System.out.println("Is married is
" + isMarried);
System.out.println("Number of
children is " + numChildren);
System.out.println("Year of birth is
" + yearOfBirth);
System.out.println("Salary is "
+ salary);
System.out.println("Net Asset is
" + netAsset);
System.out.println("Weight is "
+ weight);
System.out.println("GPA is " +
gpa);
}
}
The expected outputs are:
Name is Tan Ah Teck
Gender is m
Is married is true
Number of children is 8
Year of birth is 1945
Salary is 88000
Net Asset is 1234567890
Weight is 88.88
Height is 188.8
No comments:
Post a Comment
Please write your view and suggestion....