Session 2: Java Deep Dive

An Introduction to Java, the language of Android

Welcome back to Hack School! It's currently Week 3 at UCLA, and hopefully your midterms haven't quite started yet. Last week, we covered how to use Android Studio as well as a few basics. We will continue on this week to tackle the language that is used to develop Android Applications--Java.

Announcements

If you missed today's session, here are the relevant resources: Slides, Screencast

If you haven't yet joined, we have also launched a new ACM Hack slack. If you want to network with other students in Hack School, get help on projects, or just want general questions answered then register at the following link: https://hackucla.slack.com/

Topics

Session 2 will dive right into Java. This session will assume basic prior programming experience such as if statements and loops, and go a bit more in depth on newer topics more specific to Java. The following topics listed out are:

  • Java Basics
  • Important Java Data Structures (Containers)
  • Try/Catch
  • Classes
  • Project

In the slides and presentation for this Session, there's a brief section to brush up on Session 1 topics. If you would like a review, you can find the blog post here.

Java Basics

Java is an object-oriented, class-based language that is used to develop Android Applications. Essentially, what that means is that you can create templates, called classes, that bundle up both functions and member variables to allow for very powerful and easy programming. Object-oriented programming is a discussion within itself, so I won't go into detail about it. What you need to know is that it's a lot like C++, so if you know C++, you should have no trouble learning Java!

Variables in Java are much like variables in C++. They have a type which must be strictly adhered to. Note that you can cast variables which is super helpful but shouldn't be relied on as a crutch! Here are a list of variables you may encounter:

  • int
  • float
  • double
  • boolean*
  • char
  • String*

Note the small difference between boolean vs bool and String vs string when comparing Java and C++.

Printing in Java is traditionally done with System.out.print. However, in Android Studio, we use the Log function, which has 4 different ways to print information. We will focus on Log.d(String1, String2), which prints a tag and a message, with 'd' standing for Debug.

If-Else Statements are also quite standard. Code will be executed in whichever block a condition is met, and if none of the conditions are met, then the code in the else block will be run.

if(i > 5) {  
    //code
}
else if(i < 3) {  
    //more code
}
else  {  
    //even more code
}

For Loops execute code for a certain number of repetitions. The syntax is as follows: for(initializations; condition; iterator)

for(int i = 0; i < 10; i++) {  
    Log.d("Info", "ACM is awesome!");
}

While Loops execute code as long as some condition is true. This is the same as a for loop, except the initialization and iteration is left outside the conditional block.

int i = 1000;     //x is some predefined number  
while(i > 0) {  
    i = i / 2;
}

Arrays are used to hold a set of data. There is a general standard in Java on how to declare and define arrays. In Java, all elements in an array must be of the same type.

int [] anArray;  
anArray = new int[10];

//alternate definition
int [] yourArray = {2, 4, 1, 5, 2};  

Declaration and definition can be done in the same line or separate lines. Do not forget the new keyword. The compiler will not be happy if you forget it.

Containers - ArrayList

This part will go by the assumption that you haven't taken a course on Data Structures. Hopefully this will give you a quick introduction. If you know what an array is, you'll know how great it is to be able to store large chunks of data at once. For example, if you're working on a classroom app, you can store the information for a whole lecture of students. However, there's downsides to arrays. The main one is that they cannot be resized, and you might need some operations to add elements or remove elements, which is often difficult to do with plain arrays.

Enter ArrayList. An ArrayList is very similar to an array. In fact, you can pretty much think of an ArrayList as an array, except that it is dynamic in size. That is, you don't have to specify a specific size right away, and you can continue to add and delete elements as you please. I'm not going to go into the implementation of an ArrayList; just know that there are specific built-in function to call such as .add(), .size(), and .get() which help you work with ArrayLists. Here's how to use an ArrayList.

List<String> myList = new ArrayList<String>();  
myList.add("Apple");  
myList.add("Banana");  
myList.add("Cake");  
myList.get(0);             //returns "Apple"  
int size = myList.size();  //size = 3  
myList.remove(1);          //removes Banana  

Declare an ArrayList with List<String> myList = new ArrayList<String>();. General practice is to use List as the variable type, and specify it as an ArrayList. You do this because it allows for a more general interface such that you can change between different containers (such as Linked Lists, etc).

You can use myList.add("Apple"); to add something to your ArrayList. To retrieve something, use myList.get(index); where index is some integer that you're looking for. Note, you do not use myList[2] = "Pear"; and then try to access it with myList[2] because this will not work. It's an ArrayList, not an array!

Containers - Map

A map is a data structure in which you can look up values by a particular key. So why would you ever use this? Perhaps you want to look up the price of a car. You have a list of cars, and a list of prices. A map can associate a car to a price, and allow you to look up how expensive or cheap a car is!

Map myMap = new HashMap();  
myMap.put("BMW", 60000);  
myMap.put("Toyota", 25000);  
myMap.get("Toyota");            //returns 25000  

This is a basic example, but you may end up learning and using this later, so hopefully it gives a very brief (but useful) introduction to maps.

Classes

Classes are generally used as a template or a blueprint for objects. We won't go into what classes are or why you should use them - we'll save that for CS31, CS32, or your own reading.

