130 likes | 224 Vues
Dive into the world of Java programming with a whimsical tale of variables. Learn about different variable types, declaration, assignment statements, and more to master the basics of programming variables. Get ready to grasp the core concepts through an engaging narrative!
E N D
intX intY char c double d A Tale of 4 Variables
Once upon a time… • There was a program • And in that program there were methods • A click method • And the • main method public void click() public static void main()
intX intY And in the methods… There were variables • And the variables were declared • Creating space in memory to hold information public void click() { int intX; int intY; This is a declaration -> • But the variables were empty • There was nobody home.
And different kinds of variables hold different kinds of information • Are you happy? • That’s true or false • boolean • What’s your middle initial? • That’s a single letter • char • How far away do you live? • That’s a number, it could include a fraction or decimal • double These are different types of variables
intX intY And the assignment statementwas executed • And it gave values to the variables • intX = 8; • intY = 5; 8 5 These are assignment statements
Just be sure to declare the right kind of variable to hold the right kind of information • Which ones are correct types? • int distance = 45.5; • boolean happy = false; • char initial = “Tom”; • double distance = “far away”; • char letterGrade = ‘A’; • boolean b = “true”; This is also called a floating point value, it has a decimal point. An integer does not. These assignment statements initialize and declare the variables
Of course, assignment is not the same as equals No number can equal itself plus 3 • intX = intX + 3; • The algebra teacher said • The computer teacher said = means Always do the equation on the right first, then assign the result to the variable on the left
intX intX This is a literal value, it’s the same every time the program runs, intX is a variable, it can change So… intX = intX + 3 • Means… • First take the value of intX • Add 3 • Store the result in intX 8 8 + 3 11 =11
And the students were happy • Because they understood
intX intX intY And the students could assign values to variables • They knew that after the assignment statement • intX = intY + intX * 2 • intX = 5 11 27
intY So whenever you want to remember information in a program • Or if you want to leave a fill-in-the-blank space to be filled in later (like a Mad Lib) • Use a variable to store the information 5
Rules for making up your own variable names: • Must start with a letter • Can use numbers, letters and underscores (_) • Cannot use a work that already has a special meaning in Java like: • main • void • system
length println happyCamper best friend ready? good4u 2many tax_amount total! b45 Which identifiers do NOT follow the rules for Java variables? Identifiers must follow the rules