Variablesclick here for complete presentation What are variablesThink 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 JavaString = Text data which is enclosed by double quotes " " "Hello" "Goodbye1" "12345" int = Integers are numbers wiithout decimals 123 double = Doubles are numbers with decimals 50.99 How to declare a variable formatTo declare a variable, follow this format. (data type) (variable name) = (value - optional) Setting the value of a variable is optional ExampleString 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 VariablesYou 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(fullIdName); output System.out.println("The id value is " + id); output Variable Expressions - Making CalculationsYou normally use numeric variables to make calculations. The + OperatorUse the + operator to add two ints together int a; double a; The - OperatorExactly like + except performs subtraction int a; double a; The * OperatorThe * operator performs multiplication int a; double a; The / OperatorThe / operator performs integer division Not the same as regular division int a; The % Operator for intThe % operator is the mod operator int a; ShortcutsSome expressions are used so often, Java gives us a short cut int x; CastingYou 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 RoundingIn Java, the conversion of a double into an int does not use rounding |
Data TypesCredit: A Slides are modified with permission from Barry Wittman at Elizabethtown College |
|