Kevin's Guides
Decorative intro photo for: Chapter 3: Variables, Scanners & Strings

Chapter 3: Variables, Scanners & Strings

Chapter 3: Variables, Scanners, & Strings

This chapter will explain what variables are and how they are used. You will learn about different types of variables (primitive data types), strings, and how to perform some basic math operations. You will also learn how to use Scanners to read user input from the console window. We will conclude this chapter with a project where you build a basic calculator app.

3.1: What's a Variable?

Variables are elements of programs that store data such as numbers or text in the computer’s memory. You can think of them as containers that hold certain values. If you’ve taken an Algebra course before, you’re likely familiar with variables. Variables in Java work similarly to variables in Algebra. There are many different types of variables, and the types you use will vary depending on the situation.

Variables are declared or created by typing the keyword for the variable type followed by the variable’s identifier or name. Variables are initialized when we give them a value. We initialize variables using the equal sign = assignment operator.

Rules for Variable Identifiers

  • You may start the identifier with an underscore, a letter, or a money sign $
  • The subsequent characters in the identifier may be letters, underscores, money signs, or numbers
  • Do not use keywords (reserved words for use by Java) in variable names
  • Identifiers for variables should be written in camel case where the first word is lower case and every word after starts with a capital letter

3.2: Ints

One of the simplest examples of a variable is an integer. Integers are variables that can store whole numbers such as 1, 2, 3, and so on. They cannot store numbers containing decimal places. They may be negative or positive. In Java, integers are declared using the keyword int followed by the variable identifier. You assign a value to an integer using an equal sign (assignment operator). The example below declares a variable with the identifier “x” and initializes its value to five.

//initialize variable x with value 5
int x = 5;

You don’t have to initialize the variable with a value immediately if you do not want to. You may also declare a variable and then initialize it later.

//declare variable
int x;
//initialize variable
x = 5;

Note above that we do not use the keyword int again when we assign x a value of 5. We only use the keyword int the first time we are declaring the variable.

Printing Ints

You may print int variables using the different print methods we learned about in the last chapter. Here’s an example that prints out the value of x:

//declare and initialize variable
int x = 5;
//print out the value of x using println method

If you would like, follow along and try typing the code above into the main method of a Java project in your IDE. You can create a new project or replace the main method of your HelloWorld project. You should type it yourself and not copy-paste it – to get in the practice of typing your own code. The output should look as follows:


3.3: Basic Arithmetic Operations

It is possible to perform simple mathematical operations on integers without using special methods imported from the Java API. There are a total of seven basic arithmetic operators in Java. Operators are symbols that allow us to use mathematical expressions in Java. The table below displays all seven operators.

Name Operator Mathematical Example
Addition + 3+3=6
Subtraction - 5-1=4
Division / 4/2=2
Modulus (remainder) % 5%2=1
Multiplication * 10*10=100
Increment 1 ++ 10++ = 11
Decrement 1 -- 10-- = 9

Now let’s take a look at these operators in code.

What will the output of the following code be?

int x = 5;
x = x + 5;
System.out.print("The value of x is: ");

In the first line, we declare a variable of type integer with the initial value of 5. In the second line, we take variable x (on the left) and set it equal to itself plus five. So x is now equal to ten. The third and fourth lines print out:

The value of x is: 10

Again, you should be trying this out yourself in your IDE.

Now that we’ve seen the addition operator in use, let’s take a look at all the other ones. They’re all used in a similar manner.

