Top Banner
Introduction to Java Fundamentals Continued Chapter 3
65

Introduction to Java Fundamentals Continued Chapter 3.

Jan 02, 2016

Download

Documents

Allan Randall
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Java Fundamentals Continued Chapter 3.

Introduction to Java

Fundamentals ContinuedChapter 3

Page 2: Introduction to Java Fundamentals Continued Chapter 3.

Collabedit

• www.collabedit.com• Collabedit is an online code editor that lets

people collaborate in real-time. • It works in your web browser so no

installation is needed.

Page 3: Introduction to Java Fundamentals Continued Chapter 3.

Variables• In Java, every variable has a type. • You declare a variable by placing the type first, followed by

the name of the variable. Here are some examples:– double salary;– int vacationDays;– long earthPopulation;– boolean done;

• Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

• A variable name must begin with a letter and must be a sequence of letters or digits.

Page 4: Introduction to Java Fundamentals Continued Chapter 3.

Initializing Variables

• Variables are intialized using “=“• ‘Variable name’ = ‘value’• For example:– int vacationDays;– vacationDays = 12;

• You can both declare and initialize a variable on the same line. For example:– int vacationDays = 12;

Page 5: Introduction to Java Fundamentals Continued Chapter 3.

Constants

• the keyword final to denote a constant• you can assign to the variable once, and then

its value is set once and for all. – It is customary to name constants in all uppercase.

• A class variable is any field declared with the static modifier– this tells the compiler that there is exactly one

copy of this variable in existenc

Page 6: Introduction to Java Fundamentals Continued Chapter 3.

Constants Examplepublic class Constants2

