The NetBeans Software
The NetBeans Software
You may have to drum your fingers and wait a while, as it's not the fastest thing in the world. To start a new project, click on File > New Project from the NetBeans menu at the top. You'll see the following dialogue box appear:
We're going to be create a Java Application, so select Java under Categories, and then Java Application under Projects. Click the Next button at the bottom to go to step two:
In the Project Name area at the top, type a Name for your Project. Notice how the text at the bottom changes to match your project name (in the text box to the right of Create Main Class): firstproject.Main If we leave it like that, the Class will have the name Main. Change it to FirstProject:
Now, the Class created will be called FirstProject, with a capital "F", capital "P". The package is also called firstproject, but with a lowercase "f" and lowercase "j". The default location to save your projects appears in the Project Location text box. You can change this, if you prefer. NetBeans will also create a folder with your project name, in the same location. Click the Finish button and NetBeans will go to work creating all the necessary files for you. When NetBeans returns you to the IDE, have a look at the Projects area in the top left of the screen (if you can't see this, click Window > Projects from the menu bar at the top of the software):
Click the plus symbol to expand your project, and you'll see the following:
Now expand Source Packages to see your project name again. Expand this and you'll see the Java file that is your source code.
This same source code should be displayed to the right, in the large text area. It will be called FirstProject.java. If you can't see a code window, simply double click FirstProject.java in your Projects window above. The code will appear, ready for you to start work. The coding window that appears should look like this (we've changed the author's name):
One thing to note here is that the class is called FirstProject: public class FirstProject { This is the same name as the java source file in the project window: FirstProject.java. When you run your programmes, the compiler demands that the source file and the class name match. So if your .java file is called firstProject but the class is called FirstProject then you'll get an error on compile. And all because the first one is lowercase "f" and the second one uppercase. Note that although we've also called the package firsproject, this is not necessary. We could have called the package someprogramme. So the name of the package doesn't have to be the same as the java source file, or the class in the source file: it's just the name of the java source file and the name of the class that must match. When you create a New Project in NetBeans, you'll notice that some text is greyed out, with lots of slashes and asterisks:
The greyed-out areas are comments. When the programme runs, comments are ignored. So you can type whatever you want inside of your comments. But it's usual to have comments that explain what is you're trying to do. You can have a single line comment by typing two slashes, followed by your comment: //This is a single line comment If you want to have more than one line, you can either do this: //This is a comment spreading //over two lines or more Or you can do this: /* This is a comment spreading over two lines or more */ In the comment above, note how it starts with /*. To end the comment, we have */ instead. There's also something called a Javadoc comment. You can see two of these in the coding image on the previous page. A Javadoc comment starts with a single forward slash and two asterisks (/**) and ends with an asterisk and one slash ( */ ). Each line of the comment starts with one asterisk:
/** *This is a Javadoc comment */ Javadoc comments are used to document code. The documented code can then be turned into an HTML page that will be helpful to others. You can see what these look like by clicking Run from the menu at the top of NetBeans. From the Run menu, select Generate Javadoc. There's not much to see, however, as you haven't written any code yet! At this stage of your programming career, you can delete the comments that NetBeans generates for you. Here's our code again with the comments deleted:
In the next part, you'll learn about the structure of the above code, and how to run your programmes. In the previous section, you tidied up your code a bit. Here's what your coding window should look like now:
You can see we have the package name first. Notice how the line ends with a semicolon. If you miss the semicolon out, the programme won't compile:
package firstproject; The class name comes next: public class FirstProject { } You can think of a class as a code segment. But you have to tell Java where code segments start and end. You do this with curly brackets. The start of a code segment is done with a left curly bracket { and is ended with a right curly bracket }. Anything inside of the left and right curly brackets belong to that code segment. What's inside of the left and right curly brackets for the class is another code segment. This one: public static void main( String[ ] args ) {
} The word "main" is the important part here. Whenever a Java programme starts, it looks for a method called main. (A method is just a chunk of code. You'll learn more about these later.) It then executes any code within the curly brackets for main. You'll get error messages if you don't have a main method in your Java programmes. But as its name suggest, it is the main entry point for your programmes. The blue parts before the word "main" can be ignored for now. (If you're curious, however, public means that the method can be seen outside of this class; static means that you don't have to create a new object; and void means it doesn't return a value - it just gets on with it. The parts between the round brackets of main are something called command line arguments. Don't worry if you don't understand any of that, though.) The important point to remember is that we have a class called FirstProject. This class contains a method called main. The two have their own sets of curly brackets. But the main chunk of code belongs to the class FirstProject. When you run a programme in NetBeans, it will run in the Output window at the bottom of your screen, just underneath your code. This is so that you don't have to start a terminal or console window - the Output window IS the console. There are various ways to run your programme in NetBeans. The easiest way is to press F6 on your Keyboard. You can also run programmes using the menus as the top of NetBeans. Locate the Run menu, then select Run Main Programme:
You can also click the green arrow on the NetBeans toolbar:
Another way to run your programmes is from the Projects window. This will ensure that the right source code is being run. Simply right click your java source file in the projects window and you'll see a menu appear. Select Run File.
Using one of the above methods, run your programme. You should see something happening in the Output window:
The second line in the Output window above is our code: My First Project. You can quickly run it again by clicking the two green arrows in the top left of the Output window. You can run the code you have so far, and turn it into a programme. It doesn't do anything, but it will still compile. So let's add one line of code just so that we can see how it works.
We'll output some text to a console window. Add the following line to your main method: public static void main( String[ ] args ) { System.out.println( "My First Project" ); } When you type the full stop after "System", NetBeans will try to help you by displaying a list of available options:
Double click out to add it to your code, then type another full stop. Again, the list of options appears:
Select println( ). What this does is to print a line of text to the output screen. But you need to place your text between the round brackets of println. Your text needs to go between a pair of double quotes:
Once you have your double quotes in place, type your text:
Notice that the line ends in a semicolon. Each complete line of code in Java needs a semicolon at the end. Miss it out and the programme won't compile. OK, we can now go ahead and test this programme out. First, though, save your work. You can click File > Save, or File > Save All. Or click the Save icon on the NetBeans toolbar. To end this section, click below to learn how to share your Java programmes with others. You can send your programmes to other people so that they can run them. To do that, you need to create a JAR file (Java Archive). NetBeans can do all this for you. From the Run menu at the top, select Clean and Build Main Project. When you do, NetBeans saves your work and then creates all the necessary files. It will create a folder called dist and place all the files in there. Have a look in the place where your NetBeans projects are and you'll see the dist folder:
You should see a JAR file and README text file. The text file contains instructions on how to run the programme from a terminal/console window. Now that you know how to run your java source files, let's do some programming. Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides. The data is given a name, so that it can be re-called whenever it is need. The name, and its value, is known as a Variable. We'll start with number values. To store a number in java, you have lots of options. Whole numbers such as 8, 10, 12, etc, are stored using the int variable. (The int stands for integer.) Floating point numbers like 8.4, 10.5, 12.8, etc, are stored using the double variable. You do the storing with an equals sign ( = ). Let's look at some examples (You can use your FirstProject code for these examples). To set up a whole number (integer), add the following to the main method of your project from the previous section: public static void main(String[ ] args) { int first_number; System.out.println("My First Project"); } So to tell Java that you want to store a whole number, you first type the word int, followed by a space. You then need to come up with a name for your integer variable. You can call them almost anything you like, but there are a few rules:
Variable names can't start with a number. So first_number is OK, but not 1st_number. You can have numbers elsewhere in the variable name, just not at the start. Variable names can't be the same as Java keywords. There are quite a lot of these, and they will turn blue in NetBeans, like int above. You can't have spaces in your variable names. The variable declaration int first number will get you an error. We've used the underscore character, but it's common practise to have the first word start with a lowercase letter and the second or subsequent words in uppercase: firstNumber, myFirstNumber Variable names are case sensitive. So firstNumber and FirstNumber are different variable names.
To store something in the variable called first_number, you type an equals sign and then the value you want to store: public static void main(String[ ] args) { int first_number; first_number = 10; System.out.println("My First Project"); } So this tells java that we want to store a value of 10 in the integer variable that we've called first_number. If you prefer, you can do all this on one line: public static void main(String[ ] args) { int first_number = 10; System.out.println("My First Project"); } To see all this in action, change the println method slightly to this: System.out.println( "First number = " + first_number ); What we now have between the round brackets of println is some direct text enclosed in double quotes: ("First number = " We also have a plus sign, followed by the name of our variable: + first_number ); The plus sign means "join together". So we're joining together the direct text and the name of our variable. The joining together is known as concatenation. Your coding window should now look like this (note how each line of code ends with a semicolon):
Run your programme and you should see the following in the Output window at the bottom:
So the number that we stored in the variable called first_number is output after the equals sign. Let's try some simple addition. Add two more int variables to your code, one to store a second number, and one to store an answer: int first_number, second_number, answer; Notice how we have three variable names on the same line. You can do this in Java, if the variables are of the same type (the int type, for us). Each variable name is then separated by a comma. We can then store something in the new variables: first_number = 10; second_number = 20; answer = first_number + second_number; For the answer variable, we want to add the first number to the second number. Addition is done with the plus ( + ) symbol. Java will then add up the values in first_number and second_number. When it's finished it will store the total in the variable on the left of the equals sign. So instead of assigning 10 or 20 to the variable name, it will add up and then do the assigning. In case that's not clear, here's what happens:
The above is equivalent to this: answer = 10 + 20; But Java already knows what is inside of the two variables, first_number and second_number, so you can just use the names. Now change your println method slightly to this: System.out.println("Addition Total = " + answer ); Again, we are combining direct text surrounded by double quotes with a variable name. Your coding window should look like this:
When you run your programme you should get the following in the output window:
Added these two numbers together Stored the result of the addition in a third variable Printed out the result
You can also use numbers directly. Change the answer line to this: answer = first_number + second_number + 12; Run your programme again. What printed out? Was it what you expected? You can store quite large numbers in the int variable type. The maximum value is 2147483647. If you want a minus number the lowest value you can have is -2147483648. If you want larger or smaller numbers you can use another number variable type: double. You'll meet them in the next part of the course.
Run your programme again. The output window should look like this:
Try changing the values stored in first_number and second_number. Use any values you like. Run your programme and see what happens. In the next part, you'll learn about two more Java variable types: short and float. Two more variable types you can use are short and float. The short variable type is used to store smaller number, and its range is between minus 32,768 and plus 32,767. Instead of using int in our code on the previous pages, we could have used short instead. You should only use short if you're sure that the values that you want to hold don't go above 32, 767 or below -32,768. The double value we used can store really big numbers of the floating point variety. Instead of using double, float can be used. When storing a value in a float variable, you need the letter "f" at the end. Like this: float first_number, second_number, answer; first_number = 10.5f; second_number = 20.8f; So the letter "f" goes after the number but before the semicolon at the end of the line. To see the difference between float and double, see below.
Simple Arithmetic With the variables you've been using, you can use the following symbols to do calculations: + (the plus sign) - (the minus sign)
* (the multiplication sign is the asterisk sign) / (the divide sign is the forward slash) Try this exercise: Delete the plus symbol that is used to add first_number and second_number. Replace it with the symbols above, first the minus sign, then the multiplication sign, and then the divide. The answer to the final one, the divide, should give you a really big number. The number you should get for divide is 0.5048076923076923. This is because you used the double variable type. However, change the double to float. Then add the letter "f" to the end of the numbers. So your code should look like this:
When you run the above code, the answer is now 0.5048077. Java has taken the first 6 numbers after the point and then rounded up the rest. So the double variable type can hold more numbers than float. (Double is a 64 bit number and float is only 32 bit.) In the next lesson, you'll learn about the importance of Operator Precedence. You can, of course, calculate using more than two numbers in Java. But you need to take care of what exactly is being calculated. Take the following as an example: first_number = 100; second_number = 75; third_number = 25; answer = first_number - second_number + third_number; If you did the calculation left to right it would be 100 - 75, which is 25. Then add the third number, which is 25. The total would be 50. However, what if you didn't mean that? What if you wanted to add the second and third numbers together, and then deduct the total from the first number? So 75 + 25, which is 100. Then deduct that from the first number, which is 100. The total would now be 0. To ensure that Java is doing what you want, you can use round brackets. So the first calculation would be: answer = (first_number - second_number) + third_number; Here's the coding window so that you can try it out:
The second calculation is this: answer = first_number - (second_number + third_number); And here's the code window:
Now let's try some multiplication and addition. Change your math symbols (called Operators) to plus and multiply: answer = first_number + second_number * third_number; Delete all your round brackets, and then run your programme. With no brackets, you'd think Java would calculate from left to right. So you'd think it would add the first number to the second number to get 175. Then you'd think it would multiply by the third number, which is 25. So the answer would be 4375. Run the programme, though. The answer that you actually get is 1975! So what's going on? The reason Java got the "wrong" answer was because of Operator Precedence. Java treats some mathematical symbols as more important than others. It sees multiplication as having a priority over addition, so it does this first. It then does the addition. So Java is doing this: answer = first_number + (second_number * third_number); With the round brackets in place, you can see that second number is being multiplied by third number. The total is then added to the first number. So 75 multiplied by 25 is 1875. Add 100 and you get 1975.
If you want it the other way round, don't forget to "tell" Java by using round brackets: answer = (first_number + second_number) * third_number; Division is similar to multiplication: Java does the dividing first, then the addition or subtraction. Change your answer line to the following: answer = first_number + second_number / third_number; The answer you get is 103. Now add some round brackets: answer = (first_number + second_number) / third_number; The answer this time will be 7. So without the round brackets, Java does the dividing first, and then adds 100 to the total - it doesn't work from left to right. Here's a list on Operator Precedence
Multiply and Divide - Treated equally, but have priority over Addition and Subtraction Add and Subtract - Treated equally but have a lower priority than multiplication and division
So if you think Java is giving you the wrong answer, remember that Operator Precedence is important, and add some round brackets. In the next part, we'll take a look at how to store text values using Java. As well as storing number values, variables can hold text. You can store just one character, or lots of characters. To store just one character, the char variable is used. Usually, though, you'll want to store more than one character. To do so, you need the string variable type. Start a new project for this by clicking File > New Project from the menu bar at the top of NetBeans. When the New Project dialogue box appears, make sure Java and Java Application are selected:
Click Next and type StringVars as the Project Name. Make sure there is a tick in the box for Create Main Class. Then delete Main after stringvars, and type StringVariables instead, as in the following image:
So the Project Name is StringVars, and the Class name is StringVariables. Click the Finish button and your coding window will look like this (we've deleted all the default comments). Notice how the package name is all lowercase (stringvars) but the Project name was StringVars.
To set up a string variable, you type the word String followed by a name for your variable. Note that there's an uppercase "S" for String. Again, a semicolon ends the line: String first_name; Assign a value to your new string variable by typing an equals sign. After the equals sign the text you want to store goes between two sets of double quotes: first_name = "William"; If you prefer, you can have all that on one line:
String first_name = "William"; Set up a second string variable to hold a surname/family name: String family_name = "Shakespeare"; To print both names, add the following println( ): System.out.println( first_name + " " + family_name ); In between the round brackets of println, we have this: first_name + " " + family_name We're saying print out whatever is in the variable called first_name. We then have a plus symbol, followed by a space. The space is enclosed in double quotes. This is so that Java will recognise that we want to print out a space character. After the space, we have another plus symbol, followed by the family_name variable. Although this looks a bit messy, we're only printing out a first name, a space, then the family name. Your code window should look like this:
Run your programme and you should see this in the Output window:
If you are storing just a single character, then the variable you need is char (lowercase "c"). To store the character, you use single quotes instead of double quotes. Here's our programme again, but this time with the char variable:
If you try to surround a char variable with double quotes, NetBeans will underline the offending code in red, giving you "incompatible type" errors. You can, however, have a String variable with just a single character. But you need double quotes. So this is OK: String first_name = "W"; But this is not: String first_name = 'W'; The second version has single quotes, while the first has double quotes. There are lot more to strings, and you'll meet them again later. For now, let's move on and get some input from a user. One of the strengths of Java is the huge libraries of code available to you. This is code that has been written to do specific jobs. All you need to do is to reference which library you want to use, and then call a method into action. One really useful class that handles input from a user is called the Scanner class. The Scanner class can be found in the java.util library. To use the Scanner class, you need to reference it in your code. This is done with the keyword import. import java.util.Scanner; The import statement needs to go just above the Class statement: import java.util.Scanner; public class StringVariables {
} This tells java that you want to use a particular class in a particular library - the Scanner class, which is located in the java.util library. The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of code. It doesn't do anything until you create a new object from it.) To create a new Scanner object the code is this: Scanner user_input = new Scanner( System.in ); So instead of setting up an int variable or a String variable, we're setting up a Scanner variable. We've called ours user_input. After an equals sign, we have the keyword new. This is used to create new objects from a class. The object we're creating is from the Scanner class. In between round brackets we have to tell java that this will be System Input (System.in). To get the user input, you can call into action one of the many methods available to your new Scanner object. One of these methods is called next. This gets the next string of text that a user types on the keyboard:
String first_name; first_name = user_input.next( ); So after our user_input object we type a dot. You'll then see a popup list of available methods. Double click next and then type a semicolon to end the line. We can also print some text to prompt the user: String first_name; System.out.print("Enter your first name: "); first_name = user_input.next( ); Notice that we've used print rather than println like last time. The difference between the two is that println will move the cursor to a new line after the output, but print stays on the same line. We'll add a prompt for a family name, as well: String family_name; System.out.print("Enter your family name: "); family_name = user_input.next( ); This is the same code, except that java will now store whatever the user types into our family_name variable instead of our first_name variable. To print out the input, we can add the following: String full_name; full_name = first_name + " " + family_name; System.out.println("You are " + full_name); We've set up another String variable, full_name. We're storing whatever is in the two variables first_name and family_name. In between the two, we've added a space. The final line prints it all out in the Output window. So adapt your code so that it matches that in the next image:
Run your programme until your Output window displays the following:
Java is now pausing until you enter something on your keyboard. It won't progress until you hit the enter key. So left click after "Enter your first name:" and you'll see your cursor flashing away. Type a first name, and then hit the enter key on your keyboard. After you hit the enter key, java will take whatever was typed and store it in the variable name to the left of the equals sign. For us, this was the variable called first_name. The programme then moves on to the next line of code:
The user input has now finished, and the rest of the programme executes. This is the output of the two names. The final result should like this:
So we used the Scanner class to get input from a user. Whatever was typed was stored in variables. The result was then printed to the Output window. In the next part, we'll take a brief look at Option Panes. Another useful class for accepting user input, and displaying results, is the JOptionPane class. This is located in the javax.swing library. The JOptionPane class allows you to have input boxes like this one:
Let's adapt our code from the previous section and have some option panes. The first thing to do is to reference the library we want to use: import javax.swing.JOptionPane; This tells java that we want to use the JOptionPane class, located in the javax.swing library. You can start a new project for this, if you prefer not to adapt your previous code. (You should know how to create a new project by now. Just remember to change the name of the Class from Main to something else. We're going to have the class name InputBoxes for ours. Our package name will be userinput.) Add the import line to your new project, and your code window should look like something like this:
(The reason for the wavy underline is that we haven't used the JOptionPane class yet. It will go away once we do.) To get an input box that the user can type into, we can use the showInputDialog method of JOptionPane. We'll store the input straight into a first name variable again, just like last time. So add the following line to your main method: String first_name; first_name = JOptionPane.showInputDialog("First Name"); As soon as you type a full stop after JOptionPane you will see the following popup list:
Double click showInputDialog. In between the round brackets of showInputDialog type the message that you want displayed above the input text box. We've typed "First name". Like all strings, it needs to go between double quotes. Add the following code so that we can get the user's family name: String family_name; family_name = JOptionPane.showInputDialog("Family Name"); Join the two together, and add some text: String full_name; full_name = "You are " + first_name + " " + family_name; To display the result in a message box, add the following: JOptionPane.showMessageDialog( null, full_name ); This time, we want showMessageDialog from the popup list. In between the round brackets we first have the word null. This is a java keyword and just means that the message box is not associated with anything else in the programme. After a comma comes the text we want to display in the message box. The whole of your code should look like this:
Notice the line at the bottom of the code: System.exit(0); As its name suggests, this ensures that the programme exits. But it also tidies up for us, removing all the created objects from memory. Now run your code. (Another quick way to run your programme in NetBeans is by right-clicking anywhere inside of the coding window. From the menu that appears, select Run File.) You'll see the First Name input box. Type something into it, then click OK:
When the Family Name input box appears, type a family name and click OK:
Exercise Input boxes and Message boxes can be formatted further. Try the following for your Input boxes: showInputDialog("First Name", "Enter Your First Name"); showInputDialog("Family", "Enter Your Family Name");
Exercise For your Message boxes try this (yours should be on one line): showMessageDialog(null, full_name, "Name", JOptionPane.INFORMATION_MESSAGE);
Exercise Instead of JOptionPane.INFORMATION_MESSAGE try these: ERROR_MESSAGE PLAIN_MESSAGE QUESTION_MESSAGE WARNING_MESSAGE Exercise Input boxes are not just used for text: they can accept numbers as well. Write a programme that prompts the user for two numbers, the breadth of a rectangle and the height of a rectangle. Use a message box to calculate the area of the rectangle. (Remember: the area of a rectangle is its breadth multiplied by the height.) However, you'll need some extra help for this exercise.
Help for the Exercise You have to use the String variable to get your numbers from the user: String breadth; breadth = JOptionPane.showInputDialog("Rectangle Breadth"); However, you can't multiply two strings together. You need to convert the Strings to integers. You can convert a string to an integer like this: Integer.parseInt( string_to_convert )
So you type Integer then a full stop. After the stop, type parseInt( ). In between the round brackets of parseInt, type the name of the string variable you're trying to convert. Set up an int variable for the area. You can then multiply and assign on the same line; int area = Integer.parseInt( string_one ) * Integer.parseInt( string_two); For the message box, use concatenation: "answer = " + area You can use any of the MESSAGE symbols for your message box. The programming you're doing now is sequential programming, meaning the code is executed from top to bottom. It's very linear, in that each and every line of code will be read, starting with the first line of code you write and ending at the last line. But you don't always want your programmes to work like that. Often, you want code to be executed only if certain conditions are met. For example, you might want one message to display if a user is below the age of 18 and a different message if he or she is 18 or older. You want to control the flow of the programme for yourself. You can do this with conditional logic. Conditional logic is mainly about the IF word: IF user is less than 18 then display this message; IF user is 18 or older then display that message. Fortunately, it's very easy to use conditional logic in Java. Let's start with IF Statements.
IF Statements Executing code when one thing happens rather than something else is so common in programming that that the IF Statement has been developed. The structure of the IF Statement in Java is this: if ( Statement ) { } You start with the word IF (in lowercase) and a pair of round brackets. You then use a pair of curly brackets to section off a chunk of code. This chunk of code is code that you only want to execute IF your condition is met. The condition itself goes between round brackets: if ( user < 18 ) { } This condition says "IF user is less than 18". But instead of saying "is less than" we use the shorthand notation of the left-pointing angle bracket ( < ). IF the user is less than 18 then we want something to happen, to display a message, for example: if ( user < 18 ) {
//DISPLAY MESSAGE } If the user is not less than 18 then the code between the curly brackets will be skipped, and the programme continues on its way, downwards towards the last line of code. Whatever you type between the curly brackets will only be executed IF the condition is met, and this condition goes between the round brackets. Before we try this out, another shorthand notation is this symbol >. The right-pointing angle bracket means "greater than". Our IF Statement above can be amended slightly to check for users who are greater than 18: if ( user > 18 ) { //DISPLAY MESSAGE } The only thing new in this code is the > symbol. The condition now checks for users who are greater than 18. But the condition doesn't check for people who are exactly 18, just those greater than 18. If you want to check for those who are 18 or over, you can say "greater than or equal to". The symbols for this are the greater than sign ( > ) followed by an equals sign ( = ): if ( user >= 18 ) { //DISPLAY MESSAGE }
You can also check for "less than or equal to" in a similar way: if ( user <= 18 ) { //DISPLAY MESSAGE } The above code contains a less than symbol ( < ) followed by the equals sign. Let's try all this out in a simple programme. Start a new project by clicking File > New Project from the menu bar in NetBeans. You can call your package and class names anything you like. Enter the following code (our package name is conditionallogic and the Class is called IFStatements):
We've set up an integer variable, and assigned a value of 17 to it. The IF statement checks for "less than 18". So the message between the curly brackets should be printed out. Run your programme and check it out. (NetBeans has a habit of running the programme in bold text in the Projects window and not the code you have displayed. To run the code in your coding window, right click anywhere in the code. From the menu that appears select Run File.) You should see this in your Output window:
Now change the value for the user variable from 17 to 18. Run your programme again. You should see this:
So the programme runs OK, with no error messages. It's just that nothing gets printed out. The reason is that the message code is between the curly brackets of the IF Statement. And the IF Statement is checking for values less than 18. IF the condition is not met, Java ignores the curly brackets altogether and moves on. Exercise Replace your "less than" symbol with the "less than or equal to" symbols. Change your message to suit, something like "user is less than or equal to 18". Run your programme again. Do you see the message?
Exercise Change the user value to 20. Run your programme again. Do you still see the message?
You can have more than one IF Statement in your code. Try the following code:
This time, we have two IF Statements. The first tests for values less than or equal to 18. The second tests for values greater than 18. When the code is run with a value of 18 or less for the user variable, the Output is this:
So only one of the IF Statements will Output a print line. And it all depends on what the value of the user variable is.
Instead of using two IF Statements, you can use an IF ELSE Statement instead. Here's the structure of an IF ELSE statement: if ( condition_to_test ) { } else { } The first line starts with if, followed by the condition you want to test for. This goes between two round brackets. Again, curly brackets are used to section off the different choices. The second choice goes after the word else and between its own curly brackets. Here's our code again that checks a user's age:
So there are only two choices here: either the user is 18 or younger, or the user is older than that. Adapt your code to match that in the image above and try it out. You should find that the first message prints out. Now change the value of the user variable to 20 and run the code again. The message between the ELSE curly brackets should display in the Output window.
IF ELSE IF You can test for more than two choices. For example, what if we wanted to test for more age ranges, say 19 to 39, and 40 and over? For more than two choices, the IF ELSE IF statement can be used. The structure of an IF ELSE IF is this: if ( condition_one ) { } else if ( condition_two ) { } else { } The new part is this:
else if ( condition_two ) { } So the first IF tests for condition number one (18 or under, for example). Next comes else if, followed by a pair of round brackets. The second condition goes between these new round brackets. Anything not caught by the first two conditions will be caught be the final else. Again, code is sectioned off using curly brackets, with each if, else if, or else having its own pair of curly brackets. Miss one out and you'll get error messages. Before trying out some new code, you'll need to learn some more conditional operators. The ones you have used so far are these: > Greater Than < Less Than >= Greater Than or Equal To <= Less Than or Equal To Here's four more you can use: && AND || OR == HAS A VALUE OF ! NOT The first one is two ampersand symbols, and is used to test for more than one condition at the same time. We can use it to test for two age ranges: else if ( user > 18 && user < 40 ) Here, we want to check if the user is older than 18 but younger than 40. Remember, we're trying to check what is inside of the user variable. The first condition is "Greater than 18" ( user > 18 ). The second condition is "Less than 40" ( user < 40). In between the two we have our AND operator ( &&). So the whole line says "else if user is greater than 18 AND user is less than 40." We'll get to the other three conditional operators in a moment. But here's some new code to try out:
Run your programme and test it out. You should be able to guess what it will print out before running it. Because we have a value of 21 for the user variable the message between the curly brackets of else if will display in the Output window. Exercise Change the value of the user variable from 21 to 45. The message for the else section of the code should now display.
You can add as many else if parts as you want. Suppose we wanted to check if the user was either 45 or 50. We can use two of the new conditional operators above. We can check if the user variable "has a value of 45" OR "has a value of 50": else if (user == 45 || user == 50) To test if the user variable has a value of something you use two equal signs, with no space between them. Java will test for that value and no other values. Because want to test for the user being 50 as well, we can have another condition in the same round brackets: user == 50. This just says "test if the user variable has a value of 50". In between the two conditions, we have the OR operator. This is two pipe characters, which is just to the left of the letter "z" on a UK keyboard. Again, there's no space between the two. The whole of the line above says "Else if the user has a value of 45 OR the user has a value of 50". Here's our code with the new else if part:
Try it out for yourself. Change the value of the user variable to 45 and run your code. Then change it to 50 and run the code again. In both cases the new message should display. The various conditional operators can be tricky to use. But you're just testing a variable for a particular condition. It's simply a question of picking the right conditional operator or operators for the job.
Nested IF Statements You can nest IF Statements. (This also applies to IF ... ELSE and IF ... ELSE IF statements.) Nesting an IF Statement just means putting one IF Statement inside of another. For example, suppose you want to find out if somebody is younger than 18, but older than 16. You want to display a different message for the over 16s. You start with the first IF Statement: if ( user < 19 ) { System.out.println( "18 or younger"); } To check for over 16, you can place a second IF Statement inside of the one you already have. The format is the same: if ( user < 19 ) { if ( user > 16 && user < 19 ) { System.out.println( "You are 17 or 18"); } } So the first IF Statement catches the user variable if it's less than 19. The second IF Statement narrows the user variable down even further, for ages over 16 and under 19. To print different messages, you can have an IF ... ELSE statement instead of the IF Statement above: if ( user < 19 ) { if ( user > 16 && user < 19 ) { System.out.println( "You are 17 or 18"); } else { System.out.println( "16 or younger"); } } Notice where all the curly brackets are in the code: get one wrong and your programme won't run. Nested IF Statements can be tricky, but all you're trying to do is to narrow down the choices. In the next section, you'll about the Boolean variable type.
Boolean Values
A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable type for Boolean values: boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ). If you want to check if a variable "has a value of" something, you need two equal signs ( = =). Try this simple code: boolean user = true; if ( user == true) { System.out.println("it's true"); } else { System.out.println("it's false"); } So the first IF Statement checks if the user variable has a value of true. The else part checks if it is false. You don't need to say "else if ( user = = false)". After all, if something is not true then it's false. So you can just use else: there's only two choices with boolean values. The only other conditional operator on our lists is the NOT operator. You can use this with boolean values. Have a look at the following code: boolean user = true; if ( !user ) { System.out.println("it's flase"); } else { System.out.println("it's true"); } It's almost the same as the other boolean code, except for this line: if ( !user ) { This time, we have our NOT operator before the user variable. The NOT operator is a single exclamation mark ( ! ) and it goes before the variable you're tying to test. It's testing for negation, which means that it's testing for the opposite of what the value actually is. Because the user variable is set to true then !user will test for false values. If user was set to false then !user would test for true values. Think of it like this: if something is NOT true then what is it? Or if it's NOT false then what?
Another way to control the flow of your programmes is with something called a switch statement. A switch statement gives you the option to test for a range of values for your variables. They can be used instead of long, complex if else if statements. The structure of the switch statement is this: switch ( variable_to_test ) { case value: code_here; break; case value: code_here; break; default: values_not_caught_above; } So you start with the word switch, followed by a pair of round brackets. The variable you want to check goes between the round brackets of switch. You then have a pair of curly brackets. The other parts of the switch statement all go between the two curly brackets. For every value that you want to check, you need the word case. You then have the value you want to check for: case value: After case value comes a colon. You then put what you want to happen if the value matches. This is your code that you want executed. The keyword break is needed to break out of each case of the switch statement. The default value at the end is optional. It can be included if there are other values that can be held in your variable but that you haven't checked for elsewhere in the switch statement. If all of that is confusing, here's some code to try out. You can either start a new project for this, or just comment out the code you have. A quick way to comment out code in NetBeans is from the toolbar at the top. First, highlight the code you want to comment out. Then click the comment icon:
The first thing the code does is to set a value to test for. Again, we've set up an integer variable and called it user. We've set the value to 18. The switch statement will check the user variable and see what's in it. It will then go through each of the case statements in turn. When it finds one that matches, it will stop and execute the code for that case. It will then break out of the switch statement. Try the programme out. Enter various values for the user variable and see what happens. Sadly, you can't test for a range of values after case, just the one value. So you can't do this: case (user <= 18): But you can do this: case 1: case 2: case 3: case 4: So the above line tests for a range of values, from 1 to 4. But you have to "spell out" each value. (Notice where all the case and colons are.) To end this section on conditional logic, try these exercises.
Exercise Write a programme that accepts user input from the console. The programme should take a number and then test for the following age ranges: 0 to 10, 11 to 20, 21 to 30, 30 and over. Display a message in the Output window in the following format: user_age + " is between 21 and 30" So if the user enters 27 as the age, the Output window should be this:
If the user is 30 or over, you can just display the following message: "Your are 30 or over"
Help for this exercise To get string values from the user, you did this: String age = user_input.next( ); But the next( ) method is used for strings. The age you are getting from the user has to be an integer, so you can't use next( ). There is, however, a similar method you can use: nextInt( ).
Exercise If you want to check if one String is the same as another, you can use a Method called equals. String user_name = "Bill"; if ( user_name.equals( "Bill" ) ) { //DO SOMETHING HERE } In the code above, we've set up a String variable and called it user_name. We've then assigned a value of "Bill" to it. In between the round brackets of IF we have the variable name again, followed by a dot. After the dot comes the word "equals". In between another pair of round brackets you type the string you're trying to test for. NOTE: When checking if one string is the same as another, they have to match exactly. So "Bill" is different from "bill". The first has an uppercase letter "B" and the second has a lowercase "b".
For this exercise, write a programme that asks a user to choose between four colours: black, white, red, or blue. Use IF ELSE IF statements to display one of the following messages, depending on which colour was chosen: BLACK "You must be a Goth!" WHITE "You are a very pure person" RED "You are fun and outgoing" BLUE "You're not a Chelsea fan, are you?" When your programme ends, the Output window should look like something like this:
OK, let's move on and have a look at loops. We'll be upping the pace a bit in this next section, so hang on to your hats! As we mentioned earlier, the programming you are doing now is sequential programming. This means that flow is downward, from top to bottom, with every line of code being executed, unless you tell Java otherwise. You saw in the last section that one way to "tell" Java not to execute every line is by using IF Statement to section off areas of code. Another way to interrupt the flow from top to bottom is by using loops. A programming loop is one that forces the programme to go back up again. If it is forced back up again you can execute lines of code repeatedly. As an example, suppose you wanted to add up the numbers 1 to 10. You could do it quite easily in Java like this: int addition = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10; But you wouldn't really want to use that method if you needed to add up the numbers 1 to a 1000. Instead, you can use a loop to go over a line of code repeatedly until you've reached 1000. Then you can exit the loop and continue on your way.
Java For Loops We'll start with For Loops, one of the most common types of loops. The "For" part of "For Loop" seems to have lost its meaning. But you can think of it like this: "Loop FOR a set number of times." The structure of the For Loop is this: for ( start_value; end_value; increment_number ) { //YOUR_CODE_HERE } So after the word "for" (in lowercase) you have a pair of round brackets. Inside of the round brackets you need three things: the start value for the loop, the end value for the loop, and a way to get from one number to another. This is called the increment number, and is usually 1. But it doesn't have to be. You can go up in chunks of 10, if you want.
After the round brackets you need a pair of curly brackets. The curly brackets are used to section off the code that you want to execute repeatedly. An example might clear things up. Start a new project for this. Call the Project and Class anything you like. (We've called our Project "loops", and the Class "ForLoops"). Now add the following code:
We start by setting up an integer variable, which we've called loopVal. The next line sets up another integer variable. This variable will be used for the end value of the loop, and is set to 11. What we're going to do is to loop round printing out the numbers from 0 to 10. Inside the round brackets of the for loop, we have this: loopVal =0; loopVal < end_value; loopVal++ The first part tells Java at what number you want to start looping. Here, we're assigning a value of zero to the loopVal variable. This will be the first number in the loop. The second part uses some conditional logic: loopVal < end_value This says "loopVal is less than end_value". The for loop will then keep going round and round while the value inside the loopVal variable is less than the value in the variable called end_value. As long as it's true that loopVal is less than end_value, Java will keep looping over the code between the curly brackets. The final part between the round brackets of the for loop is this: loopVal++ What we're doing here is telling Java how to go from the starting value in loopVal to the next number in the sequence. We want to count from 0 to 10. The next number after 0 is 1. loopVal++ is a shorthand way of saying "add 1 to the value in the variable". Instead of saying loopVal++ we could have wrote this:
loopVal = loopVal + 1 To the right of the equals sign we have loopVal + 1. Java will then add 1 to whatever is currently stored in the loopVal variable. Once it has added 1 to the value, it will store the result inside of the variable to the left of the equals sign. This is the loopVal variable again. The result is that 1 keeps getting added to loopVal. This is called incrementing the variable. It is so common that the shorthand notation variable++ was invented: int some_number = 0; some_number++; The value of some_number will be 1 when the code above is executed. It is the short way of saying this: int some_number = 0; some_number = some_number + 1; To recap then, our for loop is saying this: Loop Start value: 0 Keep Looping While: Start value is less than 11 How to advance to the end value: Keep adding 1 to the start value Inside of the curly brackets of the for loop we have this: System.out.println("Loop Value = " + loopVal); Whatever is currently inside of the loopVal variable will be printed out, along with some text. Run your programme and you should see this in the Output window:
So we've trapped the programme in a loop, and forced it to go round and round. Each time round the loop, 1 gets added to the loopVal variable. The loop keeps going round and round while the value inside of loopVal is less than the value in end_value. Whatever is inside of the loop's curly brackets is the code that will be executed over and over. And that is the whole point of the loop: to execute the curly bracket code over and over. Here's some code that adds up the numbers 1 to 10. Try it out:
The answer you should get in the Output window is 55. The code itself is more or less the same as the previous for loop. We have the same two variables set up at the top, loopVal and end_value. We also have a third integer variable, which we've called addition. This will hold the value of the 1 to 10 sum. In between the round brackets of the for loop, it's almost the same as last time: we're looping while loopVal is less than end_value; and we're adding 1 to the loopVal variable each time round the loop (loopVal++). The only difference is that the starting value is now 1 (loopVal=1). In between the curly brackets, we only have one line of code: addition = addition + loopVal; This single line of code adds up the numbers 1 to 10. If you're confused as to how it works, start to the right of the equals sign: addition + loopVal; The first time round the loop, the addition variable is holding a value of 0. The variable loopVal, meanwhile, is holding a value of 1 (its starting value). Java will add 0 to 1. Then it will store the result to the variable on the left of the equals sign. Again, this is the addition variable. Whatever was previously being held in the addition variable (0) will be erased, and replaced with the new value (1). The second time round the loop, the values in the two variables are these (the values are between round brackets): addition (1) + loopVal (2); 1 + 2 is obviously 3. So this is the new value that will be stored to the left of the equals sign. The third time round the loop, the new values are these: addition (3) + loopVal (3); Java adds the 3 + 3 and stores 6 to the left of the equals sign. It keeps going round and round until the loop ends. The result is 55. (Notice that our print line is outside of the for loop, after the final curly bracket of the loop.)
Exercise Change you code so that the loop adds up the numbers 1 to a 100. The answer you should get is 5050.
Exercise Write a times table programme. The programme should ask a user to input a number. This number is then used as the times table. So if the user enters 10, the 10 times table should be displayed. Your Output window should look something like this, when your programme is run.
Help for this Exercise Your for loop only needs two lines of code between the curly brackets, and one of those is the print line. You only need a single line to calculate the answers for your times table. You should already know how to get the number from the user. This can be used in your loop's curly brackets to work out the answer to your multiplication. Your times table only needs to go from 1 to 10, like ours does in the image above.
Exercise Use a for loop to print out the odd numbers from 1 to 10. (For the easy way to do this exercise, think about the increment value of the loop, which is the third item between the round brackets.) One of the hard ways to do the exercise above is by using an operator you haven't yet met - the modulus operator. Modulus is when you divide by a number and keep the remainder. So 10 Mod 3 is 1, because 10 divide by 3 is 3. The remainder is 1, and that's what you keep. The Modulus operator in Java is the percentage sign, rather confusingly. It's used like this: int remainder; int total = 10 remainder = total %3 So the number (or variable) you want to divide up goes first. You then type a percentage sign, followed by your divider number. The answer is the remainder.
In the exercise above, you could use 2 as the Mod number, and then use an IF Statement in your for loop to test what the remainder is. (Can you see why 2 should be the Mod number?) In the next part, we'll take a look at Java while loops. Another type of loop you can use in Java is called the while loop. While loops are a lot easier to understand than for loops. Here's what they look like: while ( condition ) { } So you start with the word "while" in lowercase. The condition you want to test for goes between round brackets. A pair of curly brackets comes next, and the code you want to execute goes between the curly brackets. As an example, here's a while loop that prints out some text (Try the code out for yourself): int loopVal = 0; while ( loopVal < 5) { System.out.println("Printing Some Text"); loopVal++; }
The condition to test is between the round brackets. We want to keep looping while the variable called loopVal is less than 5. Inside of the curly brackets our code first prints out a line of text. Then we need to increment the loopVal variable. If we don't we'll have an infinite loop, as there is no way for loopVal to get beyond its initial value of 0. Although we've used a counter (loopVal) to get to the end condition, while loops are best used when you don't really need a counting value, but rather just a checking value. For example, you can keep looping while a key on the keyboard is not pressed. This is common in games programme. The letter "X" can pressed to exit the while loop (called the game loop), and hence the game itself. Another example is looping round a text file while the end of the file has not been reached.
Do ... While Related to the while loop is the do while loop. It looks like this: int loopVal = 0; do { System.out.println("Printing Some Text"); loopVal++;
} while ( loopVal < 5 ); Again, Java will loop round and round until the end condition is met. This time, the "while" part is at the bottom. But the condition is the same - keep looping while the value inside of the variable called loopVal is less than 5. The difference between the two is the code between the curly brackets of do while will get executed at least once. With the while loop, the condition could already be met. Java will then just bail out of your loop, and not even execute your curly bracket code. To test this out, try the while loop first. Change the value of your loopVal variable to 5, and then run the code. You should find that the text doesn't get printed. Now try the do loop with a value of 5 for loopVal. The text will print once and then Java will bail out of the loop.
OK, we'll leave looping there. It is a subject you need to get grips with. But don't worry if you're not completely perfect with them - you'll learn as we go along. In the next section, we'll take a look at something called an array. A programming concept you just have to get used to if you're to code effectively is the array. In this section, you'll learn what arrays are, and how to use them.
What is an Array? So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number, and the string variables just one long string of text. An array is a way to hold more than one value at a time. It's like a list of items. Think of an array as the columns in a spreadsheet. You can have a spreadsheet with only one column, or lots of columns. The data held in a single-list array might look like this:
Like a spreadsheet, arrays have a position number for each row. The positions in an array start at 0 and go up sequentially. Each position in the array can then hold a value. In the image above array position 0 is holding a value of 10, array position 1 is holding a value of 14, position 2 has a value of 36, and so on. To set up an array of number like that in the image above, you have to tell Java what kind of data is going in to your array (integers, strings, boolean values, etc). You then need to say how many positions the array has. You set them up like this: int[ ] aryNums; The only difference between setting up a normal integer variable and an array is a pair of square brackets after the data type. The square brackets are enough to tell Java that you want to set up an array. The name of the array above is aryNums. Just like normal variables, you can call them almost anything you like (with the same exceptions we mentioned earlier).
But this just tells Java that you want to set up an integer array. It doesn't say how many positions the array should hold. To do that, you have to set up a new array object: aryNums = new int[6]; You start with your array name, followed by the equals sign. After the equals sign, you need the Java keyword new, and then your data type again. After the data type come a pair of square brackets. In between the square brackets you need the size of the array. The size is how many positions the array should hold. If you prefer, you can put all that on one line: int[ ] aryNums = new int[6]; So we are telling Java to set up an array with 6 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 6 positions will be zero ( 0 ). To assign values to the various positions in an array, you do it in the normal way: aryNums[0] = 10; Here, a value of 10 is being assigned to position 0 in the array called aryNums. Again, the square brackets are used to refer to each position. If you want to assign a value of 14 to array position 1, the code would be this: aryNums[1] = 14; And to assign a value of 36 to array position 2, it's this: aryNums[2] = 36; Don't forget, because arrays start at 0, the third position in an array has the index number 2. If you know what values are going to be in the array, you can set them up like this instead: int[ ] aryNums = { 1, 2, 3, 4 }; This method of setting up an array uses curly brackets after the equals sign. In between the curly brackets, you type out the values that the array will hold. The first value will then be position 0, the second value position 1, and so on. Note that you still need the square brackets after int, but not the new keyword, or the repetition of the data type and square brackets. But this is just for data types of int values, string, and char values. Otherwise, you need the new keyword. So you can do this: String[ ] aryStrings = {"Autumn", "Spring", "Summer", "Winter" }; But not this: boolean[ ] aryBools = {false, true, false, true}; To set up a boolean array you still need the new keyword: boolean[ ] aryBools = new boolean[ ] {false, true, false, true};
To get at the values held in your array, you type the name of the array followed by an array position in square brackets. Like this: System.out.println( aryNums[2] ); The above code will print out whatever value is held at array position 2 in the array called aryNums. But let's get some coding practice. Start a new project and call it anything you like. Don't forget to change the name of the Class to something relevant. Type the following code into your new Main method:
When you run the programme you should see this in the Output window:
Change the array position number in the print line from 2 to 5 and 18 should print out instead. In the next part, we'll take a look at how to use arrays with loops. Arrays come into their own with loops. You have seen in the previous section that to assign values to array positions, you did this:
aryNums[0] = 10; But that's not terribly practical if you have a lot of numbers to assign to an array. As an example, imagine a lottery programme that has to assign the numbers 1 to 49 to positions in an array. Instead of typing a long list of array positions and values you can use a loop. Here's some code that does just that:
So we set up an array to hold 49 integer values. Then comes the loop code. Notice the end condition of the loop: i < lottery_numbers.length Length is a property of array objects that you can use to get the size of the array (how many positions it has). So this loop will keep going round and round while the value in the variable i is less than the size of the array. To assign values to each position in the array, we have this line: lottery_numbers[i] = i + 1; Instead of a hard-code value between the square brackets of the array name, we have the variable called i. This increases by 1 each time round the loop, remember. Each array position can then be accessed just by using the loop value. The value that is being assigned to each position is i + 1. So again, it's just the incremented loop value, this time with 1 added to it. Because the loop value is starting at 0, this will give you the numbers 1 to 49. The other line in the loop just prints out whatever value is in each array position. (If you wanted, you could then write code to jumble up the numbers in the array. Once you have jumbled up the values, you could then take the first 6 and use them as the lottery numbers. Write another chunk of code that compares a user's 6 numbers with the winning numbers and you have a lottery programme!) Other inbuilt java methods allow you to sort your arrays. To use the sort method of arrays, you first need to reference a Java library called Arrays. You do this with the import statement. Try it with your aryNums programme. Add the following import statement: import java.util.Arrays; You code should look like ours below:
Now that you have imported the Arrays library, you can use the sort method. It's quite easy: Arrays.sort( aryNums ); First you type the word "Arrays", then a dot. As soon as you type a dot, NetBeans will display a list of things you can do with arrays. Type the word "sort". In between a pair of round brackets, you then put the name of the array you want to sort. (Notice that you don't need any square brackets after the array name.) And that's it - that's enough to sort the array! Here's some code to try out:
The for loop at the end will go round and round printing out the values in each array position. When the code is run, the Output will look like this:
As you can see, the array has been sorted in ascending order. Sorting in descending order, however, is only possible either by writing your own sorting code, or converting your array to Integer objects then importing from the Collections library. If you need to a descending sort, here's some code that does just that (skip this code, if you want):
All a bit messy, I'm sure you'll agree! You can place strings of text into arrays. This is done in the same way as for integers: String[ ] aryString = new String[5] ; aryString[0] = "This"; aryString[1] = "is"; aryString[2] = "a"; aryString[3] = "string"; aryString[4] = "array"; The code above sets up a string array with 5 positions. Text is then assigned to each position in the array. Here's a loop that goes round all the positions in the array, printing out whatever is at each position: int i; for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] ); } The loop goes round and round while the value in the variable called i is less than the length of the array called aryString. When the above programme is run, the Output window will look like this:
You can perform a sort on string arrays, just like you can with integers. But the sort is an alphabetical ascending one, meaning that "aa" will come first over "ab". However, Java uses Unicode characters to compare one letter in your string to another. This means that uppercase letter will come before lowercase ones. Try the following code:
When the programme is run, the Output window will display the following:
Although we've sorted the array, the word "This" comes first. If this were an alphabetical sort, you'd expect the word "a" to come first." And it does if all the letters are lowercase. In your programming code, change the capital "T" of "This" to a lowercase "t". Now run your programme again. The Output window will now display the following:
As you can see, the word "this" is now at the bottom. We'll have a closer look at strings in the next section, so don't worry too much about them now. Instead, try these exercises.
A multi dimensional array is one that can hold all the values above. You set them up like this: int[ ][ ] aryNumbers = new int[6][5]; They are set up in the same way as a normal array, except you have two sets of square brackets. The first set of square brackets is for the rows and the second set of square brackets is for the columns. In the above line of code, we're telling Java to set up an array with 6 rows and 5 columns. To hold values in a multi-dimensional array you have to take care to track the rows and columns. Here's some code to fill the first rows of numbers from our spreadsheet image: aryNumbers[0][0] = 10; aryNumbers[0][1] = 12; aryNumbers[0][2] = 43; aryNumbers[0][3] = 11; aryNumbers[0][4] = 22; So the first row is row 0. The columns then go from 0 to 4, which is 5 items. To fill the second row, it would be this: aryNumbers[1][0] = 20; aryNumbers[1][1] = 45; aryNumbers[1][2] = 56; aryNumbers[1][3] = 1; aryNumbers[1][4] = 33; The column numbers are the same, but the row numbers are now all 1. To access all the items in a multi-dimensional array the technique is to use one loop inside of another. Here's some code to access all our number from above. It uses a double for loop:
The first for loop is used for the rows; the second for loop is for the columns. The first time round the first loop, the value of the variable i will be 0. The code inside of the for loop is another loop. The whole of this second loop will be executed while the value of the variable i is 0. The second for loop use a variable called j. The i and the j variables can then be used to access the array. aryNumbers[ i ][ j ] So the two loop system is used to go through all the values in a multi-dimensional array, row by row.
Exercise Finish off the programme above where we are writing a programme to print out all the values from the spreadsheet. Your Output window should look something like this when you're done:
Multi-dimensional arrays can be quite tricky, but mainly because it's hard to keep track of all your rows and columns! In the next part, you'll learn about array lists. If you don't know how many items are going to be held in your array, you may be better off using something called an ArrayList. An ArrayList is a dynamic data structure, meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array. To set up an ArrayList, you first have to import the package from the java.util library: import java.util.ArrayList; You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( ); Notice that you don't need any square brackets this time. Once you have a new ArrayList objects, you can add elements to it with the add method: listTest.add( "first item" ); listTest.add( "second item" ); listTest.add( "third item" ); listTest.add( 7 ); In between the round brackets of add you put what it is you want to add to the ArrayList. You can only add objects, however. The first three items we've added to the list above are String objects. The fourth item is a number. But this will be a number object of type Integer, rather than the primitive data type int. Items in the list can be referenced by an Index number, and by using the get method: listTest.get( 3 ) This line will get the item at Index position 3 on the list. Index numbers start counting at zero, so this will be the fourth item. You can also remove items from an ArrayList. You can either use the Index number: listTest.remove(2); Or you can use the value on the list: listTest.remove( "second item" ); Removing an item will resize the ArrayList, so you have to be careful when trying to get an item on the list when using its Index number. If we've removed item number 2, then our list above will contain only 3 items. Trying to get the item with the Index number 3 would then result in an error. To go through each item in your ArrayList you can set up something called an Iterator. This class can also be found in the java.util library: import java.util.Iterator; You can then attach your ArrayList to a new Iterator object: Iterator it = listTest.iterator( ); This sets up a new Iterator object called it that can be used to go through the items in the ArrayList called listTest. The reason for using an Iterator object is because it has methods called next and hasNext. You can use these in a loop: while ( it.hasNext( ) ) { System.out.println( it.next( ) ); }
The method hasNext returns a Boolean value. The value will be false if there are no more items in the ArrayList. The next method can be used to go through all the items in the list. To test all this theory out, try the following code:
Notice the line that prints out the entire list: System.out.println( "Whole list=" + listTest ); This gives you a quick way to see which items are on your list, if it gets a bit too long. When the code is run, the Output window will display the following: first item second item third item 7 Whole list=[first item, third item, 7] Position 1=third item To sum up, then, use an ArrayList when you're not sure how many elements are going to be in a list of items.
How Java Stores Strings A string is a series of Unicode characters held under a variable name. Take the following string: String someText = "Bill"; This tells Java to set up a string object with the four characters "B", "i", "l" and another "l". In the Unicode character set, these values are: \u0042, \u0069, \u006c, \u006c. Unicode values are stored as hexadecimals numbers. Capital letters (A to Z) are stored using the values \u0041 to \u005a, while lowercase letters (a to z) are stored using the hexadecimals values \u0061 to \u007a. In the previous section, we had an array which held strings of text. We then sorted the array:
We noted that the word "This" comes first. If the array is supposed to be sorted alphabetically, however, you would expect the word "a" to come first. The reason it doesn't is because lowercase "a" has a hexadecimal value of u\0061, which is the decimal number 97. But uppercase "T" has a hexadecimal value of u\0054, which is the decimal number 84. 84 is lower than 97, so the "T" comes first. OK, let's do some work manipulating strings of text. The string methods we'll take a look at are: toUpperCasse toLowerCase compareTo IndexOf endWith, startsWith Substring Equals charAt trim valueOf Converting your Java strings of text to upper or lower case is fairly straightforward: just use the inbuilt methods toUpperCase and toLowerCase. Start a new project for this, and add the following code:
The first two lines of code just set up a String variable to hold the text "text to change", and then we print it out. The third line sets of a second String variable called result. The fourth line is where we do the converting: result = changeCase.toUpperCase( );
To use a string method you first type the string you want to work on. For us, this was the string in the variable called changeCase. Type a dot after the variable name and you'll see a list of available methods that you can use on your string. Select toUpperCase. (The method needs the empty round brackets after it.) After Java has changed the word to uppercase letters, we're storing the new string into our result variable. When the programme is run, the Output window displays the following:
But you don't have to store the converted word in a new variable. This would work just as well: System.out.println( changeCase.toUpperCase( ) ); Here, Java will just get on with converting the string, without needing to assign the result to a new variable. If you want to convert to lowercase, just use the toLowerCase method instead. It is used in exactly the same way as toUpperCase. In the next part, you'll see how to compare strings in Java. You can compare one string to another. (When comparing, Java will use the hexadecimal values rather than the letters themselves.) For example, if you wanted to compare the word "Ape" with the word "App" to see which should come first, you can use an inbuilt string method called compareTo. Let's see how it works. You don't need to start a new project for this: simply comment out (or delete) the code you already have. Now add the following code:
We've set up two string variables to contain the words "Ape" and "App". The compareTo method is then this line in the code above: result = Word1.compareTo( Word2 ); The compareTo method returns a value. The value that is returned will be greater than 0, less than 0, or have a value of zero. If Word1 comes before Word2, then the value that is returned will be less than 0. If Word1 comes after Word2 then the value returned will be greater than 0. If the two words are identical then a value of 0 will be returned. So you need to assign the value that compareTo returns to a variable. We're placing the value in an integer variable called result. The IF Statements in the code simply tests to see what is in the result variable However, when you compare one string of text with another, Java compares the underlying hexadecimals values, rather than the actual letters. Because uppercase letters have a lower hexadecimal value than lowercase ones, an uppercase letter "A" in "App" will come before a lowercase letter "a" in "ape". Try it for yourself. Change "Ape" to "ape" in your code. The Output will read "Word1 is more than Word2", meaning that Java will place the word "ape" after the word "app" alphabetically. To solve the problem, there's a related method called compareToIgnoreCase. As its name suggest, lowercase and uppercase letter are ignored. Use this and "ape will come before "App" alphabetically.
We want to check if the @ sign is in the email address, so we first set up a char variable and assign it a value of '@'. (Note the single quotes for the char variable). After setting up an email address, we have a result variable. This is an int variable. The reason that result is an integer is because the indexOf method will return a value. It will return the position number of the ampersand character in the string email_address. Here's the relevant line: result = email_address.indexOf( ampersand ); The string you're trying to search comes first. After a dot, type indexOf. In between the round brackets of indexOf, you have several options. One of the options is to type a single character (or the name of char variable). We've placed our ampersand variable between the round brackets of indexOf. Java will then tell us the position of the @ character in the email address. It will store the value in the result variable. When you run the code, the output will be 4. You might think that the @ sign is the fifth character in the email address. But indexOf starts counting at 0. However, if the character is not in the word that you're searching, indexOf will return a value of -1. To test this out, delete the @ sign from your email_address string. Then run your code again. You'll see -1 as the output. You can use the return value of -1 to your advantage. Here's the code again, only with an IF statement that examines the value of the result variable:
So if the result of indexOf is -1 then we can do one thing, else allow the user to continue. You can also use indexOf to test for more than one character. The code below checks the email address to see if it ends with ".com":
The code is almost identical, except we're now using a String variable to hold the text we want to check for (.com), and not a char variable. Again, a result of -1 will be returned if the text to search for is not found in the String that comes before the dot of indexOf. Otherwise, indexOf will return the position of the first of the matching character. In the code above, the dot is the seventh character of the email address, when you start counting from 0.
You can also specify a starting position for your searches. In our email address example, we can start searching for the ".com" after the @ symbol. Here's some code that first locates the position of the @ symbol, and then uses that as the start position to search for ".com".
The new line of code is this one: result = email_address.indexOf( dotCom, atPos ); The only thing different is the addition of an extra variable between the brackets of indexOf. We still have the string we want to search for (which is whatever text is in the dotcom variable), but we now have a starting position for the search. This is the value of the variable called atPos. We get the atPos value by using indexOf to locate the position of the @ symbol in the email address. Java will then start the search from this position, rather than starting at 0, which is the default.
Ends With Starts With For the programme above, you can also use the inbuilt method endsWith: Boolean ending = email_address.endsWith( dotcom ); You need to set up a Boolean variable for endsWith, because the method returns an answer of true or false. The string you're trying to test goes between the round brackets of endsWith, and the text you're searching goes before it. If the text is in the search string then a value of true is returned, else it will be false. You can add an if else statement to check the value: if (ending == false ) { System.out.println( "Invalid Email Address" ); } else { System.out.println( "Email Address OK " ); }
The method startsWith is used in a similar way: Boolean startVal = email_address.startsWith( dotcom ); Again, the return value is a Boolean true or false.
Substring
One really useful method available to you is called substring. This method allows you to grab one chunk of text from another. In our email address programme above, for example, we could grab the last five characters from the address and see if it is co.uk. To get some practice with substring, we'll write a small Name Swapper game. For this game, we want to change the first two letters of a family name and swap them with the first two letters of a personal name, and vice versa. So if we have this name: "Bill Gates" we would swap the "Ga" of "Gates" with the "Bi" of "Bill" to make "Bites". The "Bi" of "Bill" will then be swapped with the "Ga" of "Gates" to make "Gall". The new name printed out would be: "Gall Bites" We'll use substring for most of this programme. Substring works like this: String FullName = "Bill Gates"; String FirstNameChars = ""; FirstNameChars = FullName.substring( 0, 2 ); You set up a string to search, in this case the string "Bill Gates". The string you're trying to search goes after an equals sign. After a dot, type the name of the method, substring. There are two ways to use substring, and the difference is in the numbers between the round brackets. We have two numbers in the code above, 0 and 2. This means start grabbing characters at position 0 in the string, and stop grabbing when you have two of them. The two characters are then returned and placed in the variable FirstNameChars. If you always want to go right to the end of the string, you can just do this: String test = FullName.substring( 2 ); This time, we only have 1 number between the round brackets of substring. Now, Java will start at character two in the string FirstName, and then grab the characters from position 2 right to the end of the string. Start a new programme to test this out. Add a print line to the end and your code should be this:
When the programme runs, the Output window should look like this:
So the substring method has allowed us to grab the first two characters of the name "Bill". To get the first characters, we had a 0 and a 2 between the round brackets of substring. You might think that to get the "Ga" of "Gates" that we could just do this: = FullName.substring(5, 2); We still want two characters, after all. Only this time, the 5 would tell Java to start from the "G" of "Gates". (The first position in a string is position 0 not position 1.) So, start at position 5 in the string and grab 2 characters. However, running that code would get you an error. That's because the second number between the round brackets of substring doesn't mean how many characters you want to grab. It means the position in the string that you want to end at. By specifying 2 we're telling Java to end at the character in position 2 of the string. As you can't go from position 6 backwards to position 2 you get an error instead. (NOTE: If you start the count at 0 in the string "Bill", you might think that position 2 is the letter "l". And you'd be right. But substring starts before the character at that position, not after it.) To get the "Ga" of "Gates", therefore, you could do this: FullName.substring( 5, FullName.length( ) - 3 ); The second number is now the length of the string minus 3 characters. The length of a string is how many characters it has. "Bill Gates" has 10 characters, including the space. Take away 3 and you have 7. So we're telling substring to start at character 5 and end at character 7. And that would work perfectly well for people called "Bill Gates". But the programme wouldn't work if you name was, say, "Billy Gates". The code above would then grab the space character plus the letter "G", which is
not what we want at all. We want the programme to work whichever two names are entered. So we have to get a bit clever. One thing we can do is to note the position of the space in the two names. The 2 characters we want to grab from the second name always come right after the space character. We want some code that grabs those first two characters after the space. We can use indexOf to note the position of the space: int spacePos = FullName.indexOf(" "); To specify a space character you can type a space between two double quotes (or single quotes). This then goes between the round brackets of indexOf. The value returned will be an integer, and it is the position of the first occurrence of the space character in the string FullName. Test it out by adding the line above to your code: Add a print line to check the Output:
So the space is at position 4 in the string. We can use this fact to grab the first two characters of "Gates", or indeed any second name. We tell Java to go from the first character after the space, and end at the next two characters: FullName.substring( spacePos + 1, (spacePos + 1) + 2) So the two numbers between the round brackets of substring are these: spacePos + 1, (spacePos + 1) + 2 We want to start at the first character after the space (space + 1), and end two characters after this position, which is (spacePos + 1) + 2.
Add the following lines to your code (The ones highlighted. Our new substring method spills over on to two lines, but you can keep your on one, if you prefer):
So we now have the "Bi" from Bill and the "Ga" from Gates. What we now need to do is get the rest of the characters from the two names, and then swap them around. Again, we can use substring to get the remaining characters from the first name: String OtherFirstChars = ""; OtherFirstChars = FullName.substring( 2, spacePos ); System.out.println( OtherFirstChars ); And the remaining characters from the second name: String OtherSurNameChars = ""; OtherSurNameChars = FullName.substring((spacePos + 1) + 2, FullName.length() ); System.out.println( OtherSurNameChars ); Not the numbers in between the round brackets of substring. To get the other first name characters, the numbers are these:
2, spacePos This tells Java to start at position 2, and go right up to the position of the space. To get the rest of the second name, however, it's a little bit trickier: (spacePos + 1) + 2, FullName.length( ) The (spacePos1 + 1) + 2 is the starting position of the third character of the second name. We want to end at the length of the string, which will get us the rest of the characters. Add the following to your code (highlighted):
We now have all the parts of the name. To join them together, we can use concatenation:
Add the new lines to your own code. When you run your programme, the Output window should display the following:
We can get rid of the print lines, though, and invite a user to enter a first name and second name. Here's the new programme (the only addition is for the keyboard input, which you've used before):
The Output window should look something like this, when you run your programme and enter a first name and surname:
We should, of course, add some error checking. But we'll assume the user can enter a first name and surname with a space between the two. If not, the programme will crash! Let's move on, though, and have a look at the equals method. You can check two strings to see if they are the same. For this, use the equals method in Java. Here's some code:
In this code, we want to check if one email address is the same as another. The first two lines set up two string variables, one for each email address. The third line sets up a Boolean variable. That's because the equals method returns a value of true or false. The fourth line is where we use the method: isMatch = email_address1.equals( email_address2 ); In between the round brackets of the equals method, you place the string you're trying to check. The other string goes before the equals method. Java will then tell you (true or false) whether the two are the same. The IF statement checks which one it is. The equals method only compares objects, however. It's OK for strings, because they are objects. But you can't use the equals method to compare int variables. For example, this code would get you an error: int num1 = 12; int num2 = 13 Boolean isMatch = false; isMatch = num1.equals(num2); The int variable is a primitive data type, and not an object. You can turn the primitive int data type into an object, though: int num1 = 12; Integer num_1 = new Integer(num1); Here, the int variable called num1 is being turned into an Integer object. Note the use of the new keyword. In between the round brackets of Integer, you put the primitive int data type you want to convert to an object. You can check to see which single character is in a particular string. The charAt method is used for this in Java. Here's some code to try: String email_address = "[email protected]"; char aChar = email_address.charAt( 4 ); System.out.println( aChar );
This code checks which letter as at position 4 in the email address string. The return value is a variable of type char: char aChar = email_address.charAt( 4 ); When the above code is run, the output is the character @. The number between the round brackets of charAt is the position in the string you're trying to check. Here, we want to get at the character in position 4 of the email_address string. Again, the count starts at 0, just like substring. One good use for charAt is for taking a letter from a string variable that is typed by a user, and then converting it to a single char variable. For example, you could ask the use to type Y to continue or an N to exit. Have a look at this code:
We can't use the Scanner class directly to get a single letter to store in a char variable. So we use the next( ) method to get the next string that the user inputs. There's a next integer, next long, next double - even a next Boolean. But there's no next char. Even if the user inputs a single character it will still be a string and not a char. (Remember: a char variable stores a Unicode number as an integer.) We can use charAt to get a character from any string that the user inputs, even if the user inputs a single letter: char aChar = aString.charAt( 0 ); All we're saying is "Get the character at position 0 in the string called aString, then store it in the aChar variable".
There are several ways to use the replace method, and they differ in what you put between the round brackets of the method. We're replacing one sequence of characters with another. Think of the comma separating the two as the word "with". You'd then have "Replace you with your". You can also replace single character: aString.replace( '', '@' ) The above code reads "Replace with @". (You can also use something called a regular expression in your replace methods, but that is outside the scope of this book.)
Trim You can trim white space from your strings White space is things like space characters, tabs, and newline characters - the characters you can't see, in other words. The trim method is easy to use: String amend = " white space "; amend = amend.trim( ); So the trim method goes after the string you want to amend. The blank characters before the word "white" and after "space" in the code above will then be deleted. If you're getting input from a user then it's always a good idea to use trim on the inputted strings.
Formatted Strings
Strings of text can be formatted and output with the printf command. The printf command understands a series of characters known as a format specification. It then takes a string of text and formats it, based on the format specification passed over. As an example, supposed we wanted the Output window to display text in neat columns, like this:
The first column is left-justified, and the second column is right-justified. The code for the Exam_Name and Exam_Grade headings was this: String heading1 = "Exam_Name"; String heading2 = "Exam_Grade"; System.out.printf( "%-15s %15s %n", heading1, heading2); To get the left-justified column, you need a percentage symbol, a minus symbol, the number of characters, and then the letter "s" (lowercase). So ''%-15s'' means fifteen characters left-justified. To get a right-justified column the same sequence of characters are used, except for the minus sign. To get a newline %n is used. Note that the characters are surrounded with double quotes. After a comma, you type the text that you want formatting. The first comma in the code above separates the format specification from the text being formatted. Here's some tables of the various options.
String Formatting
If you want to format numbers then you can either use the "d" character or, for floating point numbers, the "f" character. Integer Formatting
Here are some code examples of String, integer and floating point formatting. Try them out for yourself.
Same as above but the numbers occupy 10 places, with spaces to the left as padding.
Finally, here's the table again from the start of this formatting section:
Have a play around with formatting, and see how you get on. If you get error messages you may have gotten your "s" formatting confused with your "d" formatting!