1 of 30

Chapter 1

Java Fundamentals

    • The Java Class with a main method
    • Types, Expressions, Assignment, I/O

Data Structures with Java and JUnit

©Rick Mercer

1-1

2 of 30

Example Java Program

// Read a number and display its squared value

import java.util.Scanner; // In Java 5 only

public class ReadItAndSquareIt {

public static void main(String[] args) {

double x;

double result = 0.0;

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a number: ");

x = keyboard.nextDouble();

result = x * x;

System.out.println(x + " squared = " + result);

}

}

1-2

3 of 30

Pieces of a Java Program

    • imports allow types without qualification

import java.util.Scanner;

    • Class heading filename: ReadItAndSquareIt.java

public class ReadItAndSquareIt

      • A class has a collection of methods between { and }
    • Method heading The first programs only have this one

public static void main(String[] args)

    • Variable declaration and initialization examples

double x; // Undefined, not garbage

double result = 0.0;

1-3

4 of 30

Special Symbols

    • A special symbol is one or two character sequences no spaces

= < > () { ; } == . >=

    • Some special symbols mean different things in different contexts.
      • with two integers, + means addition
        • 2 + 5 is the integer 7
      • with two strings, + mean concatenation
        • "2" + "5" is the string "25"

1-4

5 of 30

Identifiers

    • An identifier is a collection of certain characters that could mean a variety of things
    • There are some existing Java identifiers

sqrt String Integer System in out

    • We can make up new identifiers

test1 x1 aNumber MAXIMUM A_1

1-5

6 of 30

Valid Identifiers

    • Identifiers have from 1 to many characters:

'a'..'z', 'A'..'Z', '0'..'9', '_', $

      • Identifiers start with letter a1 is legal, 1a is not
        • can also start with underscore or dollar sign: _ $
      • Java is case sensitive. A and a are different.
    • Which of these are valid identifiers?

a) abc e) $$$ i) a_1

b) m/h f) 25or6to4 j) student Number

c) main g) 1_time k) String

d) double h) first-name l) ______

1-6

7 of 30

Reserved Identifiers

    • Reserved identifier: An identifier with a pre-defined meaning that can not be changed
    • Java reserved identifiers not a complete list

boolean default for new

break do if private

case double import public

catch else instanceOf return

char extends int void

class float long while

1-7

8 of 30

Literals -- Java has 6 varieties

Floating-point literals

1.234 -12.5 0.0 0. .0 1e10 0.1e-5

String literals

"between quotes" "another" "_"

Integer literals

-1 0 1 -2147483648 2147483647

Boolean literals (there are only two)

true false

The null literal (one value only)

null

Character literals

'A' 'b' '\n' '1' ' '

1-8

9 of 30

Comments

    • Example comments there are three kinds

// on one line or

/*

between slash star and star slash

you can mash lines down real far

*/

/** javadoc comments for external documentation

* @return The square root of x

*/

      • Provides internal documentation to explain program
      • Provides external documentation via javadoc
      • Helps programmers understand code--including their own

1-9

10 of 30

Output

    • General forms for doing output:

System.out.print(expression);

System.out.println(expression);

    • Where expression may be any literal, variable, or arithmetic expression ...
      • expression is shown to the console
    • Examples (+ means concatenate)

System.out.print("Enter test 1: ");

System.out.println("Grade: " + courseGrade);

System.out.println(1 + 2 + 3); // 6

System.out.println("1"+ 2 + 3); // 123

1-10

11 of 30

Assignment

    • The programmer can set the values of a variable with assignment operations of this form:

variable-name = expression ;

    • Examples:

double x; // Undefined variables

int j; // not garbage or 0 (for now)

j = 1;

x = j + 0.23;

1-11

12 of 30

Memory before and after

    • Variables x and j are undefined ? at first

Variable Initial Assigned

Name Value Value

j ? 1

x ? 1.23

    • The expression to the right of = must be a value that the variable can store (assignment compatible)

x = "oooooh nooooo, you can't do that"; // <-Error

j = x; // <-Error, can't assign a float to an int

? means undefined

1-12

13 of 30

Differences from C

    • Declared variables are undefined, not garbage

int x;

System.out.println(x); // Compile time error

    • Cannot assign doubles to ints

int n = 0.99; // Compile time error, not 0

    • Must use real boolean values

if(n = 1) // Compile time error, not true

// It should read if(n == 1)

1-13

14 of 30

Input

    • There are many options for reading numbers
      • 1. use the decorator design pattern with classes such as BufferedReader
        • has complex code
          • Must handle exceptions, must parse the strings
      • 2. use the new Java 5 Scanner class
        • Relatively easy to use (less code to write)
        • Can read from complicated files (variety of types)

1-14

15 of 30

The new Java Scanner class

    • Need to import java.util.Scanner
    • Construct a Scanner object with new
    • Then you can send messages (call functions) such as nextInt, nextDouble, and nextLine

