Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
369 views

Java Chapters 1-6

This document provides an overview of basic concepts related to programming and Java, including: 1) Programs, software, application software, system software, and embedded/dedicated software. It also discusses programming, programming languages, source code, binary instructions, compilers, and syntax. 2) An introduction to Java, noting that it is object-oriented and platform-independent. It discusses the compilation process for Java programs using bytecode and the Java Virtual Machine (JVM). 3) Types of user interfaces for Java applications, including text-based and graphical interfaces. It also discusses files, compilers, interpreters, and creating a simple "Hello World" Java program.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
369 views

Java Chapters 1-6

This document provides an overview of basic concepts related to programming and Java, including: 1) Programs, software, application software, system software, and embedded/dedicated software. It also discusses programming, programming languages, source code, binary instructions, compilers, and syntax. 2) An introduction to Java, noting that it is object-oriented and platform-independent. It discusses the compilation process for Java programs using bytecode and the Java Virtual Machine (JVM). 3) Types of user interfaces for Java applications, including text-based and graphical interfaces. It also discusses files, compilers, interpreters, and creating a simple "Hello World" Java program.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Chapter 1

1.1 Basic Concepts


The following is a list of basic concepts that it is essential that you familiarise yourselves with and understand. Program A program is a set of instructions used to perform an operation on a computer/electronic device. Programs can be stored on electronic chips, CDs, DVDs etc Software This is the name given to a collection of programs that provide instructions for telling a computer what to do and how to do it. Two main divisions or types of software exist Application software and System Software. Application Software Computer software which is designed to help a user perform a specific task. Examples include; accounting applications, word processing applications, design applications etc System Software These are special programs that help the computer function properly. This software is designed to operate the computer hardware and to provide a platform for running application software, for example; operating systems such as Windows, UNIX etc Embedded/Dedicated These are software programs which are specific in performing a given task. Such software software is installed on electronic devices which do not only include computers but can range from microwave ovens to mobile phone to GPSs. Programming The process of writing the instructions, forming a program, which will then be executed (understood) by a computer. Programming Languages which is purposely designed and created to allow for programs to be Languages developed. Examples include; C++, Pascal, Java, etc Program/Source code The text used, in a programming language, in writing a computer program. Note that the source code has to be translated before it can be understood by the computer as computers only understand binary code i.e. instructions composed one 1s and 0s. Binary instructions Instructions made up of 1s and 0s. Such instructions are understood directly by the computer and are therefore also refereed to as Machine code. Compiler Special software which translates the Program/Source code into Machine code. Refer to Figure 1: Compiling Process. Syntax The set of rules pertaining to each Programming Language (the same as with any natural language). These rules have to be respected otherwise your program will not compile. Common examples of syntax errors in Java are; missing semi-colons, incorrect use or missing brackets etc

The Programmer types in the source code to create a software application

If (age >= 18) { System.out.println(You can vote!); }

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

101010101010 100010100101 101010101011

000011010101 011110101101 101011110011

000111001101 101011100110 000011100011

Machine code for PC

Machine code for UNIX

Machine code for MAC

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.

2.3 Java Applications


As mentioned before Java applications can run on various devices such as computers or even electronic devices. When Java applications are run on computers as a user you will be seeing an output on screen which could possibly be requiring input from you through maybe the keyboard or a joystick. The screen providing the output is known as the user interface. It is good practice to ensure that when programming your user interface is intuitive i.e. easy to follow and almost self explanatory. There are two main types of user interfaces that can be developed. These are: Text based interface this is an interface with no pictures and which requires user input generally through the keyboard. These types of interfaces are primitive and not particularly appealing to look at. They are also referred to as console applications.

Text Based Interface

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.

Graphical User Interface (GUI)

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.

2.3 Creating your first program


