1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Tutorials object oriented programming wi

45 43 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 192 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth... Java supplies a primitive data type called Boolean, instan

Trang 1

Java Arithmetic Operators

The Java programming language has includes five simple arithmetic operators

like are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo)

The following table summarizes the binary arithmetic operators in the Java programming language

The relation operators in Java are: ==, !=, <, >, <=, and >= The meanings of these operators are:

op1 + op2 op1 added to op2

op1 - op2 op2 subtracted from op1

op1 * op2 op1 multiplied with op2

op1 / op2 op1 divided by op2

op1 % op2 Computes the remainder of dividing op1 by op2

The following java program, ArithmeticProg , defines two integers and two precision floating-point numbers and uses the five arithmetic operators to perform

double-different arithmetic operations This program also uses + to concatenate strings The arithmetic operations are shown in boldface

public class ArithmeticProg {

public static void main(String[] args) {

//a few numbers

Trang 2

//computing the remainder resulting

//from dividing numbers

System.out.println("Modulus");

System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); }

}

Trang 3

Java Assignment Operators

It's very common to see statement like the following, where you're adding something to a variable Java Variables are assigned, or given, values using one of the assignment operators The variable are always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment

operator The assignment operator is evaluated from right to left, so a = b = c = 0; would

assign 0 to c, then c to b then b to a

i = i + 2;

Here we say that we are assigning i's value to the new value which is i+2

A shortcut way to write assignments like this is to use the += operator It's one operator symbol so don't put blanks between the + and =

String str = new String("Hello");

//assign b to a, then assign a

//to d; results in d, a, and b being equal

int d = a = b;

Trang 4

Java Increment and Decrement Operators

There are 2 Increment or decrement operators -> ++ and These two

operators are unique in that they can be written both before the operand they are applied

to, called prefix increment/decrement, or after, called postfix increment/decrement The meaning is different in each case

There's another short hand for the general add and assign operation, += We would normally write this as i += 15 Thus if we wanted to count from 0 to 20 by two's we'd write:

Source Code

Trang 6

Java Relational Operators

A relational operator compares two values and determines the relationship between them For example, != returns true if its two operands are unequal Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth The relation operators in Java are: ==, !=, <, >, <=, and >= The meanings of these operators are:

op1 > op2 op1 is greater than op2

op1 >= op2 op1 is greater than or equal to op2

op1 < op2 op1 is less than to op2

op1 <= op2 op1 is less than or equal to op2

op1 == op2 op1 and op2 are equal

op1 != op2 op1 and op2 are not equal

Variables only exist within the structure in which they are defined For example, if a variable is created within a method, it cannot be accessed outside the method In addition,

a different method can create a variable of the same name which will not conflict with theother variable A java variable can be thought of

The main use for the above relational operators are in CONDITIONAL phrases The following java program is an example, RelationalProg, that defines three integer numbersand uses the relational operators to compare them

