Java Chapters 1-6

download Java Chapters 1-6

of 50

Transcript of Java Chapters 1-6

  • 7/27/2019 Java Chapters 1-6

    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 etcSystem 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

    software

    These are software programs which are specific in performing a given task. Such

    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

    Languages which is purposely designed and created to allow for programs to be

    developed.

    Examples include; C++, Pascal, Java, etcProgram/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

  • 7/27/2019 Java Chapters 1-6

    2/50

    Figure 1: Compiling Process

    If (age >= 18)

    {

    System.out.println(You can vote!);

    }

    The Programmer types in the source code to

    create a software application

    Compiler

    100011101

    010101001

    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.

  • 7/27/2019 Java Chapters 1-6

    3/50

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

    If (age >= 18)

    {

    System.out.println(You can vote!);

    }

    The Programmer types in the source code to

    create a software application

    Java Compiler

    100011101

    010101001

    101010100

    101010101

    JVM

    The Java Compiler does NOT translate the source code

    into machine code, BUT rather intoJava Byte Code

    101010101010

    100010100101

    101010101011

    000011010101

    011110101101

    101011110011

    000111001101

    101011100110

    000011100011

    Machine code or PC Machine code or UNIX Machine code or MAC

    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.

  • 7/27/2019 Java Chapters 1-6

    4/50

    Important notes:

    The Java Byte Code contains instructions which are universal. These instructions are similar to machinecode 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 computerrequiring 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 theJDK 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, Javaprograms 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 whichcould 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

    http://www.java.sun.com/http://www.java.sun.com/http://www.java.sun.com/http://www.jcreator.com/http://www.jcreator.com/http://www.jcreator.com/http://www.jcreator.com/http://www.java.sun.com/
  • 7/27/2019 Java Chapters 1-6

    5/50

    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.

  • 7/27/2019 Java Chapters 1-6

    6/50

    2.3 Creating your first program

    Important Java rules to note:

    1. In Java we do not write programs but rather classes.2. The name of the class has to start with an uppercase letter.3. Only class name and file names should start with an uppercase letter.4. The name of the file HAS TO match the name of the class i.e. in the above example, the file mustbe

    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 andtrying to identify errors within your code.

    2.4 Activities

    Activity 1

    1. Open JCreator2. Click on: File New File3. 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 program5. Compile it using the Build File button, ( ), or through the Build menu option6. Run the program using the Run File button, ( ), or through the Run menu option

    What is displayed on screen?

    public class HelloWorld

    {

    public static void main(String[] args)

    {

    System.out.println("hello world");

    }

    }

  • 7/27/2019 Java Chapters 1-6

    7/50

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

    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.

    // 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 multiplelines of comments without having to type in double slash characters every time I start anew line */

  • 7/27/2019 Java Chapters 1-6

    8/50

    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 Description Range of values/FormatIntegers

    Byte Very small integers -128 to 127

    short Small integers -32768 to 32767

    Int large integers -2147483648 to 2147483647

    Long Very large integers -9223372036854775808 to 9223372036854775807

    Real

    float Real numbers +/-1.4 * 10-45 to 3.4 * 1038

    double Very large real numbers +/-1.4 * 10-324

    to 1.8 * 10308

    Special

    Char Single characters Unicode character set

    boolean Boolean value 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 symbolssuch as + or -.

    They should start with a lowercase letter (this is a convention in Java programs), underscore or dollarsign.

    The variable name cannot be an already existing reserved word within the Java language (such as classor println).

    Variables are declared in the following way:

    dataType variableName;

  • 7/27/2019 Java Chapters 1-6

    9/50

    Example:

    It is good practice to initialise your variables as follows:

    Example:

    Or

    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:

    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:

    int price;

    char choice;

    int price = 0;

    double total = 0;

    int price, total;

    price = 0;total = 0;

    int price;

    double total;

    price = 0;

    total = 0;

    char choice = A;

  • 7/27/2019 Java Chapters 1-6

    10/50

    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:

    2.9 Arithmetic Operators

    Arithmetic Operation Java Operator

    Addition +

    Subtraction -

    Multiplication *

    Division /

    Remainder (result of division process) %

    The above operators can be used within assignment statements.

    Example:

    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.

    final int score = 100;

    int x; //declaring variable

    x = 10+5; //performing an addition through the use of an assignment statement

  • 7/27/2019 Java Chapters 1-6

    11/50

    Example:

    The variable you used on the left hand side of the assignment statement may also be used on the right hand

    side contemporarily.

    Example:

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

    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

    price = price * (1 + tax/100);

    The old value

    of price

    The new value

    of price

  • 7/27/2019 Java Chapters 1-6

    12/50

    2.12 Outputs

    To display a message on screen using Java we make use of the following line of code:

    Or:

    Example:

    The above code will output the text in the following manner:

    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.

    System.out.print(Hello World);

    print instructs your program to output anything

    that follows in the brackets on the same line.

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

    }

    }

    Hello World

    Hello World again Bye Bye

  • 7/27/2019 Java Chapters 1-6

    13/50

    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:

    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:

    With the above line of code you are creating a new object called sc of the Scanner class.

    Therefore:

    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.

    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;

    Scanner sc = new Scanner(System.in);

    Scanner sc = new Scanner(System.in);

    Class Object of type

    Scanner class

    Keyboard

    representation

  • 7/27/2019 Java Chapters 1-6

    14/50

    Type Instruction Code

    Int 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:

    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:

    Also, you can make use of the assignment operator (equals (=) sign) when using strings.

    Example:

    system.out.println(Hello + World);

    System.out.println(Total price is: + (10 * 1.83));

    name = John Smith;

  • 7/27/2019 Java Chapters 1-6

    15/50

    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:

    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 tobuild 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 ofpseudocode. 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:

    String name;

    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

  • 7/27/2019 Java Chapters 1-6

    16/50

    2.17 Activities

    1. Create a program that will ask a user to enter his/her name and surname and display these as an outputon 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 thefollowing: 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 returnsthe total cost (price + VAT)

    6. Write a program which asks for 3 values and returns the multiplication on screen7. Write a program which reads in three integer values and outputs these again on screen

  • 7/27/2019 Java Chapters 1-6

    17/50

    Chapter 3

    3.1 Selection

    Up until now the programs that you have created were all executed in sequence i.e. one instruction after theother, 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. ifstatement2. ifelse statement3. 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 ifstatement.

    The general form of this statement is as follows:

    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 (/* test is entered here within brackets*/)

    {

    //instructions to be executed if the condition is met

    }

  • 7/27/2019 Java Chapters 1-6

    18/50

    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.

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

    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");

    }

    }

  • 7/27/2019 Java Chapters 1-6

    19/50

    The following are two test runs of the above program:

    ***

    3.3 Comparison Operators

    In most of the programs you will be developing you will frequently be making use ofcomparison operators. In

    the above example it is the less than ( Greater than

    >= Greater than or equal to

  • 7/27/2019 Java Chapters 1-6

    20/50

    3.5 The ifelse Statement

    As seen in the above example, the Ifstatement 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:

    3.6 Activities

    1. Write a program which asks the user to enter the price of an item. If the entered price is over EUR100, 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 isequal 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 thisinformation. 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 thestudent 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 thendisplay 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 Java Equivalent

    AND &&

    OR ||

    NOT !

    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

    }

  • 7/27/2019 Java Chapters 1-6

    21/50

  • 7/27/2019 Java Chapters 1-6

    22/50

    import java.util.*;

    public class ScoutsTimeTable

    {

    public static void main(String[] args)

    {

    char group; //declare variable to store the scout groupScanner 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 checksare made to output the corresponding grade ofthat 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.

  • 7/27/2019 Java Chapters 1-6

    23/50

    switch (variableName)

    {

    case value1: //instructions to be executed

    break;

    case value2: //instructions to be executed

    break;

    default: //instructions to be executed

    }

    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:

    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.

    Variable being tested. This can be of type

    int, char, long, byte or short

    Possible value being tested

    Possible value being tested

    This is the optional statement (otherwise

    or anything else value

  • 7/27/2019 Java Chapters 1-6

    24/50

    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

    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.

    3.11 Activities

    1. Consider a bank that offers four different types of accounts: a, b, c and x. the following illustrates theannual 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%

  • 7/27/2019 Java Chapters 1-6

    25/50

    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 isassociated with a minimum balance as shown.

    account a = 250 account b = 1000 account c = 250 account x = 5000Adapt 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 statementfor every value calculated within the switch.

  • 7/27/2019 Java Chapters 1-6

    26/50

    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 onethat is used to control such repetition and is known as a loop.

    There are three types of loops within Java:

    1. for loop2. while loop3. 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 Using 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(*****);

    }

    }

    public class PrintStars

    {

    public static void main(String[] args)

    {

    for (int i =1; i

  • 7/27/2019 Java Chapters 1-6

    27/50

    In the above example we are making use of a for loop for which its structure is as follows:

    for (int i = 1; i

  • 7/27/2019 Java Chapters 1-6

    28/50

    import java.util.*;

    public class DisplayBoxOfStars

    {

    public static void main(String[] args)

    {for (int i = 1; i

  • 7/27/2019 Java Chapters 1-6

    29/50

    do

    {

    // instructions to be executed at least once

    } while ( /* test goes here */ );

    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

  • 7/27/2019 Java Chapters 1-6

    30/50

    d. Divisione. 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.

  • 7/27/2019 Java Chapters 1-6

    31/50

    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.

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

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

  • 7/27/2019 Java Chapters 1-6

    32/50

    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...) itcannot 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 toadd two numbers:

    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 beingpublic it can be called either from within the main program where it hasbeen 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 fromwithin any other methods.

    Having set this method to void, it will not return any data to the main method.

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

    }

  • 7/27/2019 Java Chapters 1-6

    33/50

    Not having passed any parameters to this method means that the required information will beobtained 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 toit from the main method.

    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 offirstValue and val2 is assigned the value ofsecondValue.

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

    }

  • 7/27/2019 Java Chapters 1-6

    34/50

    3. There will be instances when you will require your methods to return data back to the main method. Thefollowing is an example of such a method:

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

    wheremyValue 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 thereforewhen you call it from main you need to set a variable of the return type (same as before).

    To call this method from the main method you would do so by:

    int total = addTaxWithReturnNoParams();

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

    }

    public static int addTaxWithReturnNoParams()

    {

    int value1 = 30;

    int value2 = 10;

    int result = (value1+value2);

    return result;

    }

  • 7/27/2019 Java Chapters 1-6

    35/50

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

    }

  • 7/27/2019 Java Chapters 1-6

    36/50

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

    6. Create a program which will display a menu to the user which will enable him/her to perform conversionsfrom 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 itand if greater the new value of the maximum is set. Continue doing this until the end. Use the same

    reasoning for lowest mark.

  • 7/27/2019 Java Chapters 1-6

    37/50

    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 tomake 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 ofint value,

    another can be used to hold a collection ofchar 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).

    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.

    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.

    // Declaration of an array. To DECLARE anARRAY we should declare it

    like this:

    double[] temperature;

    // Creation of an array. To CREATE anARRAY, and therefore being ableto be used:

    temperature = new double[7];

    // we can DECLARE and CREATE an array in one single statement:

    double[] temperature = new double[7];

  • 7/27/2019 Java Chapters 1-6

    38/50

    Example:

    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:

    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:

    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:

    Scanner sc = new Scanner(System.in);

    userinput = sc.nextDouble();

    //to set the population of an element:

    temperature[6] = userinput;

    System.out.println(temperature[6]);

    double[] temperature = {9, 11, 10, 2, 3, 22};

    temperature[1] = sc.nextInt();

  • 7/27/2019 Java Chapters 1-6

    39/50

    Example:

    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 thatcurrent 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:

    for (int i=0; i

  • 7/27/2019 Java Chapters 1-6

    40/50

    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:

    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 ofthe array you are calling.

    Example:

    Or

    You may however not know the size for which you require your array at design and implementation stage. Itcould 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.

    double[] = temperature;

    temperature = new double[7];

    double[] temperature = new double[7];

    System.out.println(temperature.length);

    for (int i =0; i < temperature.length; i++)

    {

    //code goes here

    }

  • 7/27/2019 Java Chapters 1-6

    41/50

    Example:

    6.6 Passing Arrays as Parameters within Methods

    To pass an array as a parameter within methods you would do as follows:

    Example:

    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

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

    }

    }

    }

    public static void enterTemps(double[] temperatureIn)

    {

    //code instructions listed here

    }

  • 7/27/2019 Java Chapters 1-6

    42/50

    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.

    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 themain i.e. temperature, they

    both are pointing to the same place in memory so both are modifying the same array!

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

    }

    }

    }

  • 7/27/2019 Java Chapters 1-6

    43/50

    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 themain 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:

    Working with the above example, the main method will then look something like this:

    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.

    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;

    }

    //the following instructions are found within the main method

    double[] temperature;

    temperature = enterTemps()

  • 7/27/2019 Java Chapters 1-6

    44/50

    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

    for(double item: temperature)

    {

    System.out.println(item);

    }

  • 7/27/2019 Java Chapters 1-6

    45/50

    The possible implementation for the above would be as follows:

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

    }

  • 7/27/2019 Java Chapters 1-6

    46/50

    The implementation for the above would be as follows:

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

    }

  • 7/27/2019 Java Chapters 1-6

    47/50

    The implementation for the above would be as follows:

    You may also need to return the index value of where the found data item resides within the array.

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

    }

    }

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

    }

    }

  • 7/27/2019 Java Chapters 1-6

    48/50

    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:

    You can also initialise a multi-dimensional array with values, such as:

    Or you can do the above by following:

    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.

    double [] [] temperature;

    temperature = new double [4] [7];

    Row Column

    double [] [] temperature = {

    {11, 12, 10, 2}

    {23, 34, 46, 2}

    };

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

    temperature[1][1] = 34;

    temperature[1][2] = 46;

    temperature[1][3] = 2;

  • 7/27/2019 Java Chapters 1-6

    49/50

    6.14 Activities

    1. Create a program using arrays which will ask the user to enter the size of the array and then populate itwith 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 10marks 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 mark2. find a maximum mark3. find a minimum mark4. find an average mark5. display all marks6. display all marks in ascending order

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

    }

    }

  • 7/27/2019 Java Chapters 1-6

    50/50

    7. ExitThe marks display should be accompanied by the position within the array which starts from index 1.

    Use methods having array type parameters where necessary