public class HelloWorld { public static void main(String[] args) { System.out.println("hello world"); } }

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, (

What is displayed on screen?

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 */

2.6 Data Types


It is good practice to know each of the available data types within Java. Any numerical value in Java is signed and can therefore be positive or negative.

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

2.7 Declaring Variables


The table containing the primitive data types listed in section 2.6 are used within programs to create named locations (variables) within the computers memory. These locations will hold values within them whilst the program is running. This is known as the declaration of variables. The following is a list of rules which should be respected when declaring variables within Java: The variable names should have no spaces within them and should not contain mathematical symbols such as + or -. They should start with a lowercase letter (this is a convention in Java programs), underscore or dollar sign. The variable name cannot be an already existing reserved word within the Java language (such as class or println).

Variables are declared in the following way:

dataType variableName;

Example: int price; char choice;

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;

2.8 Creating Constants


When programming you will find that there will be several instances where you would have data items within your program for which you do not want their value to change. These are known as constants and throughout the running of the program their value remains the same (for example the maximum score of an exam being 100). Constants are declared similar to variables however the declaration is preceded by the reserved word final. Example: final int score = 100;

2.9 Arithmetic Operators


Arithmetic Operation Addition Subtraction Multiplication Division Remainder (result of division process) Java Operator + * / %

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).

2.10 Expressions in Java


In the above examples, variable names have appeared on the left hand side of the assignment statements, however, the expression on the right hand side may also contain variables. If this is the case, then the name does not refer to the location but to the contents of the location.

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.11 Special Shorthand Instructions


In most of the programs you will be developing you will need to make use of incremental values i.e. values which are increased by 1. In Java we make use of special short hand instructions to do so. Therefore instead of writing: x = x + 1; //where x in a variable previously declared of type int We write: x++ //this is known as the increment operator Similarly we also have the decrement operator where instead of writing: x = x 1 We write: x-- //this is known as the decrement operator

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.

Or: System.out.print(Hello World);

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

Object of type Scanner 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.

2.14 Input Methods of the Scanner Class


The following are the lines of code you need to type in your program to read entries through the keyboard, depending on the variable type.

Type Int

Instruction Code x = sc.nextInt();

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.

Example: String name;

2.16 Program Design


Before you start working on a program it is important to design it i.e. consider and think exactly about how to build the software you are going to work on. Following this design, comes the implementation which is the actual coding of the program. Java consists of one or more classes (up until now we have seen only one class being created i.e. main), and each class can have one ore more methods within it (methods will be explained later on). It is important that you are aware that it is the instructions within each method that determines the behaviour of that method. The more complex the functionality of your methods, the more it becomes worthwhile and good practice to spend time designing your code/instructions that would make up your method. When designing your code you can make use of pseudocode. Pseudocode is English like statements which help you express the flow of your program without having to worry about the programming languages syntax errors (e.g. no semi colons or use of reserved words). Example: Begin Display program title Display prompt for user to enter price Enter price Display prompt for user to enter tax rate Enter tax rate Work out calculation -> total price = price + (price * tax) Display total price End

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

3.2 The if Statement


