COSC1046 - Chapter 2
COSC1046 - Chapter 2
There is also the char, which is the same size as a byte, and stores ASCII characters.
We use these data types with variables, and can assign their values like this:
int x = 10;
This creates a new space in memory that is the size of the int data type, and stores the value 10 in it.
int x = 10;
int y = 5;
x = y;
When naming your variables, you should make sure to name them something that makes sense, and is
easy to understand. Using variable names of x, y, or z should be avoided unless they make sense to use
in the situation.
Multi-word variables in Java are written in camelCase. This means that the first letter is always
lowercase, and the first letter of any other word is uppercase.
Ex.
int x = 3 + 4;
int y = 5*6;
int z = x + y;
You can have addition, subtraction, multiplication and division, exponents, and brackets. BEDMAS is
followed in all calculations
Exponents
Another if you want to adjust a variable by a certain amount you can use the following:
These are not necessary, but it can make code simpler and easier to read.
To read input from the user, we’ll be using an object that is called a Scanner. We need to import it
before we can use it. Type:
import java.util.Scanner;
Above your class so that you can access the Scanner object.
Creating a Scanner:
Input is the name that we’ve given our new Scanner, and we’ve assigned a new Scanner object to it-
you’ll learn more about objects later in the course, for now, just understand that’s how you make a
Scanner. The System.in part tells it we’re getting input from the console.
What the nextInt method that Scanners have does it wait until the user enters an input and accepts it as
an integer. Run your code and type a number in the console, press enter once you’re finished
What happens if you don’t give it an integer? What kind of error would that be?
Most of the time when getting input this way, we will print out a prompt before getting the input from
the user. Try:
Notice how we used System.out.print instead of System.out.println. This is because it is easier for the
user to understand what they are typing their input for if it’s on the same line as the prompt.
Name: Vishw Patel Student I’d(229689040) COSC1046 Lab 1
package welcometojava;
import java.util.Scanner;
System.out.print("Enter the fuel efficiency of the car in miles per gallon: ");
}
Name: Vishw Patel Student I’d(229689040) COSC1046 Lab 1