-
Notifications
You must be signed in to change notification settings - Fork 0
Strings
A string is a basically a sequence of characters, words or phrases. In Java a string is a built in class that can be used to store those things. For example, "Hello my name is Tom" is a string. Strings are used all the time to do things from storing user input to just simply telling the user hello.
How then do you write a string?
There are multiple ways you can display a string one of the most common ways is to use a print line statement (abbrv. println), also known as a print statement. A println statement is simply method outputs what you tell is to. The syntax is as follows:
System.out.println("Hello World");
Output
Hello World
With a println statement whatever you put inside of the double quotes will be displayed in the command line. There are also different types of print statements. The two major statements are print and println. The difference between the two is that println, once it outputs the results, moves to the next line. print, on the other hand, stays on the same line after it outputs. Print statements are used generally when you are taking user input or want the program to perform different actions on the same line.
Concatenation simply means to combine or put things together in a chain or series. To perform concatenation you would use a concatenation operator which is basically a symbol that tells the IDE to combine things. In Java, the concatenation operator is the plus (+) symbol. Let's say that you wanted to combine two separate strings using the operator. All you would do is place the operator between the two strings.
Example:
System.out.println("Hello World: " + "Welcome to Java");
Output:
Hello World: Welcome to Java
For the code above I have two different strings. One says "Hello World: " and "Welcome to Java" to concatenate this strings all I did was I place the plus sign between the two strings and the output became, "Hello World: Welcome to Java".
Note: Notice how I put the space at the end on Hello World this is because both of the strings above are what are called literal strings. This means that they are stored in memory EXACTLY how you input them. If I removed the space and then combined the strings that the output would be, "Hello World:Welcome to Java".
Not only can strings be used to display text and strings they can also be used to store data. To do this you would declare and initializing the string. This basically means that you are creating the string and assigning a value to it. You do not have to initialize a string, or any other data type for that fact, but it is always a good idea to initialize a string or variable at the same time that you declare it. The reason you declare and initialize this way to avoid program crashes due to the variable not having a value.
To declare and initialize a string you would first call the string class. This tells the IDE that whatever follows this statement is the name of the string. Next, you would give the string a name. This name can be whatever you want it to be. The final step is to initialize the string by setting it equal to a value using the assignment operator. All the assignment operator does is say the this "is equal to" that. Again you can set this value to be whatever you want it to be. Now if you've done everything correctly then congrats because you've just created your first string variable.
Example:
String greeting = "Hello";
Now you may be saying to yourself, "Yeah I stored the data in the String but how do I use it?". That's simple as you do is you call the variable name that you saved the string under. A call is basically when you tell the program to bring up the value of this location in memory related to this variable and do something with it. For example is I wanted to call the variable I just made above I would do:
System.out.println(greeting);
This call tells the IDE to find the value related to the greeting variable and output on the screen.
You can also combine concatenation and use strings as variable to make custom output. Let's say you wanted to say something to a person name Tom.
Example
String name = "Tom";
System.out.println("Hello World " + name);
System.out.println("Goodbye " + name);
Output:
Hello Tom
Goodbye Tom
Some programs you can get away with just declaring variables and using that for most of the program. However, any good program needs to be able to accept user input. If you have a calculation program you don't just want to use some pre-defined values, you want the user to be able to enter their own values and then perform the calculation. To do this we will need to use what is called a Scanner. A scanner, in general, is an object of the Scanner class which was created to accept user input. To learn more about classes you can visit the classes section here
To import the scanner class places the following code outside of your class declaration:
import java.util.Scanner
This import the built-in Scanner class into your class so that you can create objects from it.
Object are touched upon more in the classes section but in short, an object is an instance of a class. By creating an object wee can use the attribute from that class. This goes for the Scanner class as well. To create a Scanner class you will do the following:
Scanner keyboard = new Scanner(System.in);
This line of code creates a scanner object called keyboard. This can be named anything you want it to be but it is named keyboard because it will take input from the keyboard.
Now that we have the scanner object created we can use it to read user input. To do this first we need to declare a variable to store the input in and then use the appropriate method to read that input. Finally, we need to store this input into the variable. Let's say we want to accept integer input.
import java.util.Scanner;
public class Strings {
public static void main(String args[])
{
//creating int to store user input
int userNumber = 0;
//creating scanner object
Scanner keyboard = new Scanner(System.in);
//asking user to enter number
System.out.print("Enter a number: ");
//setting input equal to the userNumber
userNumber = keyboard.nextInt();
//outputs the userNumber
System.out.println("Your number is " + userNumber);
}
}
In the above code, you create a userNumber variable to store the input and then read in the input using the nextInt() method.
The Scanner class has different methods that are used to read input. Below is a table of each of those methods.
Method | Description |
---|---|
nextDouble() | Retrieve input as double |
nextInt() | Retrieves input as integer |
nextLine() | Retrieves next line of data and turns it into a String |
next() | Retrieves the next complete token as a String |
nextShort() | Retrieves next line as a short |
nextByte() | Retrieves next line as a byte |
nextFloat() | Retrieves input as a float |
nextLong() | Retrieves input as a long |
It is also possible to use multiple methods in a class to read in multiple types of input. If you wanted a program that read in both a String and integer input.
import java.util.Scanner;
public class Strings {
public static void main(String args[])
{
//creating int to store user input
int userNumber = 0;
String userInput = "";
//creating scanner object
Scanner keyboard = new Scanner(System.in);
//Asks user to enter their name
System.out.print("Enter your name: ");
//stores their name into the userInput variable
userInput = keyboard.nextLine();
//asking user to enter number
System.out.print("Enter a number: ");
//setting input equal to the userNumber
userNumber = keyboard.nextInt();
//outputs the userNumber and userInput
System.out.println("Your name is: " + userInput);
System.out.println("Your number is " + userNumber);
}
}
Output
Enter your name: Bubba
Enter a number: 59
Your name is: Bubba
Your number is 59
An important thing to know is that you can run into when using the Scanner class. If I were to ask the user for the number before I asked for their name then the output would look something like this:
Enter a number: 23
Enter your name: Your name is:
Your number is 23
As you can see the line asking for the user to enter their name is skipped. This is because the line asking for name uses the nextLine() method which reads keyboard buffer differently from the other methods. Keyboard buffer is where the characters you type using the keyboard are stored in memory temporarily. The next(), nextInt(), and nextDouble() methods retrieve all tokens, characters separated by whitespace, in a buffer up to the nearest whitespace. This whitespace may be a space, tab or enter key. The nextLine() method retrieves everything up until the next enter key. This means that an extra enter keystroke is stored into the buffer. To solve this you can include an extra nextLine() statement to retrieve, or consume, the extra enter key.
//Asks user to enter their name
System.out.print("Enter your name: ");
userInput = keyboard.nextLine();
//extra nextLine() to consume the extra enter
keyboard.nextLine();
System.out.print("Enter a number: ");
userNumber = keyboard.nextInt();
System.out.println("Your name is: " + userInput);
System.out.println("Your number is " + userNumber);
Output
Enter your name: Bubba
Enter a number: 59
Your name is: Bubba
Your number is 59