There will be times when you would like certain instructions to be executed only when a given condition is met To implement this you can make use of the if statement. The general form of this statement is as follows: if (/* test is entered here within brackets*/) { //instructions to be executed if the condition is met }

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

3.3 Comparison Operators


In most of the programs you will be developing you will frequently be making use of comparison operators. In the above example it is the less than (<) operator that is being used. The following is a table of the comparison operators available within Java: Operator == != < > >= <= Description Equal to Not equal to Less than Greater than Greater than or equal to Less than or equal to

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.5 The ifelse Statement


As seen in the above example, the If statement allows us to execute specific instructions based on a single choice/criteria. The ifelse statement allows us to build our program listing two alternative courses of action. Example: if ( /*test goes here within brackets */ ) { // instruction/s executed if the test is true } else { //instruction/s which are executed if the test is false }

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.

3.7 Logical Operators


Logical Operator AND OR NOT Java Equivalent && || !

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.

3.8 Nested ifelse Statements


Instructions within if and ifelse statements can themselves be any legal Java command. In particular they could contain other ifelse statements within them and this is known as nesting. Nesting allows for multiple choices to be processed. It is essential that the structure with which you nest multiple ifelse statements is correct as illustrated in the example below. It is also important to note and to remember that within Java, begin and end curly brackets i.e. { and } are not optional. Even if within your if statement you have only one line of code these need to be added.

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.

3.10 The switch Statement


When using a large amount of nested ifelse statements code may become difficult to manage and the slightest mistake in structure can easily change the logic of your code. An alternative would be to make use of the switch statement. A switch statement may be used when: Only one variable is being checked in each condition The check involves specific values of that variable and not ranges for that variable

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

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

4.2 The for Loop


The great thing about using loops is that own programs become drastically shorter and easier to manage. For example, imagine you wanted to display five lines on screen with each line containing 5 stars (*): ***** ***** ***** ***** ***** You would do the above by using the line of code: System.out.println(*****); and repeating this for 5 consecutive times. However you could also do it through the use of loops. The below table illustrates the difference between the use of these two approaches: Without the use of loops
public class PrintStars { public static void main(String[] args) { System.out.println(*****); System.out.println(*****); System.out.println(*****); System.out.println(*****); System.out.println(*****); } }

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:

for (int i = 1; i <= 5; i++)


Initialise counter to 1 (this may vary depending on the scope). Note: a counter is a variable which is created which is used to help us keep track of how many times we are going through the loop.

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.

4.4 Nested Loops


There will be instances when you will need to make use of a for loop within another for loop. These are known as nested loops i.e. loops within loops. A typical example of the use of nested loops is to draw a box of stars on screen.

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.5 The while Loop


The syntax and general structure used to make use of the while loop within Java is as follows: while ( /*test goes here*/ ) { // instructions to be executed repeatedly as long as test is true }

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.7 The dowhile Loop


The dowhile loop is very similar to the while loop only that the test of this loop occurs at the end of the loop rather than at the beginning. The main difference between these two loops is that since the dowhile loops has its test executed at the end of the loop, any instructions contained within this loop are executed at least once. Whereas with a while loop, if the test returns false, the code is never executed. A typical example of a common use of the dowhile loop is the display of a main menu i.e. the main menu is displayed at least once, and will continue to be displayed until the Quit option is selected. The main syntax structure of the dowhile loop is as follows: do { // instructions to be executed at least once } while ( /* test goes here */ );

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.

5.2 Calling a method


Once you have created your methods you can then call them as many times as you require. 1. The following is an example of a method which has been created within a class for which its function is to add two numbers:
public static void addTaxVoidNoParams() { // declare variables int value1 = 0; int value2 = 0; // object Scanner sc = new Scanner(System.in); System.out.println("Please enter the first value: "); value1 = sc.nextInt(); System.out.println("Please enter the second value: "); value2 = sc.nextInt(); int result = (value1+value2); System.out.println("The result of adding "+value1 + "and "+value2+ " is: "+result); }

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.3 Note on Method Parameters and Variables


Method parameters: A method cannot change the original value of a variable that was passed to it as a parameter. The reason being that being passed on to the method is a copy of whatever the variable contains i.e. just a value. The method does not have access to the original variable. Variable scope: variables are only visible within the pair of curly brackets in which they have been declared. If they are referred to in a part of the program outside these brackets you will get a compiler error. Variables that have been declared inside the brackets of a particular method are called local variables and these are said to being local to that method which is making use of them. We refer to variables as having a scope and this means that their visibility is limited to that particular part of the program.

5.4 Method Overloading


In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism.
public static void add(int a, int b) // 1 - A method with two parameters of type integer { int sum = a + b; System.out.println(\"Sum of a+b is \"+sum); } public static void add(int a, int b, int c) // 2 - A method with three parameters { int sum = a + b + c; System.out.println(\"Sum of a+b+c is \"+sum); } void add(double a, double b) // 3 A method with two parameters of type double { double sum = a + b; System.out.println(\"Sum of a+b is \"+sum); }

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).

6.2 Declaring and Creating Arrays


When you need to make use of an array, you first need to declare the data type of the array followed by the identifier i.e. name of array. Following, you then have to create it as shown below. In java you can combine the two steps above in a single statement (as illustrated further below). // Declaration of an array. like this: double[] temperature; To DECLARE an ARRAY we should declare it

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];

Example: Scanner sc = new Scanner(System.in); userinput = sc.nextDouble();

//to set the population of an element: temperature[6] = userinput; System.out.println(temperature[6]);

6.3 Initialising an Array


You may need to assign values directly to every element within your array. This can be done by using the following initialisation: double[] temperature = {9, 11, 10, 2, 3, 22};

6.4 Accessing Array Elements


It is important to remember that the first element within an array is index zero, for example, temperature[0]

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

Array Representation temperature Index 0 1 2 3 4 5 6 Content 10 12 11 9 8 7 10

6.5 The length Attribute


As you have seen above, when you need to make use of an array you must first declare and create it: double[] = temperature; temperature = new double[7];

or

double[] temperature = new double[7];

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]); } } }