To create a class, select File > New > Java class. From here, you'll be able to add constructors, add private variables, and create methods you wish to call with that class. Here's an example of a class Student:

public class Student {  
    private String school;
    private String name;
    private double gpa;
    public Student(String startSchool, String startName) {
        gpa = 4.0;
        school = startSchool;
        name = startName;
    }
    public boolean canBrag() {
        if(school == "USC") {
            return false;
               }
               return true;
       }
}

In this class, we created a constructor which takes in 3 arguments, private variables school, name, gpa, and a method canBrag.

Now that we've defined a Student class, you can use it in your app, perhaps in MainActivity.java with this line of code:

Student s = new Student("School", "Name")  

You can even create an ArrayList of students:

List<Student> studs = new ArrayList<Student>();  

We can now utilize what we learned about ArrayLists and its functions.

List<Student> studs = new ArrayList<Student>();  
studs = new ArrayList<Student>();  
studs.add(new Student("UCLA", "Dmitri"));  
studs.add(new Student("USC", "Tommy"));  
for(int i = 0; i < studs.size(); i++) {  
    if(studs.get(i).canBrag()) {
        Log.d("Real student", studs.get(i).getName());
    }
}
Try-Catch

Try-Catch is used in Java to catch/handle exceptions, which are events that occur during execution of programs that disrupt the normal flow of instructions (such as dividing by zero).

The try block includes statements that may cause an exception. The catch block runs if some particular exception occurs in the try block. The catch block is where the the error is actually handled.

Here is an example:

try {  
    // Try block to handle code that may cause exception
    int num1 = 0;
    int num2 = 62 / num1;
    System.out.println("Try block message");
} 
catch (ArithmeticException e) {  
    // This block catches divide-by-zero error
    System.out.println("Error: Division by zero");
}
//Outside the try-catch block now. 

Let's get some points!

For beginners you can solve all of the exercises and receive points for completing those. For intermediate/advanced students you can work on the weekly project with your team, and receive points for completing that. You can only get credit for one or the other, but not for both so choose the one most appropriate for your skill level. Please only submit one .zip file per team. Include the contents of your entire android project, and also provide your team access code in a text file. Otherwise you will not receive credit!

Grading

Submissions will be due 1 week from the session, but we will accept late submissions taking some points for each day it is late. The lateness penalty for an assignment that is submitted between N and N+1 full days late (where N is nonnegative) is 2^N % of the assignment's value. That is, the penalty is 1% for being up to 1 day late, 2% for being from 1 to 2 days late, 4% for being from 2 to 3 days late, and so forth.

Exercises

Exercise 1: ArrayLists
  1. Create a Text Field and two Buttons.
  2. Use the Text Field to gather input in the form of names.
  3. Have the first button add the name to an ArrayList of Strings.
  4. Use the second button to print (log) out all names to console.
Exercise 2: Classes
  1. Create a class called Professor.
  2. This class should have private variables name and quote.
  3. This class should have a function called setQuote that takes a parameter and changes the professor’s quote.
  4. This class should have a function called talk that makes the professor say his or her quote.
  5. Now, create a Text Field and use the input of this Text Field to change the professor’s quote.
  6. Make this professor talk upon a button click!

Project 2

For the second project we will be building out a text scrambler using different encryption strategies. The goal is to build out this project with your team based off the knowledge gained from this section. If you are feeling confident you can attempt to complete the project without the skeleton, but it will be a lot easier if you use it. We will be uploading the project solution towards the end of the week, so if you haven't cracked it by then look at the solution to learn the correct implementation.

Instructions

The goal is to scramble the input text into a "encrpyted" output text. There will be three encrypt and three decrypt methods for you to implement, and the primary purpose of this is to get more familiar with the java language so try using varied syntax for each of the encryptions. Additionally there is a swap button at the top that should switch between the encrypt and decrypt mode. The implementation is pretty flexible, so we will grade simply based on functionality so don't worry too much about following a particular structure.

Encryption 1

Implement a substitution cipher (https://en.wikipedia.org/wiki/Substitution_cipher)

  • Example:
  • plain text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • cipher text: ZEBRASCDFGHIJKLMNOPQTUVWXY
  • "flee at once. we are discovered!" transforms into "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"
Encryption 2

Implement a polyalphabetic cipher (https://en.wikipedia.org/wiki/Polyalphabetic_cipher)
This is similar to substitution but using multiple substitution alphabets

  • Example:
  • plain text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • even letter cipher text: ZEBRASCDFGHIJKLMNOPQTUVWXY
  • odd letter cipher text: CDFGHIJKLMNOPQTUVWXYZEBRAS
  • "test" transforms into "yaxo"
Encryption 3

Implement your own encryption
This doesn't have to be complicated, but for those who are interested in security, and want try something more advanced you could try creating AES encryption, which is the standard worldwide. You can also take a look at some of java and android's built-in encryption libraries for more ideas here is a link to the android developer docs

Hints
  • Start with the xml layout.
  • Add ID’s for UI objects that you want to interact with in the code.
  • Set up ui components in the code
  • Implement swap button
  • Work on each of the encryption methods, one at a time.

Here is the link to the project skeleton: https://github.com/uclaacm/Hack-School-Winter-Session-2