Introduction to Programming w/ Java – Week 2

Week 2 Agenda:

This week we’ll discuss two topics:

1. Variables – types (int, boolean, etc.). Presence - local and global

2. Basic flow and control statements (if/else, for loops)

Writing simple programs in Java, compiling with “javac”, and running with “java”

Topic 1 – Variables:

A variable is a way to store information. Variables must be declared and named, which allows the computer to dedicate some memory in which to store the information. In the old days, memory was expensive and needed to be conserved!

Variable Names:

Names are case-sensitive i.e. “Count” is not the same as “count”.

Letters, numbers, the underscore “_”, and the “$” can be used, but typically we stick with letters, use camelCase, and make our variable names very descriptive: ex: int yannisOvenTimer

Variables must be declared.

Variable Types:

int – integer, 32bits, minimum value of -231and a maximum value of 231-1

long – integer, 64bits, minimum value of -263and a maximum value of 263-1

short – integer, 16bits, values between -215and a maximum value of 215-1

byte – integer, 8bits, values between -27and a maximum value of 27-1

float – aka “floating point”, decimals, 32 bits of memory used to store it.

double – double precision floating point, decimals, 64 bits of memory used to store it.

boolean – two values, true or false

char – single 16 bit Unicode character

String - typically a collection of “char” variables together, but in Java strings are not a primitive data type, they are objects created w/ support from the class “java.lang.String”, and they are immutable –i.e. once created their value cannot be changed.

Assigning Variables Values vs. Evaluating Expressions

To assign a variable a value, we use the equal sign “=”.

int benHatSize = 14;

This is very different than evaluating an expression – in that case we use the double equal sign “==”:

if (benHatSize ==14) {

do some stuff;

}

Most other expression evaluation makes sense.

* multiply

/ divide

+ add – if numbers, concatenate if strings/char variables.

- subtract

>, < greater than, less than

Here are some neat ones you may never have seen:

!= is not equal to. == is equivalent to (equal to)

&& logic “and”, ex: if ( (benHatSize>10) && (benHatSize< 20) )

|| logical “or”, meaning if either condition is true the statement is true.

That should get you started for now!


Topic 2 – Basic Flow and Control Statements:

These statements are the means by which we provide decision making capability and instructions to our program. Through these, we can gather input and then make different things happen (objects move, provide output to user, etc.) Two examples we introduce today are:

if ( conditions ==true ) {

statements here;

} else {

more statements here;

}

for (initial value; comparison; change to value) {

statements here;

}

Now let’s see an example where we put it all together. In this example we declare several variables, one of each type – a character, an integer, a decimal (double), a boolean, and a String (which is actually an object - notice the keyword String is capitalized). Then the program runs through a “for loop” 5 times, each time displaying the count, the test grade, and then the letter grade. An “if statement” is used to make decisions to determine the output. We’ll construct it a piece at a time, compiling and running in between making each change.

Programming Pearl – Always start small, add just a few lines of code at a time, SAVE, then compile, run, and test. Making incremental changes w/ frequent saving and testing leads to many fewer errors and headaches!

Program 1, step 1: yanniGrades1.java

-----------------

public class yanniGrades1 {

public static void main(String args[]) {

boolean booleanVariable = true;

String StringObject = "Let's Look at Yanni's Grading Scale: \n";

if (booleanVariable == true) {

System.out.println(StringObject);

}

}

}

------------------------

Does this work? If so, let’s go onto Step 2. Remember to SAVE between each test (compiling and running).

Also – notice that we are now creating a new file – called yanniGrades2.java, so you will have to do a “Save As” and give your original file a new name before going on. Also, notice that we have changed the name of the class to “yanniGrades2”. With java programs, our file name must match our class name or you will get an error!. In step 2 we’ll add more variables and a for loop – note the new lines of code are highlighted in bold.

Program 1 – step 2: yanniGrades2.java

-----------------

public class yanniGrades2 {

public static void main(String args[]) {

int intVariable = 1;

boolean booleanVariable = true;

String StringObject = "Let's Look at Yanni's Grading Scale: \n";

if (booleanVariable == true) {

System.out.println(StringObject);

for (intVariable =1; intVariable <=5; intVariable++) {

System.out.println("Example "+intVariable+": “);

}

StringObject = "Now it is time to play Minecraft.";

System.out.println(StringObject);

}

}

}

------------------------

This should output your starting String, then “Example 1:” through “Example 5:”, and then the closing String. Once this works, let’ proceed to the final version – again new code is bold. Notice here we add more variables and an if/else loop to make decisions about each output. Remember, first to a “Save As” to the new filename, and also change your class name in the first line of our program!

Program 1 final version: yanniGrades.java

-----------------

public class yanniGrades {

public static void main(String args[]) {

char charVariable = 'A';

int intVariable = 1;

double doubleVariable = 80.0;

boolean booleanVariable = true;

String StringObject = "Let's Look at Yanni's Grading Scale: \n";

if (booleanVariable == true) {

System.out.println(StringObject);

for (intVariable =1; intVariable <=5; intVariable++) {

System.out.println("Example "+intVariable+": If Yanni scores a " + doubleVariable);

if (doubleVariable <90) {

charVariable = 'F';

System.out.println("Yanni's grade would be an "+charVariable+ ".\n");

} else if (doubleVariable >= 90 && doubleVariable <= 100.0) {

charVariable = 'A';

System.out.println("Yanni's grade would be an "+charVariable+ "! Good job Yanni!\n");

} else if (doubleVariable > 100) {

System.out.println(“Yanni must be one smart dude!\n”);

}

doubleVariable = doubleVariable + 10.0;

}

StringObject = "Now it is time to play Minecraft.";

System.out.println(StringObject);

}

}

}

------------------------

Does this work? Great!

Challenge #1 – Now see if you can add three more “else if” branches to make a real grading scale – meaning:

>= 80 && <90 is a “B”. >=70 && <80 is a “C” >=60 && <70 is a “D” and you’ll need to change the first if statement to make <60 an “F”. You will also need to change the staring value of your doubleVariable to a 50 and change to for loop to run 7 times instead of 5, to show the grades every 10 steps.

Did you get this working? Excellent!

Challenge #2 - Now feel free to make some changes to see how these logic statements work. Or add/change some variable names. Finally, if you’d like, feel free to experiment with two other Java statements – first try to use while versus do-while.

while (expression==true){

// your code goes here

}

do {

statement(s)

} while (expression==true);

Do you see the difference? In the while loop, the condition evaluates before the loop runs. In the do-while loop it evaluates after the loop runs each time.