String Variables
As well as storing number values, variables can hold text. You can store just one character, or lots of characters. To store just one character, the char variable is used. Usually, though, you'll want to store more than one character. To do so, you need the string variable type.Start a new project for this by clicking File > New Project from the menu bar at the top of NetBeans. When the New Project dialogue box appears, make sure Java and Java Application are selected:
String first_name;
Assign a value to your new string variable by typing an equals sign. After
the equals sign the text you want to store goes between two sets of double quotes:
first_name = "William";
If you prefer, you can have all that on one line:
String first_name = "William";
Set up a second string variable to hold a surname/family name:
String family_name = "Shakespeare";
To print both names, add the following println( ):
System.out.println( first_name + " " +
family_name );
In between the round brackets of println, we have this:
first_name + " " + family_name
We're saying print out whatever is in the variable called first_name.
We then have a plus symbol, followed by a space. The space is enclosed in double
quotes. This is so that Java will recognise that we want to print out a space
character. After the space, we have another plus symbol, followed by the family_name
variable.Although this looks a bit messy, we're only printing out a first name, a space, then the family name. Your code window should look like this:
String first_name = "W";
But this is not:
String first_name = 'W';
The second version has single quotes, while the first has double quotes.There are lot more to strings, and you'll meet them again later. For now, let's move on and get some input from a user.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment