This is to get everyone on the same page with Java. We assume that you are familiar with a modern programming language coming into the course, so we will run through these exercises with that assumption. (Aka this will be a very fast introduction.) If you are already familiar with Java, run through these anyway. You’ll just get through it nice and quick.
Now click the green “play” or “run” button on the toolbar.
You can connect strings and other types by using the concatenation operator, the ‘+’, so you can do stuff like System.out.println(“My name is ” + “Ben”);
Java is an object-oriented language, so almost everything is an Object, but there are a few basic types we call primitives. These are
int — a 4 byte integer object (Of course, for 1, 2, or 8 byte integers we can use byte, short, or long, respectively)
double — an 8 byte decimal (A double precision floating point number, as opposed to the single precision float)
boolean — a boolean value (Either true or false)
char — a single character (If you’ve used other languages like C++, you may be used to using
ASCII. However, Java characters are actually Unicode characters. You can still do character arithmetic like myChar-’a’, but just keep in mind that using
ASCII will not work.)
In Java, declaration is one step, and initialization and instantiation is a separate step. For example, you can declare an int as “int myInt;” This will declare an integer. For primitive, they all have a default value of either 0, the zero unicode character, or false. However, this is bad programming style. Programming is just as much about making your code clean and easy to read as it is doing something correctly. To explicitly initialize a variable, just use the ‘=’ operator, as in “myInt = 42;” You can do declaration and initialization in one step by doing “int myInt = 1764;”
The basic operators are available– +, -, /, *, and %. The / operator is a truncating division (often called integer division), which means if you divide two integers, it will just round down. The % is the remainder operator (essentially modulo, but technically just a tad different). It will essentially give you the positive remainder after you divide two numbers.
There’re also the shorthands +=, -=, *=, and /=, as well as ++ and — (this is a double-minus–it’s just hard to tell). someNumber += 3 is equivalent to someNumber = someNumber + 3, but just easier to write. someNumber++ is essentially someNumber += 1, with some caveats.
We also have the comparison operators, ==, !=, <, > ⇐, and >=. Notice that to compare equality, you must use double equals. The != means not equals.
(Style) In Java, variable names and method names are, by convention, camelCasedLikeThis. Classes and types are CapitalCamelCasedLikeThis.
(Deliverable) Declare two integers to represent the number of students total this summer in EPGY (guess), and the number of courses (also guess). Find the average number of students per class, and print it out. You can concatenate an int to a String exactly the same way you would concatenate two Strings.
So, speaking of Strings, what are they? Strings are not primitives. They are Objects, with slightly more complexity, and also methods defined on them. In Java, you can call a method on an object by saying myObject.someMethod(). This will call someMethod on myObject. Remember that methods need to be called on an actual instance of an object. So say you have some String, String someString = “this is a string!”;. It would not make sense to do String.length(), since String is the type, it doesn’t make sense to do this. You would call someString.length() to get the length of the string (which should return 17 in this case). Eclipse is super awesome in that it has smart autocompletion, so if you type a dot after a variable, it will automatically list the methods you can call on that object. This is one of the most killer features in Eclipse, and you should totally make use of it.
In Java, Strings are immutable, meaning you can’t change them once you’ve created them. However, you can just create a new string, or reassign the current string. If you are curious about this, ask Ben or one of the RCs.
Also, to compare strings, you must actually use str1.equals(str2) instead of ==. We’ll see why this is the case later.
(Deliverable) Create a few Strings, reassign one of them, and do a print statement with two strings, a double, and a char.
(Deliverable) There’s a method for a String to create a substring. Create a substring of one of your Strings, and print it out.
Some of the things that makes high-level programming languages useful are, of course, control structures. The if statement tests whether a boolean or condition is true, and only executes a statement if it is. The optional else statement will only execute otherwise. Example:
if (2 < 5) {
System.out.println("Math works!");
} else {
System.out.println("Oh no! Math is broken!");
}
Something fun to play with is a random number generator. Java makes it very easy to make one. First, let’s create a private static Random object called ‘random’. Do this by typing “private static Random random = new Random();” on a line outside of a method. This, unlike the other variables you’ve created so far, is an instance variable. The other variables are called local variables. Local variables will only exist within the innermost braces they’re in, called the scope, but instance variables will be available and accessible by every method in the class. The “static” means that there should only be one “static” copy of this, accessible by typing ClassName.instanceVariableName, whereas without the static, the variable is attached to each instance of this class, so myClassA.variableName and myClassB.variableName can each have their own copy of variableName.
To use the random number generator after creating it, just call random.nextInt(10); This will generate a random integer between 0 and 9. You can assign this to an int variable of course by saying “int someNumber = random.nextInt(10)”.
(Deliverable) Generate a random number between 50 and 180. (Yes, you will need to use addition (gasp!) for this.) If it is less than 90, print out “Low blood pressure!”. If it is between 90 and 130, inclusive, print out “All normal!”. If it is greater than 130, print out “High blood pressure!”. Watch the edge cases.
By this point, we’ve been using methods without really talking about them in detail. Methods essentially define small segments of code that can be used elsewhere. A method is declared in the file as multiplyStuff. Let’s go through each component of its declaration and implementation:
The private indicates that the method is accessible only within this class. These are often called helper methods since they help this class do its job, but cannot be accessed by other classes. There are three other scopes besides private. If you don’t put down any scoping keyword, Java assumes the package scope, which means that only classes within the same package, or folder, can access the method. A bit more lenient than the package scope is the protected scope. This means that subclasses as well as classes in the package can access this. We’ll talk about what this means a bit later. Finally, you can declare a method to be public, which means that all classes, anywhere, can access this. These same scoping keywords can be used on instance variables.
The static, like the instance variable modifier, just indicates that the method can’t access non-static instance variables. What this means at a high-level is that the method can’t access the instance variables “belonging” to a specific instance of the class, so it can only do stuff based on what you passed in. On the other hand, a method that isn’t static can use instance variables belonging to the specific class. A more specific example of this would be the Java Math class, which dutifully handles operations like exponentiation or trig functions. You certainly could get by without needing a separate instance of Math to give you a sine, so the sine method is given as a static method and called as Math.sine(0.343). This is a tricky concept, so ask for some help if you don’t get it.
The next portion is the return type, or what this method will return back once it completes. In our example, we used an int. If the method doesn’t return anything, the return type will be “void”.
Then comes the methodNameInCamelCase.
Inside the parentheses are the parameters, or what you can pass into the method to make it work. Think of parameters as the inputs to a machine that does some processing, and the return type as the output. In the example method, we pass in three ints as parameters.
In the body of the method, we just multiply the three numbers together.
We then actually return our result using the keyword “return”.
(Deliverable) Create a method called getRandomBetween(int low, int high) that will return a random integer between low and high, both inclusive. In your main method, use this method you just created to print out a random number between -5 and 5.
We can start making this really powerful by doing things repeatedly. In Java, there’s a few ways of doing this, and also a few special loop-related statements:
while loops. While loops are similar to if statements. You have a condition, and you execute what’s in the body if the condition is true. However, you will recheck the condition as soon as you finish the body, and will keep going as long as the condition is true. So, for example, you can have something like the following that will print the numbers 1 to 5.
int num = 1;
while (num <= 5) {
System.out.println(num);
num++;
}
for loops. Many times, you have a loop that initializes some variable, will check to see if that variable is in some range, and change that variable in every iteration in the loop. Because this pattern of use happens so often, we have a special loop for it, called the for loop. The previous statement, written as a for loop, would look like the following. Notice how much simpler it is!
for (int num = 1; num <= 5; num++) {
System.out.println(num);
}
break; If you have the statement “break;” anywhere inside a loop structure, you will automatically jump to the first line after then end of the loop. This is useful for getting out of a loop in the middle if some condition was reached.
continue; Sometimes, you want to jump to the end of the loop, but would still like to keep looping. In this case, instead of “break,” use “continue”.
If you return something in a loop, you will also implicitly break out of any loops, since once you return, the method is done.
(Style) Notice that we have been tabbing. The convention is to tab over each time we start a brace. Having correct tabbing not only makes your code more readable and pleasant, but can prevent bugs as well. In Eclipse, if your tabbing starts going awry, you can select all (Apple/Ctrl-A), and auto-tab/auto-indent by hitting Apple/Ctrl-I. .
(Style) You also notice that there are comments in the code. Comments are often crucial to understanding a program, especially for convoluted code. Experienced programmers rigorously comment their code to note how their code works. Many experience programmers also start out a program by just writing comments to plan out their program, and decomposing each commented tasks into methods and subtasks. Such an approach is a combination of two ubiquitous strategies in designing code: pseudocoding anddecomposition. We highly recommend that you do this.
(Deliverable) Create a method called gambleOnZero(int maxNumber). This method will generate generate random numbers between 0 and maxNumber, printing out each as it generates them, and keep generating them until the number 0 is generated, at which time the method ends, return the number of numbers it had to generate to get to 0. In your main method, call the gambleOnZero method, and print out how many times it took.
(Deliverable) Create a method called triangleNumber(int n). The nth triangle number is the total number of items in a pyramid if you have n items at the bottom level, n-1, in the level above that, and so on until you have one item at the very top. Calculate this using a for loop.
(Deliverable) And, to tie it all together, create a method called textTwist(String str, char haltingChar). This method will go through the String str character by charater, and, with 1/3 probability, swap that letter with the next letter in the String. (Obviously, you’ll actually just stop at the second-to-last character in the string.) In addition, we’ll keep doing this either until we reach the end of the string, or reach a character that matches the haltingChar. If that’s the case, we will just return the twisted substring from the start of the string until, and including the haltingChar. Otherwise, we will just return the entire twisted String at the end. Call this with 3 different Strings and print out the results.
Give the people sitting next to you high fives. Honestly, high fives are great, just make sure you give them a heads up.