How to Declare and Initialize a String in Java


There are two main ways to create Java Strings. One is by creating a String literal (see top line in picture below). The other is to explicitly create a new Object in memory (See second line below). I will avoid going into detail about how these differ as it involves discussing aliasing and how Java saves memory. Note: Unlike some other programming languages, in Java Strings must be enclosed in double quotes. Single quotes are used for chars, a primitive data type. 
 
Important Methods of a Java String 
 String Concatenation 
 To concatenate Strings (join to Strings), the easiest way to do it is just use the + operator as shown in the example below 

tring abcAsVariable ="abc"; 
String defAsVariable ="def"; 
String abcdef = "abc" + "def"; 
You could achieve the same concatenation by using the variables as shown in the next line.
String abcdef = defAsVariable + abcAsVariable ; 

No comments :

No comments :

Post a Comment