public class RelationalProg {

public static void main(String[] args) {

//a few numbers

//(they are equal)

//greater than or equal to

System.out.println("Greater than or equal to ");

Trang 7

System.out.println(" j < i = " + (j < i)); //false System.out.println(" k < j = " + (k < j)); //false //less than or equal to

System.out.println("Less than or equal to "); System.out.println(" i <= j = " + (i <= j)); //true System.out.println(" j <= i = " + (j <= i)); //false System.out.println(" k <= j = " + (k <= j)); //true //equal to

System.out.println("Equal to ");

System.out.println(" i == j = " + (i == j)); //false System.out.println(" k == j = " + (k == j)); //true //not equal to

System.out.println("Not equal to ");

System.out.println(" i != j = " + (i != j)); //true System.out.println(" k != j = " + (k != j)); //false }

}

Trang 8

Java Boolean Operators

The Boolean logical operators are : | , & , ^ , ! , || , && , == , != Java supplies

a primitive data type called Boolean, instances of which can take the value true or false only, and have the default value false The major use of Boolean facilities is to implementthe expressions which control if decisions and while loops

These operators act on Boolean operands according to this table

A B A|B A&B A^B !A

false false false false false true

true false true false true false

false true true false true true

true true true true false false

| the OR operator

& the AND operator

^ the XOR operator

! the NOT operator

|| the short-circuit OR operator

&& the short-circuit AND operator

== the EQUAL TO operator

!= the NOT EQUAL TO operator

Example

class Bool1{

public static void main(String args[]){

// these are boolean variables

Trang 9

Java Conditional Operators

Java has the conditional operator It's a ternary operator that is, it has three operands and it comes in two pieces, ? and :, that have to be used together It takes the form

Boolean-expression ? expression-1 : expression-2

The JVM tests the value of Boolean-expression If the value is true, it

evaluates expression-1; otherwise, it evaluates expression-2 For

Setting a single variable to one of two states based on a single condition is such a

common use of if-else that a shortcut has been devised for it, the conditional operator, ?: Using the conditional operator you can rewrite the above example in a single line like this:

max = (a > b) ? a : b;

Trang 10

Java If-Else Statement

The if-else class of statements should have the following form:

Compile and run this program and toss different inputs at it You should note that there's

no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all

Trang 11

What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { } The code inside the braces,

System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero In Java numerical greater than and lesser than tests are done with the > and < characters respectively We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively

Testing for equality is a little trickier We would expect to test if two numbers were equal

by using the = sign However we've already used the = sign to set the value of a variable Therefore we need a new symbol to test for equality Java borrows C's double equals sign, ==, to test for equality Lets look at an example when there are more then 1

statement in a branch and how braces are used indefinitely.

System.out.println("The number " + num + " is negative");

System.out.println("negative number are less than zero");

} else // false-branch {

System.out.println("The number " + num + " is positive");

System.out.print ("positive numbers are greater "); System.out.println("or equal to zero ");

} System.out.println("End of program"); // always executed }

}

All conditional statements in Java require boolean values, and that's what the ==, <, >,

<=, and >= operators all return A boolean is a value that is either true or false Unlike in

C booleans are not the same as ints, and ints and booleans cannot be cast back and forth

Trang 12

If you need to set a boolean variable in a Java program, you have to use the constants

true and false false is not 0 and true is not non-zero as in C Boolean values are no more integers than are strings

Trang 13

public static void main(String[] args)

We're not just limited to two cases though We can combine an else and an if to make

an else if and use this to test a whole range of mutually exclusive possibilities

Lets look at some examples of if-else-if:

//Example 1

if(color == BLUE)) {

System.out.println("The color is blue.");

}

else if(color == GREEN) {

System.out.println("The color is green.");

Trang 15

Java Loops (while, do-while and for loops)

A loop is a section of code that is executed repeatedly until a stopping condition is met Atypical loop may look like:

while there's more data {

Read a Line of Data

Do Something with the Data

}

There are many different kinds of loops in Java including while, for, and do while

loops They differ primarily in the stopping conditions used

For loops typically iterate a fixed number of times and then exit While loops iterate continuously until a particular condition is met You usually do not know in advance how many times a while loop will loop

In this case we want to write a loop that will print each of the command line arguments insuccession, starting with the first one We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using the

args.length Therefore we will write this with a for loop Here's the code:

Trang 16

Next comes the for loop The loop begins by initializing the counter variable i to be zero This happens exactly once at the beginning of the loop Programming tradition that dates back to Fortran insists that loop indices be named i, j, k, l, m and n in that order.

Next is the test condition In this case we test that i is less than the number of arguments When i becomes equal to the number of arguments, (args.length) we exit the loop and

go to the first statement after the loop's closing brace You might think that we should testfor i being less than or equal to the number of arguments; but remember that we began counting at zero, not one

Finally we have the increment step, i++ (i=i+1) This is executed at the end of each iteration of the loop Without this we'd continue to loop forever since i would always be less than args.length

Trang 17

Java Variables and Arithmetic Expressions

Java Variables are used to store data Variables have type, name, and value Variable

names begin with a character, such as x, D, Y, z Other examples are xy1, abc2, Count, N,sum, Sum, product etc These are all variable names

Different variable types are int, char, double A variable type tells you what kind of data can be stored in that variable

The syntax of assignment statements is easy Assignment statements look like this:

variableName = expression ;

For example:

int x; // This means variable x can store numbers such as 2, 10, -5

char y; // This means variable y can store single characters 'a', 'A'

double z; // This means variable z can store real numbers such as

10.45, 3.13411

The above are declarations for variables x, y and z

Important points:

1 Note that a variable has to be declared before being used

2 The values assigned to a variable correspond to its type Statements below represent assignment of values to a variable

x = 100; // x is an integer variable

