String Basics
Strings in Java are sequences of characters enclosed in double quotes. Whenever Java encounters a string literal in the code, it creates a string literal with the value of the string.
Example:
public class StringExample {
public static void main(String[] args) {
String name;
name = "Diablo";
System.out.println("My name is " + name);
}
}
Output:
My name is Diablo
The same can be done using an array of characters.
Example:
public class StringExample {
public static void main(String[] args) {
char[] name = {'D', 'i', 'a', 'b', 'l', 'o'};
String welcomeMsg = new String(name);
System.out.println("Welcome " + welcomeMsg);
}
}
Output:
Welcome Diablo
Concatenate Strings:
Concatenation between two strings in Java is done using the +
operator.
Example:
public class StringExample {
public static void main(String[] args) {
String fname, lname;
fname = "Diablo";
lname = "Ramirez";
System.out.println(fname + " " + lname);
}
}
Output:
Diablo Ramirez
Alternatively, we can use the concat()
method to concatenate two strings.
Example:
public class StringExample {
public static void main(String[] args) {
String fname, lname;
fname = "Diablo";
lname = " Ramirez";
System.out.println(fname.concat(lname));
}
}
Output:
Diablo Ramirez
What if we concatenate a string with an integer?
Concatenating a string and an integer will result in a string.
Example:
public class StringExample {
public static void main(String[] args) {
String name;
int quantity;
quantity = 12;
name = " Apples";
System.out.println(quantity + name);
}
}
Output:
12 Apples