When working with Java or any programming language, we usually have to deal with storing lots of different types of data called variables. This can be letters, words, integers, irrational numbers, or just about any data type you can imagine. As we will learn over the next couple of lessons, different situations call for different variable types.
The first variable we will learn is a
String is how we store a word or string of words.
In order to create our String we have to tell the computer that the variable we are creating is indeed a String. Look at the code below.
The first word
String is where we assign the variable type. It is important to note that whenever we are making a new variable, the first word must be the type of variable we wish to create. Another important thing to note, is that the word String must be capitalized!!!
The 2nd word “str” is what the user wants to name/identify the String. The name of the variable is sometimes referred to as the identifier. However, there are a couple of rules when making an identifier:
- The first symbol of the identifier must be a standard letter, a dollar sign “$”, or the underscore symbol “_”.
- After the first character of the identifier is established, the programmer is free to use numbers(0-9.)
- We are not permitted to “Reserved Words” as identifiers. These are words that are already in use/reserved by Java. Some examples of reserved words would be the word “public” or “class.”
- Make the name short and descriptive of what data you are storing. For example, if you had a String that had a list of last names it might look like “lastNames” or “last_names.”
Now that we have gone over our the criteria for naming our identifiers, let us return to our String example:
The equal sign ”=” is an assignment operator in Java. In other words, it lets us assign the data type and identifier to the actual data itself.
Next, we have quotation marks and the String data. The Quotation marks tells the computer where the String starts and ends. Therefore, we have one at the start of the sentence and the other one at the end.
Finally, we have a semicolon “;” after our String. The semicolon tells the computer that we are done with that line of code. If forgotten, it can cause many compilation errors as the computer will read several separate lines of code as one.
However, we don’t always use semicolons when we are done with a line of code. Some examples would be when declaring a class or the main method. One general rule of thumb is that any declarative statements must end with a semicolon – such as declaring our String.