y = 'A'; // y is a character variable

abc = 10.45; // abc is of type double (real numbers)

3 Both variable declaration and assignment of values can be done in same statement Forexample,

int x;

x = 100; is same as int x = 100;

4 A variable is declared only once

int x; // Declaration for x

Trang 18

x = 100; // Initialization.

x = x + 12; // Using x in an assignment statement

Often in a program you want to give a variable, a constant value This can be done:

2 Arithmetic Expressions

-An assignment statement or expression changes the value that is held in a variable Here

is a program that uses an assignment statement:

class example

{

public static void main ( String[] args )

{

long x ; //a declaration without an initial value

x = 123; //an assignment statement

System.out.println("The variable x contains: " + x );

}

}

Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and % The %

operator is the remainder or modulo operator Arithmetic expressions are used to assign arithmetic values to variables An expression is a combination of literals, operators, variables, and parentheses used to calculate a value

The following code describes the use of different arithmetic expressions

int x, y, z; // Three integer variables declared at the same time

Trang 19

x = 10;

y = 12;

z = y / x; // z is assigned the value of y divided by x

// Here z will have value 1

z = x + y; // z is assigned the value of x+y // Here z will have value22

z = y % x // z is assigned the value of remainder when y // is divided by x Here z will have value 2

Java Boolean expressions are expressions which are either true or false The different

boolean operators are < (less than), > (greater than),

== (equal to), >= (greater or equal to), <= (less or equal), != (not equal to)

Example:

int x = 10;

int y = 4;

int z = 5;

(x < 10) // This expression checks if x is less than 10

(y > 1) // This expression checks if y is greater than 1

((x - y) == (z + 1)); // This expression checks

// if (x - y) equals (z + 1)

A boolean expression can also be a combination of other boolean expressions Two or more boolean expressions can be connected using &&

(logical AND) and || (logical OR) operators

The && operator represents logical AND The expression is true only if both boolean expressions are true The || operator represents logical

OR This expression would be true if any one of the associated expressions is true

Example:

int x = 10; int y = 4; int z = 5;

(x <= 10) && (y > 1) // This expression checks if x is less

// than 10 AND y is greater than 1

// This expression is TRUE

(x*y == 41) || (z == 5) // This expression checks if x*y is equal

// to 40 OR if z is equal to 5

Trang 20

Methods (Includes Recursive Methods)

A method is a group of instructions that is given a name and can be called up at any point

in a program simply by quoting that name Each calculation part of a program is called a

method Methods are logically the same as C's functions, Pascal's procedures and

functions, and Fortran's functions and subroutines

When I wrote System.out.println("Hello World!"); in the first program

we were using the System.out.println() method The System.out.println()

method actually requires quite a lot of code, but it is all stored for us in the System libraries Thus rather than including that code every time we need to print, we just call the

System.out.println() method

You can write and call your own methods too Methods begin with a declaration This caninclude three to five parts First is an optional access specifier which can be public,

private or protected A public method can be called from pretty much anywhere A

private method can only be used within the class where it is defined A protected

method can be used anywhere within the package in which it is defined Methods that

aren't specifically declared public or private are protected by default access specifier We

then decide whether the method is or is not static Static methods have only one instance per class rather than one instance per object All objects of the same class share a single

copy of a static method By default methods are not static We finally specify the return

type

Next is the name of the method

Source Code

class FactorialTest { //calculates the factorial of that number.

public static void main(String args[]) {

Trang 21

for (i=1; i <= n; i++) {

Example (A Recursive Counterpart of the Above Factorial Method)

n! is defined as n times n-1 times n-2 times n-3 times 2 times 1 where n is a positive integer 0! is defined as 1 As you see n! = n time (n-1)! This lends itself to recursive calculation, as in the following method:

public static long factorial (int n) {

Trang 22

Arrays are generally effective means of storing groups of variables An array is a group ofvariables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array The number of variables that can be stored in an

array is called the array's dimension Each variable in the array is called an element of the

an array that will store both ints and Strings, for instance

Like all other variables in Java an array must be declared When you declare an array variable you suffix the type with [] to indicate that this variable is an array Here are some examples:

k = new int[3];

yt = new float[7];

names = new String[50];

The numbers in the brackets specify the dimension of the array; i.e how many slots it has

to hold values With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings

Ngày đăng: 08/05/2019, 19:53

w