130717666736980000

24
Methods & Arrays Lecture#6+7

Upload: tanzeel-ahmad

Post on 15-Aug-2015

15 views

Category:

Education


0 download

TRANSCRIPT

Methods & ArraysLecture#6+7

Overloading MethodsExample 4.3 Overloading the max Method

public static double max(double num1, double num2) {

if (num1 > num2) return num1; else return num2;}

Type CastingIf x is a float and y is an int, what will be the data

type of the following expression? x * yThe answer is float. The above expression is called a mixed expression. The data types of the operands in mixed

expressions are converted based on the promotion rules. The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision.

Explicit Type CastingExplicit type conversion is a type conversion which

is explicitly defined within a program (instead of being done by a compiler for implicit type conversion).

Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax:

( <data type> ) <expression>

Example (float) x / 3

(int) (x / y * 3.0)

Type case x to float and then divide it by 3.

Type case x to float and then divide it by 3.

Type cast the result of the expression x / y * 3.0 to int.

Type cast the result of the expression x / y * 3.0 to int.

ConstantsWe can change the value of a variable. If we want the value

to remain the same, we use a constant.

final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;

These are constants, also called named constant.

These are constants, also called named constant.

The reserved word final is used to declare constants.

The reserved word final is used to declare constants.

These are called literal constant.

These are called literal constant.

Sample Code Fragment//code fragment to input radius and output//area and circumferencefinal double PI = 3.14159;

double radius, area, circumference;

//compute area and circumferencearea = PI * radius * radius;circumference = 2.0 * PI * radius;

System.out.println("Given Radius: " + radius);System.out.println("Area: " + area);System.out.println(" Circumference: “ + circumference);

String Input Using a Scanner object is a simple way to input data from the

standard input System.in, which accepts input from the keyboard.

First we need to associate a Scanner object to System.in as follows:

After the Scanner object is set up, we can read data. The following inputs the first name (String):

import java.util.Scanner;

Scanner scanner;

scanner = new Scanner(System.in);

System.out.print (“Enter your first name: ”);String firstName = scanner.next();System.out.println(“Nice to meet you, ” + firstName + “.”);

Numerical InputWe can use the same Scanner class to input

numerical values

Scanner scanner = new Scanner(System.in);int age;System.out.print( “Enter your age: “ );age = scanner.nextInt();

Scanner MethodsMethod Example

nextByte( ) byte b = scanner.nextByte( );nextDouble( ) double d = scanner.nextDouble( );nextFloat( ) float f = scanner.nextFloat( );nextInt( ) int i = scanner.nextInt( );nextLong( ) long l = scanner.nextLong( );nextShort( ) short s = scanner.nextShort( );next() String str = scanner.next();

The Math class

The Math class in the java.lang package contains class methods for commonly used mathematical functions.

Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

double num, x, y;

x = …;y = …;

num = Math.sqrt(Math.max(x, y) + 12.4);

Some commonly use Math Class Methods

Method Description

exp(a) Natural number e raised to the power of a.

log(a) Natural logarithm (base e) of a.

floor(a) The largest whole number less than or equal to a.

max(a,b) The larger of a and b.

pow(a,b) The number a raised to the power of b.

sqrt(a) The square root of a.

sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)

Trigonometric Methods sin(double a)

cos(double a)

tan(double a)

acos(double a)

asin(double a)

atan(double a)

Exponent Methods exp(double a)

Returns e raised to the power of a.

log(double a)Returns the natural logarithm of a.

pow(double a, double b)Returns a raised to the power of b.

sqrt(double a)Returns the square root of a.

Rounding Methods double ceil(double x)

x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x)

x is rounded down to its nearest integer. This integer is returned as a double value.

double rint(double x)x is rounded to its nearest integer. If x is equally close to two integers, the even

one is returned as a double. int round(float x)

Return (int)Math.floor(x+0.5). long round(double x)

Return (long)Math.floor(x+0.5).

min, max, abs, and random

max(a, b)and min(a, b)Returns the maximum or minimum of two parameters.

abs(a)Returns the absolute value of the parameter.

random()Returns a random double valuein the range [0.0, 1.0).

Chapter 5 Arrays

Introducing Arrays

Declaring Array Variables, Creating Arrays, and Initializing Arrays

Passing Arrays to Methods

Introducing ArraysArray is a data structure that represents a collection of the same types of data.

myList[0]

myList[1]

myList[2]

myList[3]

myList[4]

myList[5]

myList[6]

myList[7]

myList[8]

myList[9]

double[] myList = new double[10];

myList reference

An Array of 10 Elementsof type double

Declaring Array Variablesdatatype[] arrayname;

Example:

double[] myList;

datatype arrayname[];

Example:

double myList[];

Creating ArraysarrayName = new datatype[arraySize];

Example:myList = new double[10];

myList[0] references the first element in the array.

myList[9] references the last element in the array.

Declaring and Creatingin One Step

datatype[] arrayname = new datatype[arraySize];

double[] myList = new double[10];

datatype arrayname[] = new datatype[arraySize];

double myList[] = new double[10];

The Length of ArraysOnce an array is created, its size is

fixed. It cannot be changed. You can find its size using

arrayVariable.length

For example,myList.length returns 10

Initializing ArraysUsing a loop:for (int i = 0; i < myList.length; i++) myList[i] = i;

Declaring, creating, initializing in one step:double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one statement.

Declaring, creating, initializing Using the Shorthand Notation

double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the following statements:

double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

CAUTIONUsing the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong:double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};

Passing Arrays to Methods Java uses pass by value to pass parameters to a method. There are important differences between passing a value of variables of primitive data types and passing arrays.

For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method.

For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.

THE END