1-15

16 of 30

Read 3 doubles

import java.util.Scanner;

public class ThreeNumbers {

public static void main(String[] args) {

double x = 0.0, y = 0.0, z = 0.0, average = 0.0;

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter 3 numbers: ");

x = keyboard.nextDouble();

y = keyboard.nextDouble();

z = keyboard.nextDouble();

average = (x + y + z) / 3.0;

System.out.println("Average: " + average);

}

}

1-16

17 of 30

Arithmetic Expressions�

    • Arithmetic expressions consist of operators such as + - / * and operands such as 40, 1.5, payRate, and hoursWorked
    • Example expression used in an assignment:

grossPay = payRate * hoursWorked;

    • Another example expression:

(40 * payRate) + 1.5 * payRate * (hoursWorked - 40)

1-17

18 of 30

Boolean Expressions

    • Boolean expressions evaluate to true or false
    • Will often see relational operators

Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

1-18

19 of 30

Boolean Expressions�

    • Some boolean expressions and their resulting values

double x = 4.0;

Boolean

Expression Value

x < 5.0 true

x > 5.0 false

x <= 5.0 ? ___________

5.0 == x ? ___________

x != 5.0 ? ___________

1-19

20 of 30

Precedence of Arithmetic Operators

    • Expressions with more than one operator require some sort of precedence rules:

* / evaluated in a left to right order

- + evaluated in a left to right order in the absence of parentheses

    • Use (parentheses) for readability or to intentionally alter an expression:

double C, F;

F = 212.0;

C = 5 / 9 * (F - 32);

What is the current value of C?

1-20

21 of 30

int Arithmetic

    • int variables are similar to double, except they can only store whole numbers (integers)

int anInt = 0;

int another = 123;

int NoCanDo = 1.99; // ERROR

    • Division with integers is also different
      • Perfoms quotient remainder whole numbers only

anInt = 9 / 2; // anInt = 4, not 4.5

anInt = anInt / 5; ________ What is anInt now?

anInt = 5 / 2; ________ What is anInt now?

1-21

22 of 30

The integer % operation

    • The Java % operator returns the remainder

anInt = 9 % 2; // anInt ___1___

anInt = 101 % 2; _____ What is anInt now?

anInt = 5 % 11; _____ What is anInt now?

anInt = 361 % 60; _____ What is anInt now?

int quarter;

quarter = 79 % 50 / 25; ______ What is quarter?

quarter = 57 % 50 / 25; ______ What is quarter now?

1-22

23 of 30

Compilation and Execution

1-23

24 of 30

The integer % operation

    • The Java % operator returns the remainder

anInt = 9 % 2; // anInt ___1___

anInt = 101 % 2; #11 What is anInt now?

anInt = 5 % 11; #12 What is anInt now?

anInt = 361 % 60; #13 What is anInt now?

int quarter;

quarter = 79 % 50 / 25; #14 What is quarter?

quarter = 57 % 50 / 25; #15 What is quarter now?

1-24

25 of 30

Errors

    • Categories of errors and warnings are detected during implementation

1. Compiletime errors

2. Exceptions

3. Intent errors

    • You will experience many errors

1-25

26 of 30

Compilation and Execution

Report Errors

1-26

27 of 30

A few common compiletime errors

    • Splitting an identifier

int my Weight = 0; int myWeight = 0;

    • Misspelling a keyword

integer sum = 0; int sum = 0;

    • Leaving off a semicolon

double x = 0.0 double x = 0.0;

    • Not closing a string constant

System.out.print("Hi); System.out.print("Hi");

    • Forgetting parentheses

keyboard.readDouble; keyboard.readDouble();

1-27

28 of 30

Exceptions

    • Exceptions are errors that occur while the program is running
    • Exceptions are thrown when the program encounters something it could not handle well
    • Example
      • Type in an invalid number during a nextInt message
      • Division by 0 with integers (3.0/0.0 is Infinity)
      • Index out of bounds with strings and arrays
      • Attempt to open a file that is not present

1-28

29 of 30

Intent Errors

    • When the program does what you typed, not what you intended.
    • Imagine this code

System.out.print("Enter sum: ");

n = keyboard.nextInt();

System.out.print("Enter n: ");

sum = keyboard.nextDouble();

average = sum / n;

1-29

30 of 30

Homework

1C Wholesale Cost

Write a Java program that determines the wholesale price for any item given its retail price and markup. Test your program by running it with several different inputs where you know the expected results. Given that a store has a 25% markup on compact-disc (CD) players, if the retail price (what you pay) of a CD player is $189.98, how much did the store pay for that item (the wholesale price)? Use this formula and some algebra to solve for wholesale price:

 

retail price = wholesale price * (1 + markup)

 

One dialog must look like this (user input is in italic 255.00 and 50):

 

Enter the retail price: 255.00

Enter the markup percentage: 50

Wholesale price = 170.0

1-30