Java Chapters 1-6
Java Chapters 1-6
100011101 010101001
Compiler
101010100 101010101
The Compiler translates the source code entered by the Programmer into machine readable code.
The end user is presented with a software application that is ready for use. Figure 1: Compiling Process
Chapter 2
2.1 Introducing Java
Java is what we call an object oriented language. One of its most important and positive features is that it is platform-independent which means that a Java program will run on virtually any type of computer. Other programming languages such as Pascal do not have this feature as if they are compiled on one machine, they can only be used on that machine. For Java to be able to do this it makes use of a Java Virtual Machine (JVM). This enables that a java program can be run for each particular computer on which it is required to do so. Figure 1 illustrates the compilation process from a set of instructions written using a programming language into machine code to provide a software application for a particular PC. The compilation process of Java programs is slightly different as illustrated and explained in Figure 2: Compiling Java programs. The Programmer types in the source code to create a software application The Java Compiler does NOT translate the source code into machine code, BUT rather into Java Byte Code
If (age >= 18) { System.out.println(You can vote!); } 100011101 010101001
Java Compiler
101010100 101010101
The JVM then translates each Java Byte Code into the machine code respective for the computer it is running on before this instruction is performed.
JVM
Important notes: The Java Byte Code contains instructions which are universal. These instructions are similar to machine code and are also composed of 1s and 0s however they are the same for any type of computer (unlike machine code which is specific for each type of machine). In order to benefit from the functionality offered by the JVM, this has to be installed on the computer requiring its use. Usually the JVM comes packaged together with the system, also including the Java libraries (these are pre compiled Java modules that you can make use of in your programs). The JVM together with the Java libraries are known as the Java Runtime Environment (JRE). The Java Development Kit (JDK) is composed of the JRE, compiler and other available tools. Note that the JDK does not contain the editor where you will be typing in your programs as there are many available and this is up to the users preference. The JDK (Standard Edition) can be downloaded freely from: www.java.sun.com The Java editor, JCreator can be downloaded freely from: www.jcreator.com many versions are available however version 3.5 is the classical version available for download. The JVM can be found within internet browsers, such as Internet Explorer, and because of this, Java programs may also run on the Web. The Java programs that run on the Web are called applets.
Graphics based interface A graphics based interface is one which is has pictures, icons and shapes drawn on screen. They usually allow for input through the use of multiple input devices such as the keyboard and mouse and are appealing to look at and fun to make use of.
2.2 Files
To start programming you will need to install and make use of an Integrated Development Environment (IDE). An IDE will provide you with a window/editor where you can type in your code. Common IDEs include JCreator, NetBeans, Textpad and even Notepad. When you create and save a java file you will be creating a file with the extension of .java You will then need the Java Compiler (JAVAC) which will then provide you with a Java byte code file (.class). Be careful to remember that this is not the source code, nor is it the machine code but it is the intermediary code used to produce the machine code from the source code. Note: Compilers translate source code into files. Interpreters translate source code to be run (and not into files). Every time you want to run a java program you have to re-interpret it.
Important Java rules to note: 1. 2. 3. 4. In Java we do not write programs but rather classes. The name of the class has to start with an uppercase letter. Only class name and file names should start with an uppercase letter. The name of the file HAS TO match the name of the class i.e. in the above example, the file must be called HelloWorld for it to match the name of the class. 5. It is essential that you indent your code correctly. This will help you immensely when debugging and trying to identify errors within your code.
2.4 Activities
Activity 1
1. Open JCreator 2. Click on: File New File 3. Select Java Classes and set the location path for your saved files. Note that when using Windows 7 and Windows Vista these operating systems do not allow you to save to the root directory i.e. C:\ 4. Type in the above program 5. Compile it using the Build File button, ( ), or through the Build menu option ), or through the Run menu option 6. Run the program using the Run File button, (
Activity 2
Amend the above program to display your details in the following format: Name: John Smith Address: 10, Main Road, London Telephone number: 1111111111
Activity 3 Create a program where your name is displayed on the first line and through the use of another line of code your surname is also displayed on the first line.
2.5 Comments
It is good practice to include comments within your code to help those reading through your program and also to help you remember the line of thought you went through when programming your work. Comments can be entered in either of the following two ways.
// this is a one line comment public class HelloWorld { public static void main(String[] args) { System.out.println("hello world"); } } /* this is a second type of comment which allows me to enter paragraphs or multiple lines of comments without having to type in double slash characters every time I start a new line */
Data types are exchangeable i.e. you can save a variable of type byte into a variable of type long but you cannot save a variable of type long into a variable of type byte due to the limited storage space assigned to that variable. The following is a table illustrates the primitive (most basic) data types within Java:
Type
Integers Byte short Int Long Real float double Special Char boolean
Description
Very small integers Small integers large integers Very large integers Real numbers Very large real numbers Single characters Boolean value
Range of values/Format
-128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807 +/-1.4 * 10-45 to 3.4 * 1038 +/-1.4 * 10-324 to 1.8 * 10308 Unicode character set True or false
Activity 4
Create a program which displays the information contained in the above table. Note: 10-324 is to be represented as 10^-324
dataType variableName;
It is good practice to initialise your variables as follows: Example: int price = 0; double total = 0; Or int price; double total; price = 0; total = 0;
Several variables of the same type may be declared together however when doing so you cannot initialise them all at one go as this would have to be done separately for each variable. Example: int price, total; price = 0; total = 0;
Note that when initialising our variables we are making use of the assignment operator (this operator will also be used when you want to assign a value to your variables other than zero). When assigning a value to a character there have to be single quotes surrounding that character. Example: char choice = A;
The above operators can be used within assignment statements. Example: int x; //declaring variable x = 10+5; //performing an addition through the use of an assignment statement
Note: the terms on the right hand side of the assignment statement are known as expressions (i.e. (10+5) in the above example).
Example: double price, tax, total; //declaring variables price = 100; //set the price value tax = 0.18; //set the tax value total = price + (price * tax) //calculate total price using variables
The variable you used on the left hand side of the assignment statement may also be used on the right hand side contemporarily. Example: price = price * (1 + tax/100); The old value of price The new value of price
2.12 Outputs
To display a message on screen using Java we make use of the following line of code: System.out.println(Hello World);
println in short for print line and with this statement you are directing your program to start a new line after displaying what follows in the brackets.
print instructs your program to output anything that follows in the brackets on the same line.
Example: public class HelloWorld { Public static void main(String[] args) { //anything that follows print on the next line System.out.println(Hello World); //anything that follows print on the same line System.out.print(Hello World again ); //anything that follows print on the next line System.out.println(Bye Bye); } }
The above code will output the text in the following manner: Hello World Hello World again Bye Bye
2.13 Inputs
Java provides us with a special class called Scanner which allows us to obtain input from the keyboard. This comes within the JDK and you do not need to worry about programming it yourself. It is provided as a package i.e. a pre-compiled set of classes. The package within which Scanner is found is called util and we therefore have to import this to be able to make use of it within our programs. The following statement is to be placed at the very beginning of your program: import java.util.*;
This way you will be importing ALL of the classes within the util package. Alternatively if you only want to import the Scanner class you can type: import java.util.Scanner;
You can now proceed to using all of the methods which have been defined within the Scanner class. Having imported the util package you will need to write the following instruction within your code: Scanner sc = new Scanner(System.in);
With the above line of code you are creating a new object called sc of the Scanner class. Therefore: Scanner sc = new Scanner(System.in);
Class
Keyboard representation
The Scanner object you just declared is similar to a variable, but instead of holding one value at a time it can hold many and you can reuse it various times within your code.
Type Int
Note: x would be previously defined as a variable of type int and it is to hold the data returned from the keyboard entry Double y = sc.nextDouble(); Note: y would be previously defined as a variable of type double and it is to hold the data returned from the keyboard entry Char z = sc.next().charAt(0); Note: z would be previously defined as a variable of type char and it is to hold the data returned from the keyboard entry
2.15 Strings
A collection of consecutive characters are known as strings. Example: Hello World When programming in Java it is important to always enclose strings within double quotes ( ). Two or more strings can also be joined together by making use of the plus (+) symbol. This is known as the concatenation operator. Example: Example: system.out.println(Hello + World);
Note: The plus (+) sign is said to being overloaded i.e. it has two functions mathematical and concatenation. The plus (+) symbol may also be used with expressions and mathematical workings. Example: System.out.println(Total price is: + (10 * 1.83));
Also, you can make use of the assignment operator (equals (=) sign) when using strings. Example: name = John Smith;
It is important to note that a String is not a simple data type as are char and int etc As we progress you will see that a String is in fact a class, however you declare it in the same way you would declare any other primitive types in Java with the exception that the String type has to start with a capital S.
2.17 Activities
1. Create a program that will ask a user to enter his/her name and surname and display these as an output on screen. 2. Create a program which will ask the user to enter the measurements of a rectangle and output the area. 3. Create a program which will ask the user to enter the value of the radius of a circle and then display the circumference and the area of that circle. Note that the area is calculated using and the circumference by using C = 2 . You can take the value of to being 3.1416 and ideally this should be declared within a constant variable. 4. Write a program which asks for a temperature in Celsius and outputs the value in Fahrenheit using the following: F = (C*(9/5))+32 5. Write a program which asks the user for the price of an item and asks for the VAT rate and then returns the total cost (price + VAT) 6. Write a program which asks for 3 values and returns the multiplication on screen 7. Write a program which reads in three integer values and outputs these again on screen
Chapter 3
3.1 Selection
Up until now the programs that you have created were all executed in sequence i.e. one instruction after the other, from the beginning till the end with no exceptions made. You will find that very often you will need your program to make a choice. For this reason selection is a method of programming which allows you to take different paths in executing your instructions based on certain criteria. For example, you want to develop a program which will accept an input from the user being their age and output whether or not they can vote. Therefore if the user enters any age under 18, you would like to output that the user is below the required age and cannot vote. But, if the user enters any age equal to or above 18 then you would like to output that the user can vote! In Java there are three forms of selection which you can use. These are: 1. if statement 2. ifelse statement 3. switch statement
In the above, the test is the condition which would have to be satisfied. This produces a true or false result and depending on this result, the instructions within that if statement will be executed or not. Example: if age is larger than 18 if the choice made is the first one if the weather is sunny
If the test results in false, e.g. age is not larger than 18, then the instructions within that if condition will NOT be executed and that section of code will be skipped entirely. Example: Consider the following example of the if statement
if (age >= 18) // check if age is larger than or equal to 18 { //if age is larger than or equal to 18 then execute this code System.out.println(You are old enough to vote!); } /* this line of code is executed outside of the if statement therefore it is always executed */ System.out.println(Good bye);
Example: The following is a complete example of the use of an if statement within a program. The scope of the program is to ask the user for a price to be entered. The program then checks if the price entered is larger than 100. If so a discount of 10% is given to the user.
import java.util.*; //import the util class to be able to use the Scanner method public class CheckPrice { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //create object of type Scanner double price = 0; //declare and initialise variable double discount = 0; //declare and initialise variable System.out.println("Enter the product price: "); //request input price = sc.nextDouble(); //read input into variable called price if (price >= 100) //perform test - is price larger or equal to 100? { /* if price IS larger or equal to 100 execute the following instructions */ System.out.println("You have met the promotional discount!"); discount = (price * 0.10); } /* the following instructions are outside of the if statement and will always be executed */ price = price - discount; System.out.println("The total price to pay is: " +price); System.out.println("Have a nice day"); } }
The following are two test runs of the above program: Enter the product price: 100 You have met the promotional discount! The total price to pay is: 90.0 Have a nice day *** Enter the product price: 50 The total price to pay is: 50.0 Have a nice day
Note: when performing an equality check, e.g. age ==18, make sure to use double equal signs.
3.4 Activities
1. Create a program that will check if the angle entered is 90 degrees and if this is so output that this is a right angle. Always output Have a nice day irrespective of the degree inputted by the user. 2. Create a program that will ask the user for their name, surname, locality and age. If the age of the user is greater than 18 then output that the user is eligible to vote.
3.6 Activities
1. Write a program which asks the user to enter the price of an item. If the entered price is over EUR 100, then a 10% discount is given. Else a 5% discount is given. The total cost of the item including the discount is then outputted. 2. Write a program which asks the user to enter the temperature of water in Celsius. If the temperate is equal to or larger than 100 then display that the water is at boiling point. Else display that the water is not yet boiling. Display the temperature in Fahrenheit (F = (C*(9/5))+32). 3. Write a program asking the user to enter an angle. If the angle is 90 degrees then output this information. Else output that the given angle is not a right angle. 4. Write a program to ask the user to input a students mark. If the mark is over 45 then output that the student has passed. Else output that the student has failed. Irrespective of the entered mark always output Good luck with the rest of your exams. 5. Write a program which asks the users to enter two numbers. If the two numbers are equal then display that these numbers are equal and if they are not then display that the entered numbers are not equal. 6. Write a program which will ask the user to enter two numbers. Perform a check to display either that the first number entered if greater than the second or that the second number is greater than the first.
The above table lists the logical operators and their equivalent for the use in Java programs. These are used when it if required that tests are joined together. For example, assume that for a laboratory experiment to be successful, the remaining temperate must be between 5 and 12 degrees Celsius. This would require combining two tests: if (temperature >= 5) && (temperature <= 12)
Both the AND and the OR operators join two tests together to give a final result. However, whilst the AND operator requires both tests to be true, the OR operator requires at least one of them to be true in order to execute the given instruction set.
Note: ALWAYS indent your code correctly. Code which is not indented correctly results in making it extremely hard to localise errors and to understand the logic to read through the code. It is good practice to always ensure that your code is indented correctly to group together any instructions you have within ifelse statements or any other form of loops (to be discussed later) etc You have to keep in mind that one of the main advantages of making use of an Object Oriented Language such as Java is that of code reusability. It will be very hard to make use of code you have previously worked on if the indentation is not correct as it will make you waste a lot of time to figure out the beginning and the end of the section of code you would like to reuse.
import java.util.*; public class ScoutsTimeTable { public static void main(String[] args) { char group; //declare variable to store the scout group Scanner sc = new Scanner(System.in); System.out.println("*** Scout Groups Meeting Times ***"); System.out.println("Enter your scout group (A, B, C)"); group = sc.next().charAt(0); //check scout group and display appropriate time if (group == 'A') { System.out.print("9.00 a.m"); //meeting time for group A } else { if (group == 'B') { System.out.println("5.00 p.m");//meeting time for B } else { if (group == 'C') { System.out.println("11.00am"); //meeting time for group C } else { System.out.println("No such scouts group!!"); } } } } }
3.9 Activities
1. Create a program which will ask the user to enter the exam mark of a student. The following checks are made to output the corresponding grade of that students exam mark: larger or equal to 90 A, larger or equal to 80 B, larger or equal to 70 C, larger or equal to 60 D, anything else F.
The format of the switch statement is as follows: Variable being tested. This can be of type int, char, long, byte or short
switch (variableName) { case value1: //instructions to be executed break; case value2: //instructions to be executed break;
Possible value being tested default: //instructions to be executed } This is the optional statement (otherwise or anything else value
The break statement is the statement which forces the program to ignore the rest of the switch statement. It is important because once a matching case has been found it is useless for the program to go through any remaining case options listed within the switch.
Example: The following illustrates the example defined in the previous section i.e. using nested ifelse statement, but through the use of the switch statement.
import java.util.*; public class ScoutsGroupUsingSwitch { public static void main(String[] args) { char group; Scanner sc = new Scanner(System.in); System.out.println("*** Scouts Groups Meeting Times ***"); System.out.println("Enter your group (A, B, C)"); group = sc.next().charAt(0); switch (group) { // to check for lowercase values or to combine checks do as follows //case value: case value: instruction case 'A': case 'a': System.out.println("9.00am"); break; case 'B': case 'b': System.out.println("5.00pm"); break; case 'C': case 'c': System.out.println("11.00am"); break; // any other input value default: System.out.println("No such group"); break; } //end of switch } //end of main } //end of class
3.11 Activities
1. Consider a bank that offers four different types of accounts: a, b, c and x. the following illustrates the annual rate of interest offered for each type of account. a = annual interest of 1.5% b = annual interest of 2% c = annual interest of 1.5% x = annual interest of 5%
Design and implement a program that allows the user to enter an amount of money and a type of bank account before displaying the amount of money that can be earned in one year as interest on that money for the given type of bank account. 2. Consider the bank accounts example previously made, and now assume that each type of account is associated with a minimum balance as shown. account a = 250 account b = 1000 account c = 250 account x = 5000 Adapt the switch statement of the program written before so that the interest is applied only if the amount entered satisfies the minimum balance required for the given account. If the amount of money is below the minimum balance an error message should be displayed. Hint: Use an if...else statement for every value calculated within the switch.
Chapter 4
4.1 Iteration
Iteration is a form of program control that allows us to repeat a section of code. The program structure is one that is used to control such repetition and is known as a loop. There are three types of loops within Java: 1. for loop 2. while loop 3. dowhile loop
Using loops
public class PrintStars { public static void main(String[] args) { for (int i =1; i <= 5; i++)
{
System.out.println(*****); } } }
In the above example we are making use of a for loop for which its structure is as follows:
Condition for loop to execute. I.e. if condition returns true then loop is executed, when condition returns false loop is exited.
Incrimination of counter variable i.e. every time the loop is executed the counter is incremented by 1.
Therefore the general structure of a for loop within Java is as follows: for (/*start counter*/ ; /*test counter*/ ; /*change counter*/)
4.3 Activities
By making use of a for loop do the following: 1. Create a program to display five rows of 5 dollar signs ($) in each row on screen. 2. Create a program to display the numbers from 1 to 10 on screen. 3. Create a program to go through the numbers from 1 to 10 and display only those numbers which are even on screen. Note: and even number is one which leaves no remainder when divided by 2 therefore make sure you make use of the correct Java operator to test for this. Hint: in this exercise you will need to make use of an if statement within the for loop.
import java.util.*; public class DisplayBoxOfStars { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.println(*); } //end of inner loop System.out.println(); //start new line and loop again until i=5 }//end of outer loop } //end of main } //end of class
The for loop is an often used construct to implement fixed repetitions i.e. repeat for x amount of times. You will come across instances when you will however need to make use of repetitions which are not fixed. A typical example would be to display a menu on screen until the user decides to select the Quit option. For such examples the while loop offers non-fixed iteration capabilities.
4.6 Activity
1. Create a program which will ask the user to enter an exam mark. If the mark is above 45 then display Congratulations you passed whereas if the mark entered is below 45 display You failed. Good luck next time.. A validation is to be made to ensure that no marks are entered which are either higher than 100 or lower than zero. If the user enters such marks then Invalid mark please re -enter correct mark:
Hint: The following pseudocode will help you develop your code: Ask user to enter mark Keep repeating the following while mark is < 0 or >100 Display error message Ask user to re enter mark End of while Perform check to see if mark is >45 Display Congrats you passed Perform check to see if mark is <45 Display You failed. Good luck next time End program.
4.8 Activities
1. Create a program which calculates the total cost of a product (price and VAT entered by user) and allows the user to repeat the program for as long as he/she chooses. 2. Create a program which displays a menu to the user with the following options: a. Addition b. Subtraction c. Multiplication
d. Division e. Quit For each of the options a-d the user is asked to enter two numbers and the equivalent of menu option is outputted. The menu is displayed allowing the user to keep using the functionality offered until option e Quit is selected.
Chapter 5
5.1 Methods
So far we have seen that all our programs contained one method: public static void main(String[] args) What we will be working on next is the creation of several other methods within our programs. These methods can then be called from our main program and this allows for reusability of code i.e. rather than repeating the same lines of code for whenever certain instructions are to be executed, we will place those instructions within a method and call that method for as many times as we need. A method is a sub program that is found within another big program. Its role is to execute a set of tasks related to it and the scope is to write the code once within a method and then if execution of that method is needed you can call it again over and over as required. The advantages of building and making use of methods are: avoid repetition, program is smaller to trace and write, if mistakes are made these are easier to correct, faster rapid application development. methods in java are simpler to handle.
Based on the above method reference which we have used up until now, below are a list of important points which describe its structure and which help you build upon creating new methods of your own. Every method should have an identifier i.e. name of method. They should start off with a public or private setter. A public method is one which can be called up both from within the program where it is written and declared or it can be called up by an external program (i.e. one where it has not been declared). Hence, public implies publicly accessible. A private method is one which can be called up within the class where it has been declared only. Methods should ALWAYS be static i.e. that that particular method can be only called up by reference from the main method and not from any other method i.e. within the main method only not from within the other methods created. The term void is a setting on a method which means that that method, when called up and executed by the main, does not return any kind of data back to the main. To better explain this through an analogy, I can give you 20 euros to go shopping but I do not want to receive anything back for it.
If not void, you can declare any one of the primitive data types within Java and this means that the data return by that method is of that type. The name of the method then follows with brackets listing the variables. A method is an enclosed set of code. If you declare a variable anywhere else (in main, other method etc...) it cannot be used within your method. That is, anything declared in a method is kept locally within that method and it cannot be referenced anywhere else i.e. usable within that method only.
Based on what we have discovered in the first section of this chapter, what we can understand from the method listed above is that: Since it is declared as being public it can be called either from within the main program where it has been written and declared or from any other program which would need to make use of it Given that it is static, it can only be called from within the main method of the class and not from within any other methods. Having set this method to void, it will not return any data to the main method.
Not having passed any parameters to this method means that the required information will be obtained through the method itself and not passed on to it from the main method.
To call the above method from within the main method you would simply do as follows:
addTaxVoidNoParams()
2. The following is an example of a method which is set to making use of parameters which are passed on to it from the main method.
public static void addTaxVoidWithParams(int val1, int val2) // val1 and val2 are known as formal parameters { int result = 0; result = (val1+val2); System.out.println("The result is "+result); }
Formal parameters are holes not variables through which we pass on data to the method. In the above method we can see that values are being passed from within the main method rather than read through the keyboard.
To call the above method from within the main method (given that it is static), you need to do as follows:
addTaxVoidWithParams(firstValue, secondValue);
firstValue and secondValue have to be variables of type int as these have to match the parameters being used within the method. Within the above method what we are doing is setting the values of firstValue and secondValue from within the main method (for example, asking the user to enter these values through the keyboard), and then, passing on these variables into the method
addTaxVoidWithParams.
Therefore, val1 is assigned the values of firstValue and val2 is assigned the value of secondValue.
3. There will be instances when you will require your methods to return data back to the main method. The following is an example of such a method:
// a method which returns data - based on the type defined i.e. int in this case public static int addTaxWithReturn(int val1, int val2) { int result = 0; result = (val1+val2); return result; }
The above method is providing that the content of result is being passed back to the main method. return has 2 meanings: a. go back from where you came i.e. if you have more code after return it will ignore this b. get the value that you have within the 'result' and take to main. Therefore when you call a method which returns a values like this one here Therefore when you call this method you have to declare a variable which will contain the result and these have to be of the same type i.e. within main it is called as: myValue = addTaxWithReturn(10, 5) where myValue is of type int as is 'result' and this variable will contain the value of 'result'
4. The following method is an example of one which takes no parameters but returns a value and therefore when you call it from main you need to set a variable of the return type (same as before). public static int addTaxWithReturnNoParams() { int value1 = 30; int value2 = 10; int result = (value1+value2); return result; } To call this method from the main method you would do so by: int total = addTaxWithReturnNoParams();
It is important that the variable total which is created to contain the return data from the method, is of the same data type as that returned by the method otherwise you will get an error.
5.5 Activities
By making use of methods do the following: 1. Create a program that will ask the user to enter his/her personal details. 2. Create a program that will check if an integer entered by the user is an even number or not (i.e. when divided by 2 will have zero remainder). 3. Create a program, which will calculate the area of a square. 4. Create a program which will ask a user to enter the price of an item, the tax rate and output the total price. It is advised that you make use of a different method for each section of the user entry. 5. Create a program which will ask the user to enter a sum of money, an exchange rate, and output the new rate. 6. Create a program which will display a menu to the user which will enable him/her to perform conversions from Celsius to Fahrenheit and vice versa. The following menu options are to be available: 1... Celsius to Fahrenheit 2... Fahrenheit to Celsius 3 Quit 7. Create a program which displays the following menu options available to the user: 1 students marks are entered, 2 view the highest mark entered so far, 3 display the lowest mark entered so far 4 display average 5 Exit Hint: If a mark is entered assume that this first mark is the greatest. The second mark is then compared to it and if greater the new value of the maximum is set. Continue doing this until the end. Use the same reasoning for lowest mark.
Chapter 6
6.1 Arrays
The more you start to develop programs the more you will find that there will be cases where you will need to make use of a large number of data items. Lets say, for example, you want to create a program that will store 10 student marks. It would be tedious and inefficient if you were to create a variable for each of the inputted marks this is were arrays come in! An array is a data type that stores a collection of items. These items are often referred to as elements of that array. Each element contained within the array MUST be of the same data type (i.e. homogeneous) however there is no restriction on which data type this is (e.g. an array can be used to hold a collection of int value, another can be used to hold a collection of char values But you cannot have the same array holding both the int and the char values).
In the above what we are doing is declaring or defining an array whose name is 'temperature' and which is going to be a list holding 'double' data types. Note: the array hasnt been created at this point it can only been declared. // Creation of an array. to be used: To CREATE an ARRAY, and therefore being able
temperature = new double[7]; In the above what we are doing is stating that the 'temperature' array is going to hold 7 elements and has now been created. We can also declare and create an array using a single statement. // we can DECLARE and CREATE an array in one single statement: double[] temperature = new double[7];
Arrays can be used like any other variable of the given data type within Java. The assignment operator (=) can be used to enter a value and you must specify within which element you want to place that value. Example: temperature[1] = sc.nextInt();
What the above line of code is doing is placing the user input for the temperature value within the 2nd element. When making use of arrays, loops are very frequently used. Look at the following example:
Example: for (int i=0; i<7; i++) { System.out.println(Enter the temperature for day +(i+1)); temperature[i] = sc.nextDouble(); }
Explaining the above: The first line of code specifies the for loop that we will be using. For every time the instructions will be looped (i.e. 0 to 6 times), an output will be displayed which will ask the user to enter the temperate for the day of that current counter i.e. Enter the temperature for day 1, Enter the temperature for day 2, Enter the temperature for day 3 and so on. Note that this is why we make use of (i+1) as the loop counter begins from 0 and we do not want to have displayed: Enter the temperature for day 0! Following by using temperature[i] = sc.nextDouble(); we are assigning each user input to an element within our array called temperature. Therefore:
User Input Screen Enter the temperature for day 1: 10 Enter the temperature for day 2: 12 Enter the temperature for day 3: 11 Enter the temperature for day 4: 9 Enter the temperature for day 5: 8 Enter the temperature for day 6: 7 Enter the temperature for day 7: 10
or
You will frequently need to know the length of the array you are working with. From the above creation statement we can see that the length is of 7 elements. However, Java also provides us with an attribute called length which returns the length of the array you are calling. Example: System.out.println(temperature.length); Or for (int i =0; i < temperature.length; i++) { //code goes here }
You may however not know the size for which you require your array at design and implementation stage. It could be the case that your program requires the user to set the length of the array, for example, the program you would like to create would ask the user to input the an amount of days (specifying the length of your array), and for each day enter the temperature (each element will then be populated within your array). Take a look at the below program example, what it does is upon creation of the array declare a variable of type int which will contain the user entry which will define the size of our array. Following based on the length of the array (making use of the length attribute), the array is populated, and finally the contents are displayed on screen.
Example:
import java.util.*; public class TemperatureEntry { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter amount of days: "); int size = sc.nextInt(); double[] temperature = new double[size]; for (int i=0; i < temperature.length; i++) { System.out.println("Enter max temperature for the day "+(i+1)); temperature[i] = sc.nextDouble(); } System.out.println(); System.out.println("Temperatures entered"); System.out.println("===================="); for (int i = 0; i < temperature.length; i++) { System.out.println("day "+(i+1) + " " + temperature[i]); } } }
From the above note that when a parameter is declared being of type array, the size of the array is not required and only empty brackets are listed. Important note: when passing an array as a parameter within a method, it is not a copy of that array which will get populated but it is the actual array! So in the above example, any changes make to temperatureIn
will in turn update the original array which was passed when the method was called (this will further be explained later on). Example: the example defined in section 6.5 will be re implemented using methods.
import java.util.*; public class TemperatureEntry { public static void main(String[] args) { double[] temperature = new double[7]; enterTemps(temperature); displayTemps(temperature); int userValue = 10; }
private static void enterTemps(double[] temperatureArrayIn) { Scanner sc = new Scanner(System.in); for (int i = 0; i < temperatureArrayIn.length; i++) { System.out.println("Enter max temperature for the day "+(i+1)); temperatureArrayIn[i] = sc.nextDouble(); } } private static void displayTemps(double[] temperatureIn) { System.out.println(); System.out.println("temperatures entered"); for (int i = 0; i < temperatureIn.length; i++) { System.out.println("day "+(i+1)+ " "+ temperatureIn[i]); } } }
In the above example it is important that you are aware that even though the receiving parameter (e.g. temperatureIn) has a different name to the original variable within the main i.e. temperature, they both are pointing to the same place in memory so both are modifying the same array!
Working with the above example, the main method will then look something like this:
//the following instructions are found within the main method double[] temperature; temperature = enterTemps()
It is important to note that the above for loop should NOT be used to modify the elements of an array. Although a compiler error will not occur if you do so, it is unsafe as it may cause your problem to behave unreliably. The enhanced for loop is to be used when: You need to access all of the array elements and not part of them. You with to read the elements within the array and not modify or change them. You do not need the array index for any other processing.
Set the maximum number to the first data item within your array (i.e. at index 0). Loop through the array { If the next element within the array is > than the maximum number set then Set the maximum number = the next element } Return the value of maximum
Set the total to zero Loop through all the elements within your array Set total to = total + the value at the current array index End.
/* the method will return an int value having been passed an array of type int as a parameter */ public static int sum(int[] arrayIn) { //create and initialise a variable of type int int total = 0; //loop through array for (int i = 0; I < arrayIn.length; i++) { total = total + arrayIn[i]; } return total; }
Loop through all of the elements within the array If the current element is = to the search item Return true Else Return false
You may also need to return the index value of where the found data item resides within the array.
/* the method will return an int value having been passed an array of type int as a parameter together with the data being searched for of type int */ public static int searchNum(int[] arrayIn, int valueIn) { for (int i = 0; i < arrayIn.length; i++) { if (arrayIn[i] == valueIn) { return i; } return -999; } }
Row
Column
You can also initialise a multi-dimensional array with values, such as:
double [] [] temperature = { {11, 12, 10, 2} {23, 34, 46, 2} };
Scanner sc = new Scanner(System.in); //the outer loop controls the week row for (int week = 1; week < temperature.length; week++) { //the inner loop controls the day column for (int day = 1; day < temperature[0].length; day++) { System.out.println(Enter temperature for week +week+ and day +day); /*since an array starts from index 0 and not 1 we need to take one off the loop counters */ temperature[week-1][day-1] = keyboard.nextDouble(); } }
6.14 Activities
1. Create a program using arrays which will ask the user to enter the size of the array and then populate it with temperatures. Following display these temperatures on screen together with the day they correspond to. Example, day 1: temperature in degrees: 23
2. Create a program which manages the marks of a school classroom. The program is to use arrays where 10 marks are read, display and it gives the maximum, minimum, and average. The program should have the following features: an array holding 25 marks A menu which provides the following: 1. input a mark 2. find a maximum mark 3. find a minimum mark 4. find an average mark 5. display all marks 6. display all marks in ascending order
7. Exit The marks display should be accompanied by the position within the array which starts from index 1. Use methods having array type parameters where necessary