Tuesday, March 12, 2013

Java Math basics

Maths Operators

The maths operators in the figure below, probably look familiar.

The basic set of Java arithmetic operators is presented in the figure.

  • Multiplication

  • Division

  • Modulo

  • Addition

  • Subtraction

The operators have been split into two groups to indicate their ‘precedence’ - the order in which they are obeyed.

 

Order of precedence

Multiplication, division and modulo operations are carried out before addition and subtraction.

If a calculation contains operators of the same precedence, the calculation is performed from left to right.

int j;
    int n = 2;
    j = n + 5; // Set to to 7
    j = n * 2; // Set to 4
    j = 3 + 3 * 2; // Set to 9
    j = n * ( 5 + 2 ) * 2 // Set to 28
    j = 25 - 3 // Set to 22

We can use parenthesis (brackets) to group calculations and force them to be carried out in a particular order.

Wherever brackets are used, the items within them are calculated first.

For instance, the sum 10 + 20 multiplied by 100 produces the result 3000. It could be tempting to write that equation as follows:

     10 + 20 * 100

However, due to the order of precedence in which arithmetic operations are performed, the sum is performed as if it had been written 10 + ( 20 * 100 ) producing the result 2010.

Note: Spaces are only required on either side of an operator for easy readability.

Integer Division

The Integer data type is a whole-number numeric data type. Where integer division is being performed, only the integer part of the result is returned.

For instance, if you type 13 / 5 into a calculator, you will see the result is 2.6.
However, when you perform integer division in a programming language, such as Java, the result of the same calculation is 2 - only the integer (whole number) part is returned as the result.

Double Division

The double data type is a floating point numeric data type..

Where double division is performed, the result is returned as a floating point number. Once again, using the example of 15 / 5, the result returned from double division is 2.6.

The % operator (modulo)

This operator returns the remainder of division of one number by another number.

int examples

For instance, 10 / 2 has a remainder of 0. This is because 10 is divided by 2 exactly.

Another example, 15 / 2 has a remainder of 1. This is because, after division has taken place (15 can be divided 7 times), 1 is left over.

More examples:

    int x;
    x = 12 % 4; // Set to 0
    x = 12 % 3; // Set to 0
    x = 12 % 5; // Set to 2
    x = 50 % 7; // Set to 1
    x = 100 % 33; // Set to 1
    x = 100 % 5; // Set to 0
    x = 30 % 9; // Set to 3

Remember, the remainder of an integer division only returns the integer part of the result.
 
For instance, if you were to type 4 / 3 into a calculator, you would see the result is 1.3333333 etc. However, where this calculation is being performed as integer division in a programming language, such as java, only the integer part is returned - producing the result 1.

Using % to convert cents into dollars

Let’s say we want to convert an int amount of cents (577) into dollars and cents.
The algorithm is as follows:

inputs - numOfCents
outputs - numOfDollars, centsRemaining
processing tasks -
    • get numOfCents
    • numOfDollars = numOfCents / 100
    • centsRemaining = numOfCents % 100


Remember, integer division returns the integer part of the result, so the statement

    dollars = numOfCents / 100

will return 5, in this example.

Monday, March 4, 2013

Overriding Methods

Method overriding allows us to provide our own implementation of a method in a child class.

