Pre-bootcamp Learner Notes

Once you’ve followed the Pre-course Introduction section, follow through these tutorial chapters and self-guided exercises. This will ensure that you’ve got a grounding in the fundamentals of the C# language and Git, so that you’re ready for Bootcamp.

1. Your first Java program

This topic sees you write your first Java program.

Reading material

Work through Chapter 1 (“Getting Started”) of The Java Tutorial, or if you’re using the online version then follow the “Getting Started” Trail.

Hello World! in VSCode

If you are using our recommended development environment, Visual Studio Code, then you should follow the instructions below to create the “Hello World!” application, rather than the instructions in the tutorial.

  • Start by creating a new folder for the program (say C:\Work\Training\HelloWorld) and then open that folder in VSCode (File > Open Folder…)
  • Create a new file (File > New File…) called HelloWordApp.java
  • Type the following in the VSCode editor, and save it:
/**
 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}
  • The following steps are for compiling and running the code. If any problems occur, consult Common Problems (and Their Solutions)
  • Open a terminal console in VSCode (Terminal > New Terminal)
  • At the prompt (which should show the project path C:\Work\Training\HelloWorld), type the following command and press Enter: javac HelloWorldApp.java
    • At this step, the compiler generates a bytecode file, HelloWorldApp.class.You should be able to see this file in the Explorer window in VSCode
  • At the Terminal prompt, type the following command: java -cp . HelloWorldApp
    • At this step, your program is executed
    • You should see the text Hello World! in the Terminal window – if so then your program works!

If you get stuck with the above and the Common Problems page hasn’t helped, ask your trainer for some help.

Once you’ve finished reading, work through the exercises in the book or trail. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 1.1

As we progress through this section, we’re going to work through and build a very simple Calculator application. It will be a console (command line) application and so entirely text based. Here’s how to get started:

  • Create a new folder for your project (say C:\Work\Training\Calculator) and then open it in VSCode
  • Create a file called App.java with a main method, like the Hello World example
  • Write some code that just prints out a welcome message for your calculator app – e.g., “Welcome to the calculator!”
    • Because your filename is App.java, the class name should be App also
  • Run your program from the menu (Run > Start Debugging)
    • Check that your program prints the expected message!

Exercise 1.2

Having started your Calculator program, we want to put it on GitHub for all the world to see. Or at least, so your tutor can take a look in due course. In git, each project generally lives in its own ‘repository’. Here’s how to create one:

  • Go to GitHub
  • Click the green “New” button to start creating a new repository
  • Enter a suitable name for your repository – “Calculator” would do! Make sure the “Owner” is set to your name. Enter a description if you like too.
  • It would be handy to “Add .gitignore” – choose “Java” as the template.
    • .gitignore is a file describing the types of files that shouldn’t be stored in git; for example, temporary files or anything else that shouldn’t be shared with other team members. You pick a Java-specific one so it’s preconfigured with all the files the Java compiler will create that really shouldn’t be stored in git.
  • Leave everything else at the defaults. In particular you want a “Public” project, unless you want to pay for the privilege.
  • Click “Create repository”.

That gives you a (nearly) empty repository. Now you want to link that up to your Calculator. Open up Git Bash (or your command line utility of choice). Navigate to where your Calculator lives (e.g. cd C:\Work\Training\Calculator, or right-click and use ‘git bash here’). Then run the following commands:

git init
git remote add origin https://git@github.com:YourName/Calculator.git
git fetch
git checkout main

Replace “YourName” in the above with your GitHub username. You can find the correct text to use by clicking the green “Code” in your project on GitHub and then finding the “Clone with HTTPS” URL.

Info

We’ll discuss these git commands later in the Bootcamp, and for now you don’t need to worry about what they do exactly. Broadly what we’re doing is setting up a local repository that’s linked to the one on GitHub so changes you make can be uploaded there.

If you’re using a GitHub account you created in 2020 or earlier, you may need to replace main with master above because that used to be the default branch name. If you’ve just signed up for GitHub now that won’t be an issue.

You should find that there are no errors, and that the .gitignore file that you asked GitHub to create now exists locally. However if you refresh your web browser on your GitHub project you’ll see that hasn’t changed – the Calculator code is only on your local machine. You can fix this by running this in your command prompt:

git add .
git status
git commit -m "My first piece of C# code"
git push

Now refresh your GitHub browser window and your source code should be visible!

Info

Again, we’ll discuss what these are doing later – for now just remember that you should run these four commands, replacing the text in quotes with a short summary of what you’ve changed, every time you’ve made a change to your code and want to update your GitHub repository with that change.

When you’re prompted to submit your answers exercises during the course, you can just supply the GitHub link – something like https://github.com/YourName/Calculator. Your trainer can see the code, and provide feedback on it if appropriate. You don’t need to submit anything at this stage, you can move on to the next exercise.

Some notes on git

For the time being, you don’t need to worry too much about what the various commands above actually did. However, here are some details to satisfy your curiosity:

  • git init: Turn the current directory into a git repository on your local machine. A hidden directory .git is created to manage all the git internals – the rest of your files stay unchanged.
  • git remote add origin git@github.com:YourName/Calculator.git: Git is a distributed version control system. Your local machine contains a complete and working git repository, but other people can also have a complete and working copy of the git repository. If one of those “other people” is GitHub, that provides a convenient way of sharing code between multiple people. This line just says that GitHub (specifically, your Calculator repository) should have a remote copy, and we’re naming that copy “origin”. The name “origin” is just a git convention meaning “the master copy” – but actually you could use any name, and Git doesn’t really do anything special to make one copy “more important” than another.
  • git fetch: This downloads all the latest changes from GitHub. In this case, that means downloading the .gitignore file to your machine. But it’s not visible on your local machine yet…
  • git checkout main: This tells Git which version of the code you want to see. The “main” branch is the main copy of the code that’s currently being worked on. You’ll notice “Branch: main” is displayed in GitHub too – you can create multiple branches to track progress on different features under development, and this is useful if several people are working on your code at once.
  • git add .: This tells Git to record the changes made to all the files at . which means the current working directory; you could equally well specify each individual file by name.
  • git status: This doesn’t actually do anything, but displays the current status of your repository – you should see some files listed as being changed and ready for commit.
  • git commit -m "My first piece of C# code": This tells Git to save those changes in its history. That way you can go back to this version of the code later, should you need to. Git provides a history of everything that’s happened. The -m precedes a message which explains the purpose of the change.
  • git push: This sends all the changes stored in your local repository up to GitHub. It’s just like the earlier git fetch, but in the opposite direction.

If you want to see the history of your commits, click on the “commits” label in GitHub, or run git log locally. There’s also a local graphical view by running gitk.

2. Variables and control flow

This topic introduces variables, i.e. how you store data within your program, and control flow, i.e. how you get your code to make decisions. We’ll use this knowledge to make your Calculator project a bit more functional.

Reading material

Work through Chapter 3 (“Language Basics”) of The Java Tutorial, or if you’re using the online version then follow the “Language Basics” Trail.

Once you’ve finished reading, work through the exercises in the book or trail. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 2.1

Add the following functionality to your Calculator project:

  • Display two random numbers
  • Prompt the user to enter an operation to perform on them: “+”, “*” (multiply) or “-” (subtract).
  • Perform that addition / multiplication / subtraction on the random numbers, and print out the result

Here’s how to read in a string from the user:

Scanner scanner = new Scanner(System.in);
String input = scanner.next();

And here’s how to generate a random number between 0 and 99:

Random random = new Random();
int randomNumber = random.nextInt(100);

See if you can combine these snippets with what you’ve learnt so far to implement the calculator functionality required.

Once you’ve got your program working, commit the changes to GitHub. You should be able to follow the same steps as last time (from git add onward), or here’s an abbreviated version:

git commit -a -m "Added a choice of operations on random numbers"
git push

The -a argument to git commit tells Git to first add any changes, and then commit them. Note that this only works if Git already knows about the files – it won’t pick up any newly created files.

3. Numbers and strings

This topic introduces the key data types for numbers and strings, and how to convert between them. Again we’ll apply this to your Calculator.

Reading material

Work through Chapter 9 (“Numbers and Strings”) of The Java Tutorial, or if you’re using the online version then follow the “Numbers and Strings” Lesson Trail.

Once you’ve finished reading, work through the exercises in the book. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 3.1

Currently your calculator picks two random numbers to do calculations on. Improve it by letting the user supply the two numbers, as well as the operator. Perform the addition / multiplication / subtraction on the two numbers supplied, and print out both the sum you’re calculating and the result.

4. Classes and objects

This topic looks at how Java encourages you to organise your code into logical units called Classes, and at the core concepts of Object Oriented Programming. If you are already familiar with these concepts then feel free to skim through the material.

Reading material

Work through Chapter 2 (“Object-Oriented Programming Concepts”) and Chapter 4 (“Classes and Objects”) of The Java Tutorial. If you’re using the online version then the relevant Lessons are Object Oriented Programming Concepts and Classes and Objects.

As usual try the exercises in the book once you’ve finished. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 4.1

At the moment your Calculator probably consists of a series of code blocks dealing with the different operations (add, subtract, multiply etc.). Refactor this code to introduce a more organised way of handling the operations:

  • Add separate classes for each operation (e.g. Multiply, Add, etc.)
  • Add a Calculation interface, exposing a single method calculate that takes the two values to perform the operation on
  • Modify your code to create instances of these classes and use them to do the sums

This approach is overkill when you’re doing something so simple as adding or multiplying numbers, but it’s good practice at putting some structure into your code – as the operations being performed become more complex, the benefits start to rapidly accumulate!

5. Collections

This topic looks at the Java collection classes, which provide ways of working with sets of data rather than single values.

Reading material

Work through Chapter 12 (“Collections”) of The Java Tutorial. If you’re using the online version then instead use the “Collections” Trail.

The first two sections (Introduction and Interfaces) are the most important for now.

Once you’ve finished reading, work through the exercises in the book. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 5.1

So far our calculator only performs operations on two numbers. Let’s enhance it so it can do calculations on any number of numbers! For example:

3 + 4 + 5 = 12
1 * 2 * 3 = 6
12 - 2 - 2 = 8

Let’s keep things simple by using the same operator each time. So a typical output might look like this (for the first sum above):

Welcome to the calculator!
==========================
Choose an operation: +
How many numbers? 3
Enter number 1: 3
Enter number 2: 4
Enter number 3: 5
Result: 12

As a starting point, try implementing this using arrays rather than collections. See what you can come up with, and push the result to GitHub.

Exercise 5.2

We kept things simple above by asking the user “How many numbers?”. The motivation behind this was that we need to specify the length of an array up-front. Here’s a slightly better interface for the Calculator:

Welcome to the calculator!
==========================
Choose an operation: +
Enter a number: 3
Enter another number: 4
Enter another number: 5
Enter another number: done
Result: 12

Use a collection class such as ArrayList to improve your Calculator to work in this more flexible way.

6. Input and output

This topic looks at Input and Output (or ‘I/O’). This is typically reading and writing to files, or other external inputs/outputs such as internet connections.

Reading material

Work through Chapter 11 (“Basic I/O and NIO.2”) of The Java Tutorial. If you’re using the online version then instead use the “Basic I/O” Lesson.

Once you’ve finished reading, work through the exercises in the book. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 6.1

Let’s add a feature to the calculator where it can read the input numbers from a file, and logs all calculations to a file.

Suppose you have a file called numbers.txt containing:

3
4
5

The Calculator might have an interface like:

Welcome to the calculator!
==========================
Choose an operation: +
Enter a file: numbers.txt
Result: 12

Exercise 6.2

Once you’ve done the above, try logging the results of your calculator to a separate file.

  • Clear the log when the program starts up
  • Print each calculation as a separate line in the log file
  • Create your logging code in a separate class, avoiding static methods where possible, to make it reusable in future

7. Exceptions

This topic introduces exceptions which can be used to handle errors or other exceptional events.

Reading material

Work through Chapter 10 (“Exceptions”) of The Java Tutorial. If you’re using the online version then instead use the “Exceptions” Lesson.

Once you’ve finished reading, work through the exercises in the book. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 7.1

Your Calculator probably has a block of code that consists of a series of if-tests or a switch statement to decide which operation to carry out (+, -, *, /). What happens if the user enters an invalid operator?

Move this decision logic into a separate method, and have that method throw an exception if an invalid operator is entered. Run your code and check that the program now fails in a suitably fatal manner.

Then modify the main method to catch and handle that exception appropriately, for example displaying a sensible error to the user and then letting the program continue running. Run your code again, and check that the exception is no longer fatal!

Think about other error cases that might occur – are they handled appropriately?

  • Entering invalid numbers
  • Multiplying very large numbers (so the total is more than 2 billion)
  • Other problems?

8. Packages and packaging

Packages allow you to bundle together classes (and interfaces) into convenient hierarchical units.

Reading material

Work through Chapter 8 (“Packages”) of The Java Tutorial. If you’re using the online version then instead use the “Packages” Lesson.

Having done that, take a look at Chapter 16 (“Packaging Programs in JAR Files”), which is the “Packaging Programs in JAR Files” Lesson online.

Once you’ve finished reading, work through the exercises in the book. Use the link to check your own answers, and make a note of anything you don’t fully understand.

Exercise 8.1

Your calculator is likely just in the default unnamed package – put it in a sensibly named package, with any supporting classes in their own sub-package.

To complete work on your calculator, try packaging your classes into a jar file which can be easily distributed and run on the command line:

java -jar calculator.jar

9. Conclusion

This topic concludes the “Introduction to Java” course. You have seen how to create a simple Java program and prepare it for sharing and deployment.

Whether you’ve been working through the Java Tutorial book or online course, there’s more material there to look at now that you’ve finished the rest of the course. Pick the bits that look most interesting, and see how much more of what you learn you can put into your Calculator application!

Beyond that, the best way to learn is by doing.

A programming kata is a practice piece – a relatively simple problem where the goal is just to practice solving it in different ways, and hence develop your expertise. You can start of course by just solving the problem once, any old how – if you’re still learning Java, that experience has taught you something. But once you’ve done that, how about trying it again in a different way. Could you use more Collection classes, or divide the problem into classes / methods differently? What happens if you change the problem (e.g. supply different inputs, or ask a slightly different question in the output) – how easy is your code to adapt? Here are a couple of kata to start you off:

Another fantastic source of learning is your job, which presumably involves programming. If you didn’t know Java at all before taking this course, you probably haven’t actually done much programming yet… Now is your opportunity! You should know enough to be able to read and understand some simple Java code, even if you still struggle to make modifications to a large application. Ask around for some suitable code to read. Perhaps try to find a known bug or requested feature, and have a go at making suitable changes to the code.

If you’re not yet confident enough to do this “for real”, there’s no harm in trying it “for practice” – just don’t commit the code to your source control and your tentative changes will never go live. This is a great opportunity not just to practice Java, but to get familiar with the particular applications you’re going to be working with. After you’ve been on the Bootcamp, you will hopefully be ready to take the next steps and start making a more substantial contribution to the projects you’re working on.

Good luck, and see you at the Bootcamp!