Last time, we started our coding journey with the NetBeans IDE and Java Development Kit, getting the ‘Hello, world’ app out of the way. We even had Java calculating the answer to life, the universe and everything. But in order to do some more serious coding, we need to introduce some new key concepts.
If you missed the last session, we made Java calculate the answer to life, the universe and everything and display it to the console (command prompt, if you like) with the following code line:
System.out.println( “The answer to life is “ + (7 * 2 * 3) );
Inside the second, inner brackets, Java is doing some multiplication for us, which is fine if all you ever want to know is 7 x 2 x 3. This is an example of ‘hard coding’ and it’s not terribly useful because it doesn’t do anything else.
Look at it another way – what if you had $1 million in a bank account earning 5% interest per year. How much have you earned after one year? We could write that again as:
System.out.println( “Interest earned: $“ + (1000000 * 0.05) );
If you add this to our JavaApplication1.java code from last month, you’ll get the answer:
Interest earned: $50,000
And that’s great – provided you knew what the source code was calculating. To the end-user, it means diddly-squat. To calculate different amounts this way, we’d have to change the source code every time and recompile it to calculate the answer. In a word, yuck. Instead, we can write a program that asks the user for the cash amount (the ‘principal’) and the interest rate, calculates the amount of interest earned and returns the answer to the console output.
To print text to the console, we’ve been using a special Java class called System and in particular, using the System.out.println (print line) function. System.out is Java’s standard output device, which in this case is the computer screen. But Java also has a standard input device too – the keyboard – and we can use it to get data from the user. To do that, we use Java’s Scanner class to read the keyboard input (System.in). The great thing about Java is that it’s designed so that you can reuse code – you don’t have to write everything from scratch and classes are one form that reusable code takes.
App #2 – InterestCalc
Let’s start with a brand new project in our NetBeans IDE – choose File/New Project, ensure ‘Java Application’ is selected, click the Next button, change the Project Name entry to ‘InterestCalc’ and the Finish button.
Now before we go off half-cocked, let’s nut out what we want this project to do. This is actually the most important step because it helps ensure you don’t start heading down rabbit warrens sign-posted ‘feature-creep, this way’, looking for great new ideas you probably don’t need. So, here’s what our program will do:
1. (INPUT) Greet the user and ask for three pieces of information:
a. The amount of cash in the bank account
b. The interest rate on the account
c. The amount of time the cash is earning interest
2. (PROCESS) Calculate the total interest over that time
3. (OUTPUT) Display the result back to the user.
It sounds pretty simple but having the plan in the first place is what makes it simple. It also follows a very simple programming model called IPO – input, process, output.
Getting input from the user
To begin, the first thing we need is to import Java’s Scanner library code into our project – this is brilliant because it just saves so much time. To do this, we add the following line to line 8 of our project:
Beware the capital letters! Java is case-sensitive so always put the upper-case letters in when asked, otherwise, you’ll generate syntax errors. The first code statement in your java code should always be the ‘project’ statement – after that, you put in any java classes you wish to import. Now we’re ready to write our program inside the main section or ‘method’.
The first thing we do is use the Scanner class to create a new Scanner object called ‘input’:
Scanner input = new Scanner(System.in);
Classes are one of Java’s most important features and we’ll talk a lot more about them in the months ahead. The standard convention is that class names begin with uppercase letters and objects/variables with lower-case to help you distinguish between the two. This code line assigns a new Scanner object listening to the keyboard (System.in) to the input variable.
So what’s a variable? A variable is essentially a chunk of memory in your computer you can use store stuff – numbers, strings of characters, photos, whatever you want – but rather than having to know its exact logical location, we can define that chunk by a data type and a name and let Java look after where it’s kept.
In the case of the Scanner statement, we’re assigning the chunk of memory to the variable ‘input’ and we’re declaring it to be a new Scanner object. Not making any sense? Try this – think of a variable as a big coffee mug. You know – the one on your desk, holding those pens, pencils and your takeaway Thai chopsticks? On the mug, you write the variable’s name, decide what type of stuff or ‘data’ it’ll hold and load it up with whatever matches the designated data type.
You can create any data type you wish, but Java comes with some basic common ones called ‘primitive data types’. They include ‘integer’ (whole numbers), ‘double’ (decimal-point numbers) and ‘boolean’ (true or false). When you create or ‘declare’ a variable, you declare its datatype and its name. Let’s declare some variables for our InterestCalc program, using the following code:
We’re declaring the variables principal, interestRate, accountTime and interestAmount to be of type ‘double’, which means they can each hold a decimal number (including integers, kind of). This step is vital because you cannot assign any value to a variable without first declaring what type it is.
Notice a couple of things here – first, we’ve used plain English words for the variable names. This is a good habit to get into, rather than just using ‘x’ or ‘y’, because, again, it makes your code easier to read. Note too that ‘interestRate’ uses a lower-case ‘i’ but uppercase ‘R’ – this is another programming convention to again help ease of reading and object identification.
Now we ask the user for the data we need:
System.out.print(“Cash in account (eg. 1230.50): “);
principal = input.nextDouble();
System.out.print(“Interest rate (eg. enter 0.05 for 5%): “);
interestRate = input.nextDouble();
System.out.print(“Time in account (eg. 2.45 years): “);
accountTime = input.nextDouble();
Note the pair repetition here – we start with a print statement asking the user for data and in the next line, the data comes from the input.nextDouble function and is assigned to a variable. The nextDouble function knows to wait for and take the next numeric data entered in (literally, it waits for the Enter key to be pressed) and store that in the assigned variable.
Note the text string is printed using ‘print’, not ‘println’ as we did last month. The println function adds a carriage-return or line-feed to the end of the string of text, meaning our user command prompt would start on the next line. Using print instead keeps the cursor at the end of the line, which just looks a bit neater.
interestAmount = principal * interestRate * accountTime;
In other words, we multiply the values inside the ‘principal’, ‘interestRate’ and ‘accountTime’ variables and assign the result to the variable interestAmount. This is an example of a ‘mathematical expression’ – a very simple one, but that’s what it’s called.
The last thing we have to do is write the answer back to the user via the console:
System.out.println(“Total interest: “ + interestAmount);
Now each time we run this program, we can load in different values for principal, interest rate and time in the account and get the right result. But since we have the yearly interest amount in a variable called ‘interestAmount’, we can do something else with it too – like, work out the equivalent amount of interest per week. We can do it on-the-fly with another print statement:
System.out.println(“Average per week: “ + interestAmount/(accountTime * 52));
We’re taking the total interest amount and dividing it by the years the money is in the bank multiplied by 52, which will give us the equivalent interest earned per week, assuming it is paid once a year and not reinvested. This ‘on the fly’ calculation is called an ‘inline expression’ because we’re doing it ‘in the same line’ as printing the text string to the console. There’s only one problem – loading the IDE every time we want to run the app is a bit of overkill.
Build a standalone app
Well, this isn’t exactly true – you can’t really build a Java ‘standalone’ executable because that’s not the way Java works. Java is sometimes considered a bit weird in that you compile the source code but you don’t create an executable file – you create an intermediate form called ‘bytecode’ that still needs to be interpreted by what’s called a Java Virtual Machine (JVM). The reason for doing this is that bytecode is still portable – you can run Java bytecode on any device with a JVM.
In fact, this is exactly the way every Android device works. When you grab an app from Google Play, you’re downloading bytecode – the same bytecode, regardless of whether you’re using a Galaxy S5 or an el-cheapo $50 tablet. The devices can be completely different on the inside (CPU, RAM etc), but because they both run a JVM, they can load the same bytecode and run the app (assuming they’re running a similar Android OS).
But while you can’t build an executable, you can build a Java Archive (.jar) file and that file will launch from the command line – all you need is a Java Runtime Engine (JRE) that matches the JDK version you coded the app with. Clear as mud? Let’s use our InterestCalc app as a quick example.
First step, with your app loaded, choose Run | Build Project from the NetBeans IDE menu or just hit the
java –jar InterestCalc.jar
You might be thinking this is a bit clunky and that a standalone executable that doesn’t need a runtime engine would be better. Sure, it probably would – but you’d also need to compile separate versions for Windows, Mac OS X, Linux, Android, Unix and any other system you want to run the app on. With Java, as long as the user can get hold of a JRE for their OS, you only need the one .jar file and they can run it.
It might not seem like it, but right now, you have enough basic tools to write your own very simple apps. There’s much more to learn and we’ll be back next month, but in the meantime, hack around with this month’s project – modify it or even start your own project from scratch. Coding is all about practice – the more you do, the better you get!