{

public static void main(String[] args)

{

double paperWidth = 8.5;

double paperHeight = 11;

System.out.println("Paper size in centimeters: ” + paperWidth * CM_PER_INCH + "

by " + paperHeight * CM_PER_INCH);

}

public static final double CM_PER_INCH = 2.54;

}

Page 7: Introduction to Java Fundamentals Continued Chapter 3.

Operators

• Operators are used for:–Arithmetic math (+, -, *, /, ++, --, %)–Relational operators (==,>, <=, &&)–Bitwise math (|, &, >>, <<)

• One issue of which a programmer must be aware is conversion or casting

Page 8: Introduction to Java Fundamentals Continued Chapter 3.

Arithmetic Operators

• Basic arithmetic– a+b return the sum of a and b– a-b return the difference of a and b– a*b return the product of a and b– a/b return the quotient of and b– a%b return the remainder of a/b (modulus)

• If both operands are integer types, the result is an integer

• If either or both operands are floating-point types, the result is a float

Page 9: Introduction to Java Fundamentals Continued Chapter 3.

Arithmetic Operators

• Basic arithmetic– a+=b sets a equal to the sum of a and b– a-=b sets a equal to the difference of a and b– a*=b sets a equal to the product of a and b– a/=b sets a equal to the quotient of and b– a%=b sets a equal to the remainder of a/b

• For any operator @: a@=b is equivalent to a=a@b

Page 10: Introduction to Java Fundamentals Continued Chapter 3.

Arithmetic Expressions

• Dividing any integer type by 0 will raise an exception– Covered later in the course– For now, avoid dividing by 0!

• Dividing any floating-point by 0 sets the result to a special value indicating infinity or NaN (Not a Number)– Does not raise an exception

Page 11: Introduction to Java Fundamentals Continued Chapter 3.

Increment and Decrement

• Post-Post increment and decrement– a++ or mynum++ is like a+=1 or mynum+=1– b-- or students-- is like b-=1 or students-=1

• If used in an expression, a post-increment or decrement evaluates to the value of the variable before the post-inc or dec

• For example, the following code prints “3”int b,a=3;b = a++;System.out.printf(“%d”,b);

Page 12: Introduction to Java Fundamentals Continued Chapter 3.

Increment and Decrement Cont’• Pre-increment and decrement• ++mynum is also like mynum+=1• --students is also like students-=1• However, pre-increment and pre-decrement

return the value of the variable after the operation

• For example, the code below returns “4”int b,a=3;b = ++a;System.out.printf(“%d”,b);

Page 13: Introduction to Java Fundamentals Continued Chapter 3.

Relational Operators• Always return the boolean true or false values– a==b returns true only if a and b are equal– a!=b returns true when a and b are not equal– a<b returns true if a is less than b, false otherwise– a>b returns true is a is greater than b, false otherwise– a<=b returns true if a is less than or equal to b– a>=b returns true if a is greater than or equal to b– !(expr) returns true if expr is false, of false if expr is true

• Short-circuit operators– a && b returns true only if both a and b are true– a || b returns true if either a or b is true, false otherwise

Page 14: Introduction to Java Fundamentals Continued Chapter 3.

Ternary Operator• Takes the form of expr?val1:val2• If expr is true, val1 is returned• If expr is false, val2 is returned• Example:

double qdouble r;r = 2.5;r *= 5.4/9.1;q = (r>1.5)?3.5:2.5;

• If r>1.5, q =3.5, otherwise, q=2.5

Page 15: Introduction to Java Fundamentals Continued Chapter 3.

Bitwise Operators

• Generally used on integer types– a|b performs a bitwise OR

• If a bit in either a or b is 1, the corresponding output bit is 1

– a&b performs a bitwise AND• If a bit in both a and b is 1, the output bit is 1, otherwise 0

– a^b performs a bitwise XOR• If one bit is 1 and one 0, the output bit is 1, otherwise 0

– ~a negates each bit• 0111 becomes 1000

Page 16: Introduction to Java Fundamentals Continued Chapter 3.

Bitwise Shift Operators• a<<n shifts each bit in a n places to the left – eg, 1<<3 shifts each bit 3 places left– Also equivalent to multiplying a by 2^n– Bits added at right are always 0

• a>>n shifts each bit in a n places to the right, sign extending it– If the leftmost bit was 1, bits added are 1– If the bit was 0, bits added are 0

• a>>>n is the same as a>>n, except bits added are always 0– Equivalent to dividing a by 2^n

Page 17: Introduction to Java Fundamentals Continued Chapter 3.

Simple Math Methods• Math.sqrt(a); returns square root of a• Math.pow(a,n); raises a to the nth power• Trig functions

– Math.sin(a); – Math.cos(a);– Math.tan(a);– Math.atan(a); – Math.atan2(a);

• Exponential function and inverse– Math.exp(a); returns e^a– Math.log(a); returns the log base e of a

• Simply add: import static java.lang.Math.*

Page 18: Introduction to Java Fundamentals Continued Chapter 3.

Type Conversion

• Automatic promotion is performed when necessary:

Page 19: Introduction to Java Fundamentals Continued Chapter 3.

Type Casting• Force conversion from one type to another when necessary• Information may be lost• Up to the programmer to determine whether loss of precision is

acceptable• short x = 5, y = 12; The following assignment statement will produce a

compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

• short z = x + y; // Error: no conversion from int to short To fix this problem, use a cast:

• short z = (short)(x + y); // OK• : explicit conversion It is possible though to use the following statements,

where the destination variable has the same storage size or a larger storage size:

• int m = x + y; long n = x + y;

Page 20: Introduction to Java Fundamentals Continued Chapter 3.

String API

• All strings are instances of class String• String greeting = “hello”;• String code_block = “for(x=0;x<2;x++) i*=2;”;• Strings are immutable• Strings can be changed with substrings and

concatenation (discussed momentarily)

Page 21: Introduction to Java Fundamentals Continued Chapter 3.

String API cont’

• Fetch character at location:– greeting.charAt(0); //’H’– greeting.charAt(4); //’o’

• First character is at position 0, not 1• Retrieve substring:– greeting.substring(1,3); //”el”– First parameter is first character of string to copy

• Second parameter is first char NOT to copy

Page 22: Introduction to Java Fundamentals Continued Chapter 3.

String API cont’

• Concatenation• Uses (overloads) the + operator• Changing “hello” to “help”:– greeting = greeting.substring(0,3)+”p”;

• Note: use of substring and concatenation• Comparing Strings– greeting.equals(“help”) returns false– greeting.equalsIgnoreCase(“HeLLo”) returns true

• Textbook shows full set of String methods

Page 23: Introduction to Java Fundamentals Continued Chapter 3.

Online Documentation• http://download.oracle.com/javase/6/docs/api/

Page 24: Introduction to Java Fundamentals Continued Chapter 3.

Reading Input• import java.util.*;– Is required at the beginning of your programs to read

input• To read console input, you first construct a

Scanner that is attached to System.in:Scanner in = new Scanner(System.in);• You can use the various methods of the Scanner class to

read input. – For example, the nextLine method reads a line of input.

System.out.print("What is your name? ");String name = in.nextLine();

Page 25: Introduction to Java Fundamentals Continued Chapter 3.

Reading Input Cont’

• String firstName = in.next();– Reads a single word delimited by whitespace

System.out.print("How old are you? ");

int age = in.nextInt();

– Read an single integer

• Similarly, the nextDouble method reads the next floating-point number.

Page 26: Introduction to Java Fundamentals Continued Chapter 3.

Reading Input Cont’

• boolean hasNext()– tests whether there is another word in the input.

• boolean hasNextInt()• boolean hasNextDouble()– tests whether the next character sequence

represents an integer or floating-point number.

Page 27: Introduction to Java Fundamentals Continued Chapter 3.

Output

• Output to the console: writing text

System.out.println(“This is on its own line”);

System.out.print(“The next output will be here->”);

System.out.printf(“%d %.2f”,3,0.251);

This is on its own line

This next output will be here->3 0.25

Page 28: Introduction to Java Fundamentals Continued Chapter 3.

Formatting Output

• You can print a number x to the console with the statement System.out.print(x).– will print x with the maximum number of non-zero

digits for that type. For example,double x = 10000.0 / 3.0;

System.out.print(x);

prints3333.3333333333335

Page 29: Introduction to Java Fundamentals Continued Chapter 3.

Formatting Output Cont’

• System.out.printf("%8.2f", x);• prints x with a field width of 8 characters and

a precision of 2 characters. That is, the printout contains a leading space and the seven characters

• 3333.33• You can supply multiple parameters to printf.

For example:• System.out.printf("Hello, %s. Next year, you'll be %d", name, age);

Page 30: Introduction to Java Fundamentals Continued Chapter 3.

Input and Output• Input: reading text

– Uses the class Scanner– The type to be read must be specified

• Example:Scanner in = new Scanner(System.in);System.out.print("name: ");String name = in.nextLine();System.out.print("age: ");int age = in.nextInt();System.out.println("You are"+name+” and youare "+age+” years old");

Page 31: Introduction to Java Fundamentals Continued Chapter 3.

File Input and Output

• To read from a file, construct a Scanner object from a File object, like this:

Scanner in = new Scanner(new File("myfile.txt"));

• If the file name contains backslashes, remember to escape each of them with an additional backslash: "c:\\mydirectory\\myfile.txt".

• Now you can read from the file, using any of the Scanner methods that we already described.

Page 32: Introduction to Java Fundamentals Continued Chapter 3.

File Output

• To write to a file, construct a PrintWriter object. In the constructor, simply supply the file name:

• PrintWriter out = new PrintWriter("myfile.txt");

• If the file does not exist, it is created. You can simply use the print, println, and printf commands as you did when printing to System.out.

Page 33: Introduction to Java Fundamentals Continued Chapter 3.

File I/O

Page 34: Introduction to Java Fundamentals Continued Chapter 3.

Control Flow

• Block Scope–A block or compound statement is any

number of simple Java statements that are surrounded by a pair of braces.–Blocks define the scope of your variables.– Blocks can be nested inside another block.

Page 35: Introduction to Java Fundamentals Continued Chapter 3.

Conditional Statementsif (condition) statement

• The condition must be surrounded by parentheses.

• In Java, as in most programming languages, you will often want to execute multiple statements when a single condition is true. {statement1statement2. . .}

Page 36: Introduction to Java Fundamentals Continued Chapter 3.

If/else

•if (condition) statement1 else statement2•For example:if (yourSales >= target){

performance = "Satisfactory";bonus = 100 + 0.01 * (yourSales - target);

}else{

performance = "Unsatisfactory";bonus = 0;

}

Page 37: Introduction to Java Fundamentals Continued Chapter 3.

Multi-Conditional Statementif (yourSales >= 2 * target){performance = "Excellent";bonus = 1000;}else if (yourSales >= 1.5 * target){performance = "Fine";bonus = 500;}else if (yourSales >= target){performance = "Satisfactory";bonus = 100;}else{System.out.println("You're fired");}

Page 38: Introduction to Java Fundamentals Continued Chapter 3.

Assignment 1

Page 39: Introduction to Java Fundamentals Continued Chapter 3.

While Loops• The while loop executes a statement (which may be a

block statement) while a condition is true. • The general form is

while (condition) statementwhile (balance < goal){balance += payment;double interest = balance * interestRate / 100;balance += interest;years++;}System.out.println(years + " years.");

Page 40: Introduction to Java Fundamentals Continued Chapter 3.

While Loops

• The loop will never execute if the condition is false

Page 41: Introduction to Java Fundamentals Continued Chapter 3.

Loops cont’

• In a “while loop” there is a chance that the code in the block is never executed.

• To ensure code is executed at least once use “do while” loopdo statement while (condition);

• This loop executes the statement (which is typically a block) and only then tests the condition.

Page 42: Introduction to Java Fundamentals Continued Chapter 3.

Do While Loopdo{balance += payment;double interest = balance * interestRate / 100;balance += interest;year++;// print current balance. . .// ask if ready to retire and get input. . .}while (input.equals("N"));

Page 43: Introduction to Java Fundamentals Continued Chapter 3.

Determinate Loops

• Use a “for loop” when you want loop an exact number of times with a counter

• First you initialize a counter variable• Then set the check condition of the counter

variable• Then modify the value of the counter variable

Page 44: Introduction to Java Fundamentals Continued Chapter 3.

For Loopfor (int i = 1; i <= 10; i++)System.out.println(i);

Page 45: Introduction to Java Fundamentals Continued Chapter 3.

For Loop odds and ends

• When you declare a variable in the first slot of the for statement, the scope of that variable extends until the end of the body of the for loop.

• if you define a variable inside a for statement, you cannot use the value of that variable outside the loop.

• However you can define variables with the same name in separate for loops

• You can write a while loop using the same contents as a for loop

Page 46: Introduction to Java Fundamentals Continued Chapter 3.

Switch Statement• Behaves the same as multi-

conditional if/else statement• Execution starts at the case

label that matches the value on which the selection is performed and continues until the next break or the end of the switch.

• If none of the case labels match, then the default clause is executed, if it is present.

Scanner in = new Scanner(System.in);System.out.print("Select an option (1, 2, 3, 4) ");int choice = in.nextInt();switch (choice){

case 1:. . .break;case 2:. . .break;case 3:. . .break;case 4:. . .break;default:// bad input. . .break;

}

Page 47: Introduction to Java Fundamentals Continued Chapter 3.

Switch cont’

Page 48: Introduction to Java Fundamentals Continued Chapter 3.

“Breaking” Control Flow

• The “break;” statement used for switch statements can also be used for loops

• Labeled break statements exit out of all loops– Set a label with a “name:”(note the colon) – Place it immediately before outermost loop– To break out of all loops have the statement

“break label;” in your code

Page 49: Introduction to Java Fundamentals Continued Chapter 3.

Breaking Control Flow cont’

label:{. . .if (condition) break label; // exits block. . .}// jumps here when the break statement executes

Page 50: Introduction to Java Fundamentals Continued Chapter 3.

Continue

• The continue statement transfers control to the header of the innermost enclosing loop

for (count = 1; count <= 100; count++){

System.out.print("Enter a number, -1 to quit: ");n = in.nextInt();if (n < 0) continue;sum += n; // not executed if n < 0

}

Page 51: Introduction to Java Fundamentals Continued Chapter 3.

Big Numbers

• java.math package: – BigInteger and BigDecimal.

• These are classes for manipulating numbers with an arbitrarily long sequence of digits.– The BigInteger class implements arbitrary

precision integer arithmetic – BigDecimal does the same for floating-point

numbers.

Page 52: Introduction to Java Fundamentals Continued Chapter 3.

Big Numbers Con’t

• Use the static valueOf method to turn an ordinary number into a big number:

BigInteger a = BigInteger.valueOf(100);

• Unfortunately, you cannot use the familiar mathematical operators such as ”+” and “*” to

BigInteger c = a.add(b); // c = a + b

BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d = c * (b + 2)

Page 53: Introduction to Java Fundamentals Continued Chapter 3.

Arrays!!!

• An array is a data structure that stores a collection of values of the same type.

• You access each individual value through an integer index.– For example, if a is an array of integers, then a[i]

is the ith integer in the array

Page 54: Introduction to Java Fundamentals Continued Chapter 3.

Arrays Cont’

• You use the new operator to create the array.int[] a = new int[100];private String[] toppings = new String[20];

• This statement creates an array of 100 integers. – When you create an array of numbers, all elements

are initialized with 0. – Arrays of boolean are initialized with false– Arrays of objects are initialized with null values– Declare array type[] name; or type name[];

Page 55: Introduction to Java Fundamentals Continued Chapter 3.

How to access arrays

int[] a = new int[100];

for (int i = 0; i < 100; i++)

a[i] = i;

// fills the array with 0 to 99•Once an array is created you can not change its size.•Array.length() will give you number of elements in array.•For Arrays of variable size use array list object. (See Chapter 5 for more on array lists.)

Page 56: Introduction to Java Fundamentals Continued Chapter 3.

For “each” loop

• you can loop through each element in an array without index values.

• for (variable : collection) { statement }• sets the given variable to each element of the

collection and then executes the statement• The collection expression must be an array or an

object of a class that implements the Iterable interface, such as ArrayListFor example,for (int element : a)System.out.println(element);

Page 57: Introduction to Java Fundamentals Continued Chapter 3.

More with Arrays

• The call Arrays.toString(a) returns a string containing the array elements,

• enclosed in brackets and separated by commas, such as "[2, 3, 5, 7, 11, 13]".

• To print the array, simply call• System.out.println(Arrays.toString(a));

Page 58: Introduction to Java Fundamentals Continued Chapter 3.

Initializing Arrays

• If you don’t want your array elements to be 0, false, or null you create your array object and fill at the same time

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };

Page 59: Introduction to Java Fundamentals Continued Chapter 3.

Copying Arrays

• You can copy one array variable into another, but then both variables refer to the same array:

int[] luckyNumbers = smallPrimes;

luckyNumbers[5] = 13;

// now smallPrimes[5] is also 13

Page 60: Introduction to Java Fundamentals Continued Chapter 3.

Copying Arrays Cont’int[] luckyNumbers = smallPrimes;luckyNumbers[5] = 12; // now smallPrimes[5] is also 12int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);

•Sort Arrays– To sort an array of numbers, you can use one of the

sort methods in the Arrays class:int[] a = new int[10];. . .Arrays.sort(a);

Page 61: Introduction to Java Fundamentals Continued Chapter 3.

Command Line Parameters

• Actually you’ve already been exposed to arrays since your first programming assignment.

public static void main(String[] args)

Page 62: Introduction to Java Fundamentals Continued Chapter 3.

Command Line Cont’

• To input command line parameters to your program using eclipse

• Goto Run->Run Configurations

• Command line arguments

Page 63: Introduction to Java Fundamentals Continued Chapter 3.

Multidimensional Arrays

• Multidimensional arrays use more than one index to access array elements.

• “Array of arrays”• int[][] a2 = new int[10][5];

// print array in rectangular form for (int r=0; r<a2.length; r++) { for (int c=0; c<a2[r].length; c++) { System.out.print(" " + a2[r][c]); } System.out.println(""); }

Page 64: Introduction to Java Fundamentals Continued Chapter 3.

Multidimensional Arrays Cont’

Page 65: Introduction to Java Fundamentals Continued Chapter 3.

Assignment 2