6.6 Passing Arrays as Parameters within Methods


To pass an array as a parameter within methods you would do as follows: Example: public static void enterTemps(double[] temperatureIn) { //code instructions listed here }

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!

6.7 Returning an Array from a Method


An mentioned in the above section, 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! You can also however, also choose to return an array from a method. Follow the example provided below:
public static double[] enterTemps() { Scanner sc = new Scanner(System.in); //create an array within this method double[] temperatureOut = new double[20]; //fill in the array called temperatureOut which has been created in this method for (int i = 0; i < temperatureOut.length; i++) { System.out.println(Enter the max temperature for day +(i+1)); temperatureOut[i]= sc.nextDouble(); } //send back the populated array which you created within this method return temperatureOut; }

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()

6.8 The for loop enhanced for Arrays


Rather than making use of a counter to go through all of the elements with an array, we can make use of the enhanced for loop which consists of a variable that, upon each iteration, stores consecutive elements from the array. The following example illustrates the use of this for loop to go through an array called temperature and display all its contents on screen.

for(double item: temperature) { System.out.println(item); }

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.

6.9 Finding the maximum value within an Array


Very often you will need to analyse the data within your array to produce results. A typical example would be to identify the maximum value within an array (such as that of an array containing student marks). The pseudocode to do this is as follows:

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

The possible implementation for the above would be as follows:


/* the method will return an int value having been passed an array of type int as a parameter */ public static int max(int[] arrayIn) { //set the first array element = to the max Num int maxNum = arrayIn[0]; //loop through the array for (int i = 0; I < arrayIn.length; i++) { // If the element at position i is greater than the maxNum if (arrayIn[i] > maxNum { //set this value to maxNum maxNum = arrayIn[i]; } //return the max number found to the main method return maxNum; }

6.10 Finding the sum of all values within an Array


Another common function you may need to perform when using arrays is the summation of all of the data elements within your array. The pseudocode to do this is as follows:

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 implementation for the above would be as follows:

/* 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; }

6.11 Searching for a data element within an Array


When developing most of the programs you will be working on, you will find it is common that you will need to search for certain data, say, a value contained within an array. The following is the pseudocode to do so: Example: say we are searching through an array containing ID card numbers of students so that if a particular ID was already entered we do not re enter this!

Loop through all of the elements within the array If the current element is = to the search item Return true Else Return false

The implementation for the above would be as follows:


/* the method will return a Boolean value having been passed an array of type int as a parameter together with the data being searched for of type int */ public static boolean searchNum(int[] arrayIn, int valueIn) { for (int i = 0; i < arrayIn.length; i++) { if (arrayIn[i] == valueIn) { return true; } 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; } }

6.12 Multi-dimensional Arrays


A multi-dimensional array is one which has more than one index. To create a two-dimensional array (i.e. an array having 2 indexes) you would do as follows:
double [] [] temperature; temperature = new double [4] [7];

Row

Column

You can also initialise a multi-dimensional array with values, such as:
double [] [] temperature = { {11, 12, 10, 2} {23, 34, 46, 2} };

Or you can do the above by following:


double [] [] temperature = new double [2][4]; //initialise first row of values temperature[0][0] = 11; temperature[0][1] = 12; temperature[0][2] = 10; temperature[0][3] = 2;

//initialise second row of values


temperature[1][0] temperature[1][1] temperature[1][2] temperature[1][3] = = = = 23; 34; 46; 2;

6.13 Processing 2D Arrays


The processing of 2D arrays is very similar to that of one-dimensional arrays, however it is common to make use of a pair of nested loops.

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

You might also like