What are variables
Think of variables as a box you can put values into
Variables are place holders for data. Data comes in the form on whole numbers, decimals, text, and objects.
Data types in Java
String = Text data which is enclosed by double quotes " "
int = Integers are numbers wiithout decimals
double = Doubles are numbers with decimals
How to declare a variable format
To declare a variable, follow this format.
(data type) (variable name) = (value - optional)
Setting the value of a variable is optional
String name = "James"; //creates a string
int num1 = 9; //creates an integer
int num2; //creates an integer variable with no value
double num3= 9.78; //creates a double
Student joeObj = new Student(“Joe Schmo” , 16, 23432); //creates a new instance of a student class
Concat variables - Appending Variables
You can concat a variable to String by using the plus + operator. If you concat a number type (double or int) to a String, it makes the data a String.
String fname = "Joe"; // name is a String
String fullIdName = fname + "--" id + "--" + lname;
System.out.println("The id value is " + id);
Variable Expressions - Making Calculations
You normally use numeric variables to make calculations.
The + Operator
Use the + operator to add two ints together
The - Operator
Exactly like + except performs subtraction
The * Operator
The * operator performs multiplication
The / Operator
The / operator performs integer division
Not the same as regular division
The % Operator for int
The % operator is the mod operator
Some expressions are used so often, Java gives us a short cut
You cannot directly store a double value into an int variable
int a = 2.6; // fails!
However, you can cast the double value to convert it into an int
int a = (int)2.6; // succeeds! (a = 2)
Casting tells the compiler you want the loss of precision to happen
In Java, the conversion of a double into an int does not use rounding
Credit: A Slides are modified with permission from Barry Wittman at Elizabethtown College