3.3b: Operations
public class Main {
    public static void main(String[] args) {
        //Addition Example
        int x = 5; //Create the variable x and set it to 5
        x = x + 5; //add 5 to x, then store in x for a value of 10
        //Display the results
        System.out.println("Addition: x + 5 =");
        //Subtraction Example
        int y = 10; //Create the variable y and set it to 10
        y = y - 5; //Subtract 5 from y and store result in y for value of 5
        //Display the results
        System.out.println("Subtraction: y - 5 =");
        //Multiplication Example
        int z = 10; //Create the variable z and set it to 10
        z = z * 10; //Multiply z by 10 and store the result in z for value of 100
        //Display the results
        System.out.println("Multiplication: z * 10 = ");
        //Division Example
        int a = 100; //Create the variable a and set it to 100
        a = a / 10; //Divide a by 10, store result in a for value of 10
        //Display the results
        System.out.println("Division: a / 10 =");
        //Remainder Example (Modulus)
        int b = 100; //Create the variable b and set it to 100
        b = b % 10; //Find the remainder of b divided by 10 for value of 0
        //Display the results
        System.out.println("Remainder: b % 10 =");
Addition: x + 5 =
Subtraction: y - 5 =
Multiplication: z * 10 = 
Division: a / 10 =
Remainder: b % 10 =

Process finished with exit code 0

You’ve probably already seen all the above operators before. The only one you may not be familiar is the modulus % operator. The modulus operator is used to determine the remainder when you divide two numbers. So for example, if you take 12 and divide it by 5, the answer is 2 with a remainder of 2. The operation 12 % 5 will give you that remainder of two as the answer.

3.3c: Remainders
public static void main(String[] args) {
    //What does modulus do?
    int x = 12 % 2;
    System.out.print("The remainder is: ");
The remainder is: 2

In addition to being able to perform operations with numbers, we can also do operations with the variables themselves. We can take two variables and add them together, divide them, subtract them, whatever. We can add five variables together if we want. The example below takes three variables and adds them all together in a variable called sum:

3.3d: Adding Variables Together
//declare/initialize variables
int a = 1;
int b = 2;
int c = 3;
//add them all together
int sum = a + b + c;
//print out result
System.out.print("a + b + c = ");
a + b + c = 6

Note how we could add a, b, and c together at the same time we were declaring and initializing the variable sum. We could have done this across multiple lines, but it was simpler to do it all in one statement.

Finally, let’s look at the increment and decrement operators. These increase the value or decrease the value by one.

3.3e: Increment/Decrement
//declare variable
int x;
//give x value of 10
x = 10;
//increment by one
//print result

The above code prints out 11 because the ++ operator increased the value of x by 1.


The code below would decrease the value of x by 1:

int x = 10;

Shorthand Operators

Java provides us with useful shortcuts to doing arithmetic. These shorthand operators allow you to type less and produce the same code. The table below shows these operations:

Name Definition Operator Example Equivalence
Addition Adds whatever follows the operator to the preceding variable += x += 5;x += y; x = x + 5;x = x + y;
Subtraction Subtract whatever follows the operator from the preceding variable -= x -= 5;x -= y; x = x – 5;x = x – y;
Multiplication Multiply the variable by whatever follows the operator *= x *= 5;x *=y; x = x * 5;x = x * y;
Division Divide the variable by whatever follows the operator /= x /= 5;x /= y; x = x / 5;x = x / y;

Sample Code: Take the variable x and add ten to it, then subtract y from x and print the result.

3.3g: Using Shorthand
int x = 10;
int y = 5;
x += 10;
x -= y;

The resulting output of the above code would be 15. It takes an x value of 10 and adds 10 to it for a sum of 20, then subtracts the y value of 5 from 20 for a result of 15.

3.4: Order of Operations (Precedence)

It is possible to perform multiple arithmetic operations with a single statement, as is shown below:

int answer = 5+3*2;

The output of the code is 11 because Java follows operator precedence, which is just a fancy term for order of operations. Just like in third grade math class where you are taught to do multiplication and division before addition and subtraction, Java has an order of operations. You may have heard of the acronym PEMDAS (Please Excuse My Dear Aunt Sally) which stands for (Parenthesis, Exponents, Multiplication, Division, Addition, and Subtraction). Java largely functions in the same way, with the exception of exponents, because there is no built-in exponentiation operator in Java. It will evaluate expressions from the left to the right, processing anything in parenthesis first, followed by multiplication and division, and then finally addition and subtraction. So in the above example, it multiplied 3 by 2 for a total of 6, then added 5 for a result of 11.

We can use parenthesis to group terms together if we want to change the order of operations. For example, if we want to add before we multiply, we could do something like this:

int answer = (5+3)*2;

In the example above the value of x would be 16, because 5 and 3 are added together in the parenthesis first for a sum of 8, and then that 8 is multiplied by 2 for a total of 16.

3.5: Algebraic Examples

Now that you know the basics of how to do arithmetic, let's look at some slightly more advanced examples. We'll be taking algebraic expressions and turning them into Java using the operators we've learned about.

Consider the slope intercept formula, \(y=mx+b\) How would you write this in Java?

//In Java, this would be written as:
y = m * x + b;

Keep in mind if you are trying this out yourself, you will have to declare/initialize all the variables being used.

Now let's take something slightly more advanced, say we want to calculate the average or mean of four numbers:

\(mean=\frac{a + b + c + d}{4}\)

//In Java, this would be written as:
mean = (a + b + c + d)/4;

Now, let's look at the standard form for a quadratic equation/parabola:


We need to be a bit more thoughtful with this one. Remember that there's no exponentiation operator in Java. So we'll have to multiply x by x to get the result for \(x^2\).

//In Java, this would be written as:
y = a * x * x + b * x + c;

Finally, let's look at a more complex example:


//In Java, this would be written as:
result = (a*a*a*2*b+7*(c-4))/(2*c-4*a*a);

Note that we always need to use an operator to tell Java exactly what we want to do. In algebra, we know \(2a\) means \(2*a\). In Java, we must always write 2 * a. If we wrote result = 2a in Java it would error out. Additionally in Algebra we know parenthesis next to something means multiply. For example, \(y=(x)(2)\) would be equivalent to \(y=x*2\) in Algebra. In Java, we cannot do y = (x)(2). It would have to be y = (x)*(2) or y = x*2, as the parenthesis are useless in this case.

3.6: Basic String Operations

As mentioned in the last chapter, Strings are sequences of characters enclosed between a set of quotation marks. We can use Strings as a format for our variables. So just as you can create integers to represent numbers, you can create strings to represent text. The keyword in Java to declare a variable as a string is String. Remember, capitalization matters. int is lower case, String is capitalized.

The example below creates a new string variable with the message “Hello, World.” and prints it to the screen.

//Create String
String message = "Hello, World.";
//Print string using println method
Hello, World.

In Java, it’s possible to add two strings together using the addition operator, just like we did for integers. Except in the case of Strings, it takes two and combines them into one. This is known as concatenation of strings, which is when we’re appending one string to the end of another. The example below takes three strings and combines them into a fourth, before printing them to the screen.

public class CombineStrings{
   public static void main(String[] args){
       //create 3 strings
       String partA = "Java is an ";
       String partB = "Object Oriented Programming Language ";
       String partC = "because it uses objects.";
       //combine them
       String combined = partA + partB + partC;
       //print result

The above code outputs:

Java is an Object Oriented Programming Language because it uses objects.

You can also combine strings when you are printing them out. The example below prints multiple variables out at once:

int x = 5;
int y = 7;
int z = 22;
System.out.println("The value of x is " + x + ", y is " + y + " and z is " + z + ".");
The value of x is 5, y is 7 and z is 22.

3.7: Printing Formatted Data

Now we’re going to discuss the printf method mentioned in the last chapter in greater detail. The f in printf stands for formatted data. Java has a series of format specifiers which are placeholders for values of variables. Format specifiers begin with a percent symbol % and end with what’s known as a converter. To print variables within strings we simply add format specifiers (corresponding to the data type we want to look at) into our string message followed by arguments containing the variables. This will make more sense once you see it in action. Look at the sample code below. The format specifier for an integer is %d.

int i = 10;
System.out.printf("The value of i is %d.", i);

The above code outputs:

The value of i is 10.

Essentially the %d was replaced with the value of i. Only the printf method can do this – this will not work with the print or println methods. Note the comma between the end of our string in quotes and the variable i. We are passing arguments to the printf method – the first argument is the string containing our message, and the second argument is the variable i. Arguments are always separated using commas.

The code below prints out the values of two variables at once:

3.7a: Formatted Printing
int a = 1;
int b = 2;
int c = 3;
System.out.printf("a is %d, b is %d, and c is %d.", a, b, c);
a is 1, b is 2, and c is 3.

What about other types of data? What about a String? Strings have a format specifier as well – it is %s.

String name = "Bob";
String job = "Burger Chef";
String location = "Bob's Burgers";
System.out.printf("%s is a %s at %s", name, job, location);
Bob is a Burger Chef at Bob's Burgers

Escape Sequences

When using the print methods and working with strings there will be times when you need to insert characters or text elements that you can’t usually insert due to the restrictions of the Java language. What if you want a String to contain quotes within it – but you can’t because Strings are made using the quotation marks. This is what escape sequences are for. Escape sequences are special sequences of characters that enable us to print out other reserved characters. Each escape sequence begins with a backslash. Below is a list of some key escape sequences:

  • \t – insert tab
  • \n – insert new line
  • \’ – insert a single quotation mark
  • \” – insert double quotes

As an example, the following single line of code prints out a message with one word per line.


3.8: Primitive Data Types

Primitive data types are built-in elements of Java that allow us to store data. They’re different types of variables with different purposes. Integers are one example of a primitive data type – but there are seven more. They’re called “primitive” because they’re the basic data types we use to create all variables in Java. The table below outlines each type and its purpose.

Datatype Keyword Min/Max Value Description
Byte byte -128 / 127 Used to store whole numbers. Smaller than an integer. 8 bit. Useful only when working with small numbers between -128 and 127.
Short short -32,768 / 32,767 Used to store larger whole numbers – 16 bit – smaller than an int but larger than a byte.
Integer int -(2^31) / (2^31)-1 Used to store larger whole numbers – 32 bit.
Long long -(2^63) / (2^63)-1 Used to store even larger whole numbers than integers can support – 64 bit.
Float float Out of scope Used to store numbers including decimals, 32 bit. Should not be used to store currency due to rounding inconsistencies. Must end value with f when being initialized. Up to 6-7 digits of precision.
Double double Out of scope Used to store numbers including decimals. 64 bit. Takes up double the memory of a float. Should not be used to store currency due to rounding inconsistencies. Up to 14-15 digits of precision.
Boolean boolean True or False A simple data type that can only be true or false
Character char 0/65,535 Represents a 16 bit Unicode character. You may simply enter a character rather than the actual number representing the character.

The first four primitive data types in the table above are all used to store whole value negative and positive numbers. The ones you use simply depend on how large of a number you’re planning on storing. You should use the smallest data type possible for whatever you’re working with. This is a good practice because it will conserve the user’s computer memory (RAM). For example, if you’re creating a program that only deals with the whole numbers 1 through 100, you should be using a byte, not an integer. If you use larger data types than you need, the system will reserve memory that never gets used.

3.8b: Primitive Declaration Examples
//Example initializing different data types
byte myByte = 100;
short myShort = 10000;
int myInt = 100000;
long myLong = 1000000;
float myFloat = 10.25f;
double myDouble = 143.432;
boolean myBool = true;
char myChar = 'a';

The only strange thing in the above code is the f behind the 10.25 in the myFloat variable. If you set myFloat to 10.25 and not 10.25f – it will error out. That f is very much intentional.

By default, any time you use a decimal point Java will think you are creating a double. It will error out when you set a float equal to a double because they’re two different things, and you can’t fit a double in a float. You must put an f after the number in order to tell Java that this is in fact a float number – not a double. When we put an f after the number, it is said we are casting it to a float. We will learn more about type casting later, but for now, just remember if you’re using floats – you must end the number with an f.

3.9: Floats and Doubles

Floats and Doubles are the primitive data types responsible for handling numbers with decimal places.

The example below multiplies two floats together:

3.9a: Floats Example
float myFirstFloat = 12.32f;
float mySecondFloat = 2f;
float product = myFirstFloat * mySecondFloat;
System.out.printf("The product is %f", product);
The product is 24.639999

Let’s take a look at a more advanced example that calculates the area of a circle using doubles. The formula for the area of a circle is: \(Area=\pi * radius^2\)

Note that we can use Math.PI to get the value of \(\pi\). The format specifier for floats and doubles in the printf method is %f. Since we are using doubles in this example, there is no need to place an f after the number.

3.9b: Circle Area with Doubles
public class Main {
    public static void main(String[] args) {
        //Initialize Variables
        double radius = 1.5;
        //Calculate area (pi*r*r)
        double circleArea = Math.PI*radius*radius;
        //Print it
        System.out.printf("Area of a circle with radius of %f units is %f units squared.", radius, circleArea);
Area of a circle with radius of 1.500000 units is 7.068583 units squared.

The above program created a double with a radius of 1.5. It then set another double circleArea to the value of that radius multiplied by itself (radius squared) and pi. Once we found the circleArea, we printed out the results with the printf method.

As you can see, the double is displayed with six decimal places (millionths) by default. We can optionally declare the level of precision we want in our format specifiers. The number of decimal places we want is placed in the middle of the format specifier. For example, if we want to only show two decimal places, %f becomes %.2f

//Print results to 2 decimal places
System.out.printf("Area of a circle with radius of %.2f units is %.2f units squared.", radius, circleArea);
Area of a circle with radius of 1.50 units is 7.07 units squared.

Note that 7.068583 was rounded up to 7.07.

A Note On Currency/Money

When working with currency values, we should not use doubles or floats. If you noticed in example 3.9a, the answer isn't actually correct. It's very close, but still not correct. There's a rounding issue going on. We will learn about another class called BigDecimal in chapter 5, which is used to handle currency operations. While it might be a problem on a small scale, if we run our applications on a large scale these rounding issues could amount to lots of money going missing. One cent missing from a few million accounts is a lot of money. So remember, don't use floats or doubles for very sensitive or important calculations.

3.10: Booleans

Booleans are a very simple primitive data type that can only have a value of true or false.

boolean thisIsFalse = false;
boolean thisIsTrue = true;
System.out.println("thisIsFalse: " + thisIsFalse);
System.out.println("thisIsTrue: " + thisIsTrue);
thisIsFalse: false
thisIsTrue: true

3.11: Characters

Characters are used to represent 16 bit Unicode characters (letters, numbers, symbols, etc.). They only store a single character – unlike a String which can store entire sentences.

char a = 'a';
char b = 'b';
System.out.println("Character a is: " + a);
System.out.println("Character b is: " + b);
Character a is: a
Character b is: b

3.12: Importing the Scanner for User Input

So far all of our sample programs have calculated things based on hard-coded numbers stored in the source code. We can’t expect the people using our software to have to edit the source code every time they want to perform a new calculation. Instead, we want the programs to ask the user what numbers to use in calculations. We can do this through the use of Scanners.

The Scanner is a class in the Java API which allows us to scan the input stream to determine what the user is typing on their keyboard. We can then store what they type in variables and perform computations based on their input.

The Scanner class must be imported from the Java API. Import statements are statements placed towards the top of our class files (after package declarations) in order to use objects from the Java API in our classes.

The import statement for a Scanner looks like this:

//package statements first
package com.kevinsguides.javademos;
//import statements after package
import java.util.Scanner;
//main class and method
public class Main {
    public static void main(String[] args){
    //Todo: Create a scanner and make it do something

3.13: Using the Scanner

Now that we have imported the scanner class we can begin using it. Just like we had to declare and initialize variables for primitive data types – we have to do something similar with objects before we can use them. We’ll have to create a Scanner object for our program to use. The format is:

ObjectType objectName = new ObjectType(Arguments);

In the case of our Scanner, we’re using the object type “Scanner.” We can give the Scanner any identifier we want (so long as it’s not a keyword). It should be written in camel case. For the argument of the Scanner, we’re going to use the object. is the standard input stream where we can see what the user is typing on their keyboard. It’s essentially the opposite of the System.out stream we’ve been using so far.

Creating a new scanner would look like this:

Scanner userInputScanner = new Scanner(;

So this is telling Java to create a new Scanner called “userInputScanner” and instantiate it as a new Scanner using the System input stream. For our purposes, instantiate means to initialize an object. Objects are instantiated, and variables are initialized. Either way, memory is being set aside for the object or variable.

In this situation, "userInputScanner" is an instance of a Scanner. That is, it's a variable being defined as an instance of another class. We call these instance variables when they represent some other type of object defined by a class in Java. You will hear the terminology instance quite often in programmer lingo - it basically means the same thing as Object. An instance is an Object and in this case that object is a Scanner. Hopefully that makes sense.

If you really wanted, you could create two Scanners. They would both be considered instances of Scanners.

Scanner aScanner = new Scanner(;
Scanner anotherScanner = new Scanner(;

You won't need to use two different Scanners using the input stream at the same time, as there's only one input stream. But in the above example, aScanner and anotherScanner are both instances of Scanner.

Now that we have a Scanner imported and instantiated, we can start using it in our code to figure out what the user is typing! The sample code below asks the user to type their name and simply repeats it back to them. We will use the Scanner’s nextLine() method to determine what String of text the user has typed.

//import the Scanner to our file so we can use it
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        //Create new scanner of
        Scanner userInputScanner = new Scanner(;
        //Ask the user to type their name
        System.out.println("What is your name?");
        //Store the result in a String
        String userName = userInputScanner.nextLine();
        //Print the result
        System.out.println("Hello, " + userName + ".");
        //Close scanner
What is your name?
Hello, Kevin.

When we call the nextLine() method on a Scanner it pauses the program until the user types a response and presses enter.

Note that after we are done using the scanner we close it using the .close() method. This is so we’re not wasting computer resources monitoring the input stream when we’re done using it.

Other useful Scanner methods include nextDouble() and nextInt() which will get the next entered number or int. The example below shows these methods in use.

//Create new scanner of
Scanner userInputScanner = new Scanner(;
//Ask for an integer
 System.out.println("Type an integer:");
int myInt = userInputScanner.nextInt();
//Ask for a double
System.out.println("Type a double:");
double myDouble = userInputScanner.nextDouble();
//Print results
System.out.printf("You typed %d for the int and %f for the double.", myInt, myDouble);
//Close scanner
Type an integer:
Type a double:
You typed 10 for the int and 10.100000 for the double.

Area of a Circle Program

Let’s change the example program from earlier in this chapter, which calculated the area of a circle based on its radius. I’d encourage you to try this yourself before looking at the source code below.

Instructions: Create a program that calculates the area of a circle. It should ask the user to enter a value, store that value as a double in variable radius with a Scanner. Then it should calculate the area and print the result to the screen with two decimal places. Remember to use the right import statement.

Recall that \(\pi\) can be found with Math.PI

Program should look like this when executed:

Please enter circle radius: 
A circle with radius 15.00 will have an area of 706.86 units squared.
the formula for the area of a circle shown in a diagram
//import the Scanner to our file so we can use it
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        //Create a scanner
        Scanner userInput = new Scanner(;
        //Ask for radius
        System.out.println("Please enter circle radius: ");
        //Store result in double
        double circleRadius = userInput.nextDouble();
        //Calculate result
        double result = Math.PI * circleRadius * circleRadius;
        //Print result
        System.out.printf("A circle with radius %.2f will have an area of %.2f units squared.", circleRadius, result);

Assignment 3 – Basic Calculator

Your assignment is to create a basic calculator that asks the user to enter two values and finds the sum, difference, product, and quotient of the two numbers. It should then print out these results to the console. Remember to close your scanner. Round to two decimal places.

Suggested Steps:

  • Create a new console project called BasicCalculator in your IDE.
  • Import the Scanner object
  • Instantiate a Scanner with the System input stream
  • Print a message saying “Enter first value: “
  • Save the next double they enter using a scanner
  • Repeat for the second value
  • Remember to close the Scanner when you are done using it
  • Create variables of type double for sum, difference, product, and quotient
  • Use arithmetic operators to find these values and save them in the respective variable
  • Print the results to the screen using whatever type of print method you want

How it should look:

When you are done, the console output from running the program should look similar to below:

Welcome to Basic Calculator
Enter first value:
Enter second value:

Calculating results...
Sum: 10.00 + 5.00 = 15.00
Difference: 10.00 - 5.00 = 5.00
Product: 10.00 * 5.00 = 50.00
Quotient: 10.00 / 5.00 = 2.00

  • Review your code for syntax errors, improperly spelled object/variable names, missing semicolons, brackets, etc.
  • Pay attention to the debugger message (if there is one) – it should tell you what line the error happened on.
  • Make sure you’ve created all objects with the proper arguments, initialized all variables, etc.
  • Make sure you’re using the correct data types for the operation and correct methods for the Scanner
  • If you really can’t figure it out, compare your code to my solution. Note that there are multiple ways you could do this – you could achieve the same output in more or fewer lines depending on how you want to do it.

//import the Scanner 
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Basic Calculator");
        //Create Scanner
        Scanner userInput = new Scanner(;
        //Ask use to type first value
        System.out.println("Enter first value:");
        double x = userInput.nextDouble();
        //Ask use to type second value
        System.out.println("Enter second value:");
        double y = userInput.nextDouble();
        //Close Scanner
        //Calculate results
        System.out.println("\nCalculating results...");
        double sum = x + y;
        System.out.printf("Sum: %.2f + %.2f = %.2f\n", x, y, sum);
        double difference = x - y;
        System.out.printf("Difference: %.2f - %.2f = %.2f\n", x, y, difference);
        double product = x * y;
        System.out.printf("Product: %.2f * %.2f = %.2f\n", x, y, product);
        double quotient = x / y;
        System.out.printf("Quotient: %.2f / %.2f = %.2f\n", x, y, quotient);

Challenge: Can you achieve the same result in fewer statements than my above example?

You can shorten the calculations. You can actually replace the “sum” variables in the printf arguments with the mathematical expressions shown below:

//import the Scanner
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Basic Calculator");
        //Create Scanner
        Scanner userInput = new Scanner(;
        //Ask use to type first value
        System.out.println("Enter first value:");
        double x = userInput.nextDouble();
        //Ask use to type second value
        System.out.println("Enter second value:");
        double y = userInput.nextDouble();
        //Close Scanner
        //Calculate results one line at a time
        System.out.printf("\nCalculating results...\nSum: %.2f + %.2f = %.2f\n", x, y, x+y);
        System.out.printf("Difference: %.2f - %.2f = %.2f\n", x, y, x-y);
        System.out.printf("Product: %.2f * %.2f = %.2f\n", x, y, x*y);
        System.out.printf("Quotient: %.2f / %.2f = %.2f\n", x, y, x/y);

This shortens the code by 4 lines because we don’t need to declare or initialize the sum, difference, product, or quotient variables.

We can take this a step further and do all the printing and calculations in one line – though this is kind of ugly. I’d prefer the above method to this:

//Calculate all results in one statement
        System.out.printf("\nCalculating results...\nSum: %.2f + %.2f = %.2f\nDifference: %.2f - %.2f = %.2f\nProduct: %.2f * %.2f = %.2f\nQuotient: %.2f / %.2f = %.2f\n", x, y, x+y, x, y, x-y, x, y, x*y, x, y, x/y);


This concludes this chapter on variables and Scanners. In the next chapter, we will learn about decision making in Java. Take the review quiz or proceed to the next chapter.

Be the first to comment on “Chapter 3: Variables, Scanners & Strings"

Login to post a comment

Related Guides

Chapter 4: Decision Making with Control Statements
You will learn how to use control statements (If/Else/Switches) to make decisions in Java. You'll also learn about the equals method and build a tax calculator.
Chapter 1: Introduction to Java
This section discusses key components of computers and how the Java programming language works. You will also learn about the tools developers use to code.
Chapter 2: Hello, World.
This section introduces you to the IntelliJ IDE and your first Java project, which is called "Hello, World."
Chapter 5: BigDecimals, Mutability & Basic Memory Concepts
This chapter discusses how to use BigDecimals to perform precise calculations, along with an introduction to mutability and how the JVM handles memory.
Chapter 6: Methods
This chapter discusses how to create your own methods, void methods, and return methods. You will also learn a little bit about scope.
Chapter 7: Loops
Learn how to use different loops in order to do repetitive tasks. The seventh free chapter of KG's Intro to Java series.
Main Menu
Kevin's Guides
Full size image will appear here.