Lecture 2 - Wikispaces

Lecture 2
VARIABLES, PRINTING AND IF-STATEMENTS
Variables
Variables are containers for different values.
In a program, the programmer has to
create(instantiate) these variables.
To Initialize variables:
DataType identifier [= Expression]
Data Type: What can this box hold?
Identifier (Name): What’s the name of this box?
integers
Expression: What do you want to do with this
box? (Often you will put something in it.)
The whole things is called a statement.
Statements are instructions for the computer.
Statements end with a semicolon (;)
AgeOfBaby
Data Types – Primitive Types
Integer (int)

Holds integers; whole numbers
Double (double)

Holds numbers with decimal points.
Boolean (bool)

Holds true of false
String (String)

Holds words/sentences. Denoted via double quotes (“ ”)
Quick Practice
“Hello World”
int ageOfBaby = 3;
String
integers
AgeOfBaby
Note:
Semicolon
greetMsg
String greetMsg =
“Hello World”;
Literals

Literals are the “thing” you can put into variables
Literals
“Hello World”
int ageOfBaby = 3;
integers
AgeOfBaby
String
greetMsg
String greetMsg =
“Hello World”;
Naming Variables
The name of a variable adheres to a strict set of rules:

All variable names must begin with a letter of the alphabet, an
underscore, or ( _ ), or a dollar sign ($)

After the first initial letter, variable names may also contain letters and the
digits 0 to 9. No spaces or special characters are allowed
(periods or dashes).

You cannot use a java keyword (reserved word) for a variable name.


if, else, true, false are examples of reserved words
Optional (But Good Practice): use camelCaseForNamingVariables
Naming Variables
The name of a variable adheres to a strict set of rules:

Java is case-sensitive. Different variable names should represent different
objects


Log, log, LOG are different variables
You cannot create multiple objects with the same name
int x = 3;
int x = 5;
int x = 3;
String x = "Hello";
BAD
Displaying Information to User

Printing to the user requires 1 line of code:


To print “Hello World”:



System.out.println(<Things to print go here>);
System.out.println(“Hello World”);
What happens in this code?

String greeting = “Hello Dave”;

System.out.println(greeting);
Turns out, you can print almost anything. The exceptions will be discussed
when we get to them.
Statements

A statements is the smallest instruction that can be carried out. Statements
end with a semicolon ‘ ; ’

What does it mean by smallest instruction?

Big instruction


Put on your clothes
Smaller instructions

Put on shirt

Put on pants

Put on socks

Etc.
Write the Hello World Program in
IntelliJ
Tricks with assigning numbers to
variables
What happens when we…


1. Put a double literal in an integer variable?

int numberOfPencils = 12.5;

Truncating or Not allowed (language dependent)
2. Put an integer literal in a double variable?

double height = 65;
Arithmetic Operators
Operator
Meaning
Example
+
Addition
X + 3
-
Subtraction
X – 3
/
Division
9 / x
*
Multiplication
5 * 6
%
Modulus
Remainder
Tricky Arithmetic with Variables
1
Add two
integers
2
Add two
doubles
3
4
Add
integer and
double
Add
integer and
String
Casting Numbers

Store a double in an integer: Truncate


Store an in in a double: Decimal point gets added


Lose data
Safe
Changing an objects type from one to another is called casting.

double cost = 12.5;

int numDollars = (int) cost;
Cast the “cost” to an
“int” using parenthesis.
If - Statements

Allows us to execute different code based on different conditions

Am I allowed to drive?

Am I in preschool, elementary, high school or college?
if (<condition is true>) {
//do something with this code inside the brackets
}

Code inside the brackets will run if the condition is true.

“if” must be lowercase. “If” is incorrect.
If - Statements

The code within the parenthesis ‘( )’ of the if statement must evaluate to
true of false
int age = 10;
if (age >= 16){
System.out.println("You can drive");
}
boolean canDrive = true;
if (canDrive){
System.out.println("You can drive");
}
Boolean Expressions

You can Relational Operators to compare two primitive types to form
Boolean expressions

Boolean expression return true or false


ageToDrink == yourAge

heightToRideRollerCoaster <= yourHeight
When comparing Strings use “.equals()”, gives you true or false


yourName.equals(myName)
Conditions will usually look like one of the red pieces of code above.
Relational Operators
Operator
Meaning
Example
==
Equal to
if (x == 3)
!=
Not equal to
if (x != 3)
>
Greater than
if (salary > 10000)
<
Less than
if (salary < 10000)
>=
Greater than or equal to if (salary >= 10000)
<=
Less than or equal to
if (salary <= 10000)
If Statements – Multiple Conditions

You can put if statements within if statements
//Print message saying a person can ride a roller coaster if they
// are 4 feet tall AND over 10 years old.
int personHeight = 5;
int personAge = 10;
if (personHeight >= 4) {
if (personAge > 10) {
System.out.println("You can ride the roller coaster.");
}
}
Compound Boolean Expression

You can put multiple conditions in an if statement to form a Compound
Boolean expression

Compound Boolean expressions: Boolean expressions joined by logical
operators
//Print message saying a person can ride a roller coaster
// if they are 4 feet tall AND over 10 years old.
int personHeight = 15;
int personage = 30;
if (personHeight >= 4 && personage > 10){
System.out.println("You can ride the roller coaster.");
}
Compound Boolean Expression
Logical Operators
Operator
Meaning
Example
!
NOT
if (!found)
&&
AND
if (x < 3 &$ y > 4)
||
OR
if (age < 2 || height < 4)
If Else Statement

Like an if-statement but with a default action if none of the previous
conditions are met.
Print message saying a person can ride a roller coaster if they are 4 feet tall
AND over 10 years old. If they can’t ride, also print an apology message.
boolean personCanRide = false;
if(personCanRide){
System.out.println("You can ride");
} else {
System.out.println("You can't ride");
}
Else If Statements

Specifies a new condition if the condition above it is false.
Print message saying a person can ride a roller coaster if they are 4 feet tall
OR over 10 years old.
boolean personIsOver4FeetTall = true;
boolean personIsOver10YearsOld = true;
if (personIsOver4FeetTall) {
System.out.println("You can ride");
} else if (personIsOver10YearsOld){
System.out.println("You can ride");
} else {
System.out.println(“Sorry. You can't ride");
}
If Statement Block
The moment a condition is
true, the computer executes
the code for that condition
then exits the block.