"Overriding and Hiding Methods (The Java™ Tutorials > Interfaces and Inheritance)" ( http://bit.ly/Zn8eop )

"Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)" ( http://bit.ly/PYQDIV )

Tuesday, February 26, 2013

String.valueOf

DOWNLOAD THE CODE: StringValueOfPkg

Why use this function?
You want to treat a number like a String.

String.valueOf()
The String class has a function call valueOf(). This function will return the String representation of all the numeric data types (int, double, boolean, char, etc).

In the example below, two numbers are stored as int. The first print statement attempts to print each int as if they were strings. In this case, we would be hoping to see 100200 printed to screen. Notice that the concatenation operator is used - which, if you place between 2 numbers, becomes the addition operator.

The second print statement uses the String.valueOf() function. The function, as it is being used here, will return the String representation of each int.

The output for each statement is very different. The first print statement has caused the two int variables to be added (addition) together, whereas the second print statement has caused each int to be printed as a String.



Also see:
"Java - String valueOf() Method" ( http://bit.ly/YSRK2u )

Here's a cat:


Monday, February 25, 2013

Unicode

"Unicode (The Java™ Tutorials > Internationalization > Working with Text)" ( http://bit.ly/13gWvIM )

"Unicode Chart" ( http://bit.ly/13gX0m1 )

Character wrapper class for char

"Characters (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)" ( http://bit.ly/LUgCyw )

Methods and method parameters

Consider a method (also called a behaviour) for logging on to a network. When a user logs on, we could reasonably assume that the user must provide a username and password. A method for logging on could look like this:


This method signature can be broken down as follows:

public - The visibility of the method. A method that is public (as opposed to private) can be seen by other classes.

void - This indicates that the method will not return a value. Some methods return values (as in the case of the Scanner’s nextInt() function).

login - This is the name of method. Method names are named in the same way as variables in that they should start with a lower case letter. If the method name contains serveral words, each subsequent word starts with an uppercase letter. Method names must be unique - except where method overloading is used.

(String userName, String password) - This is the parameter list for method. When a method requires some data to perform its task, a list of that data is specified. This parameter list contains 2 parameters (although a parameter list may contain more, less or no parameters). 

Each parameter has a name, a type and is separated by a comma.

Getting input

DOWNLOAD THE CODE: InputFromScannerPkg

The Scanner class
A class is a template for an object. A class contains methods for performing particular tasks. From one class we can create many object instances.

The Scanner class belongs to the Java library of classes. It contains methods for reading many different types of data, from different types of input.

System.out
You have already seen System.out in action when we print to the console. This is the default stream for output.

This statement causes the words “Print this’ to be printed to the console in Eclipse.

System.out.println(“Print this”);

What you cannot see, however, are the special line ending characters which this method places at the end of the line. When subsequent lines are printed using println(), they each begin on a new line.

Here’s a different way to print to the console:

System.out.print(“Print this”);

Notice that we are now using the print() method. This method does not include special line ending characters. Each subsequent line of characters that is printed using print() will begin immediately where the last line of characters left off.




and the output...


System.in
The following code example uses Scanner’s nextInt() method to read an int input from System.in (default input from console). The input is assigned to the int variable called aNumber.

Scanner myScanner = new Scanner(System.in);
int aNumber = myScanner.nextInt();


Scanner can be told to read different types of data - or tokens. By default, Scanner uses whitespace characters as delimiters of tokens (the characters that separate tokens).

In the case of the nextInt() function, Scanner is using whitespace to delimit tokens, and return the token as an int. (seen in the figure below).

Other Scanner functions of note include:

next() - Return the next token, of any type.
next(String pattern) - the next token is delimited by the pattern supplied as a parameter.
nextLine() - reads the current line and returns it.



and the output...

In the figures above, the user is prompted to enter information. Methods of the scanner class are used to read the input typed into the console, and assign it to variables. The variable values are then printed to the console.

You can read the entire Scanner class specification here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Java I/O and Import statements
When we wish to use Scanner:
At the top of the code file we import a reference to the Scanner class by using the line:

import java.util.Scanner;

This line says that we intend to use the class called Scanner from the package called java.util.

In Java, all input and output (I/O) is performed by importing methods from the java.io or java.util packages.

Any source of input or destination of output is called a stream: keyboard, screen, network connection, a file, etc., are all streams.

There are three predefined Streams already open and ready to use in every program:
  •     System.in
  •     System.out
  •     System.err



Object Instantiation
To use the Scanner class, we must first declare an instance of Scanner and give it a name. Similar to declaring a variable in that we declare a type and an identifier. In this case, the type is Scanner.

As well as being declared, an object also needs to be instantiated. The use of the new keyword, instantiates the object called myScanner from the Scanner class.

Scanner myScanner = new Scanner(System.in);

In the next statement, we declare an int variable and assign it the value of the next int that is returned myScanner’s nextInt() function.


int aNumber = myScanner.nextInt();

You will notice that when we instantiated a Scanner object, we have also included System.in, inside of the parenthesis (round brackets). This is an example of passing data to a method. Often, a method needs data passed to it so that it can perform its task.

System.in is the input stream from the keyboard, via the Java console, so, we are telling the Scanner object to use this as its source.