1 of 51

Variables

Java 1 Chapter 2

2 of 51

Variable

A named item used to store a value of a specified type

favoriteNumber

int

Syntax

int favoriteNumber = 17;

17

3 of 51

Variable

A named item used to store a value of a specified type

firstLetter

char

Syntax

char firstLetter = ‘A’;

A

4 of 51

Variable

A named item used to store a value of a specified type

price

double

Syntax

double price = 9.63;

9.63

5 of 51

Variable

A named item used to store a value of a specified type

isSunny

boolean

Syntax

boolean isSunny = true;

true

6 of 51

Variable Declaration

Specify the datatype and give the variable a name.

Syntax

int favoriteNumber;

char firstLetter;

double price;

boolean isSunny;

7 of 51

Variable Initialization

After a variable is declared, it can be assigned a value.

Notice the datatype is not specified when assigning a value to the variable, but the value’s type must match the type that was specified when the variable was declared.

Syntax

favoriteNumber = 17;

firstLetter = ‘A’;

price = 9.63;

isSunny = true;

8 of 51

Variable Declaration and Initialization in 2 statements

1 - Specify the datatype and give the variable a name.

2 - Refer to the variable by name and assign it the initial value.

Syntax

int favoriteNumber;

favoriteNumber = 17;

char firstLetter;

firstLetter = ‘A’;

double price;

price = 9.63;

boolean isSunny;

isSunny = true;

9 of 51

Variable Declaration and Initialization in 1 statement

Specify the datatype, give the variable a name, and assign the initial value to it.

Syntax

int favoriteNumber = 17;

char firstLetter = ‘A’;

double price = 9.63;

boolean isSunny = true;

10 of 51

Replacing a value in a Variable

After a variable is declared, its value can be assigned or replaced.

Notice the syntax for replacing a value is the same as initializing a variable’s value.

Notice the datatype is not specified when assigning a value to the variable, but the value’s type must match the type that was specified when the variable was declared.

Syntax

favoriteNumber = 21;

firstLetter = ‘C’;

price = 5.27;

isSunny = false;

11 of 51

Replacing a value in a variable

Syntax

int a = 5;

a = 99;

a

int

5

5

99

99

The state changes when a value is replaced.

12 of 51

Using Variables

Syntax

int a = 5;

int b = 3;

int c = a + b;

c

int

5 + 3 = 8

a

int

5

8

b

int

3

13 of 51

Arithmetic Expressions

Variable: A named item used to store a value of a specified type

The combination of variables, literals, operators and parentheses to be evaluated

Literal: A specific unchanging value used in an expression (a hard coded value)

Operator: A recognized symbol that performs a calculation + - * / %

Example Arithmetic Expression: 2 * ( a + b )

The literal is 2

The operators are * and +

The variables are a and b

The parentheses ( ) enforce the order of operations in the above arithmetic expression

14 of 51

Assignment Statement

Examples:

int a = 5;

int b = 3;

int c = a + b;

int d = 2 * ( a + b );

int e = d / c ;

Designates a value for the variable on the left side of the = symbol to receive from the right side.

a

int

5

b

int

3

c

int

8

d

int

16

e

int

2

15 of 51

Primitive Data Types

All Primitive Data Types

int

long

short

byte

double

float

char

boolean

16 of 51

Primitive Data Types

Primitive Data Types for Whole Numbers

int stores whole numbers, requires 32 bits (4 bytes of memory)

range -231 to 231-1 -2,147,483,648 to 2,147,483,647

long stores whole numbers, requires 64 bits (8 bytes of memory)

range -263 to 263-1 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

short stores whole numbers, requires 16 bits (2 bytes of memory)

range -215 to 215-1 -32,768 to 32,767

byte stores whole numbers, requires 8 bits (1 byte of memory)

range -27 to 27-1 -128 to 127

int w = 550; long x = 400; short y = 275; byte z = 125;

17 of 51

Primitive Data Types

Primitive Data Types for Floating Point (Decimal) Numbers

double stores up to 15 decimals, requires 64 bits (8 bytes of memory)

float stores up to 7 decimals, requires 32 bits (4 bytes of memory)

double price = 9.63;

float weight = 13.2;

18 of 51

Primitive Data Types

Primitive Data Type for Boolean Values

boolean stores a value of true or false (requires 1 bit of memory)

The single bit with a value of 1 represents true/on and 0 represents false/off

boolean isSunny = true;

boolean isMoving = false;

19 of 51

Primitive Data Types

Primitive Data Type for Character Values

char stores single characters, requiring 16 bits for Unicode (requires 2 bytes of memory)

ASCII uses 8 bits to support 255 characters, while Unicode uses 16 bits to support 64000

Java uses Unicode, but earlier languages like C or C++ use ASCII.

Unicode's first several hundred items are the same as ASCII.

char firstLetter = ‘A’;

char secondLetter = ‘B’;

char lowerFirst = ‘a’;

Binary

Decimal

Char

100 0001

65

A

100 0010

66

B

110 0001

97

a

20 of 51

Number Systems and Conversions

Base 10 (digits range from 0 to 9)

DECIMAL

Base 2 (digits range from 0 to 1)

BINARY

Base 10 Number 237

(2*100) + (3*10) + (7*1)

200 + 30 + 7

237

Base 2 Number 11101101

(1*27)+(1*26)+(1*25)+ (0*24)+(1*23)+(1*22)+ (0*21)+ (1*20)

128 + 64 + 32 + 0 + 8 + 4 + 0 + 1

BASE TEN 237 = BASE TWO 11101101

105

104

103

102

101

100

100000

10000

1000

100

10

1

27

26

25

24

23

22

21

20

128

64

32

16

8

4

2

1

21 of 51

Number Systems and Conversions

Base 10 (digits range from 0 to 9)

DECIMAL

Base 2 (digits range from 0 to 1)

BINARY

Base 10 Number 26

(2*10) + (6*1)

26

Base 2 Number 00011010

(0*27)+(0*26)+(0*25)+ (1*24)+(1*23)+(0*22)+ (1*21)+ (1*20)

0 + 0 + 0 + 16 + 8 + 0 + 2 + 0

BASE TEN 26 = BASE TWO 00011010

105

104

103

102

101

100

100000

10000

1000

100

10

1

27

26

25

24

23

22

21

20

128

64

32

16

8

4

2

1

22 of 51

Number Systems and Conversions

Base 10 (digits range from 0 to 9)

DECIMAL

Base 16 (digits range from 0 to 15)

HEXADECIMAL

Base 10 Number 257

(2*100) + (5*10) + (7*1)

200 + 50 + 7

257

Base 16 Number 101

(1*162)+ (0*161)+ (1*160)

256 + 0 + 1

DECIMAL 257 = HEXADECIMAL 101

105

104

103

102

101

100

100000

10000

1000

100

10

1

165

164

163

162

161

160

1048576

65536

4096

256

16

1

23 of 51

Number Systems and Conversions

Base 10 (digits range from 0 to 9)

DECIMAL

Base 16 (digits range from 0 to 15)

HEXADECIMAL

Base 10 Number 246512

(2*100000) + (4*10000) + (6*1000) + (5*100) + (1*10) + (2*1)

246512

Base 16 Number 3C2F0

(3 * 164) + (C * 163) + (2 * 162) + (F * 161) + (0 * 160)

(3 * 65536) + (12 * 4096) + (2 * 256) + (15 * 16) + (0 * 1)

196608 + 49152 + 512 + 240 + 0

DECIMAL 246512 = HEXADECIMAL 3C2F0

105

104

103

102

101

100

100000

10000

1000

100

10

1

165

164

163

162

161

160

1048576

65536

4096

256

16

1

24 of 51

Storing values and Integer Overflow

When a value is greater than the maximum capacity for the datatype

int The base ten number 2147483647 or any value less than it can be stored without a problem since an int uses 32 bits of memory.

2147483647 + 1 = 2147483648 which will result in an overflow and cause the value to incorrectly be stored as the most negative value for that datatype since the bit will be flipped

(Example: -2147483648 instead of 2147483648 )

int

range -231 to 231-1 -2,147,483,648 to 2,147,483,647

long

range -263 to 263-1 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

25 of 51

Identifier

The name given to a variable or method

Must be a sequence of letters (a-z, A-Z), underscore (_), dollar signs ($), and digits (0-9)

Must start with a letter, underscore, or dollar sign

Must NOT be a keyword / reserved word of the Java programming language

Syntax Rules for an identifier

Note: Java is case sensitive, therefore so are identifiers.

Best Practices:

Use camel case for identifiers of variables or methods (Example: camelCaseNamingConvention)

Use title case for classes (Example: TitleCaseNamingConvention)

Use uppercase with underscore separation for named constants (Example: UPPER_CASE_CONVENTION)

26 of 51

Declared Constant / Final Variable / Named Constant

A named value that cannot be changed/replaced after initialization

Syntax:

final int NUM_DAYS_IN_WEEK = 7;

final int NUM_HOURS_IN_DAY = 24;

final String SCHOOL_NAME = “Lehman College CUNY”;

final double PI = 3.14159265

Purpose:

Minimize the use of literals and humans having to remember values used in code

Improve code clarity, legibility, and maintenance

Avoid errors

Rules for a named constant are the same as any other identifier

Best Practice: Use UPPERCASE with underscore separation for named constants

27 of 51

Keyword / Reserved Word

Any word that is already part of the Java programming language

Some Java Keywords / Reserved Words

abstract assert boolean break byte case catch char class const

continue default do double else enum extends final finally float

for if implements import instanceof int interface long native new

package private protected public return short static super

switch synchronized this throw throws try void volatile while

28 of 51

Integer Division

int a = 20;

System.out.println("a is "+a);

int b = 5;

System.out.println("b is "+b);

int c = 3;

System.out.println("c is "+c);

int d = a / b;

System.out.println("a/b=d "+a+" / "+b+" = "+d);

29 of 51

Integer Division

Examples:

int a = 20;

int b = 5;

int c = 3;

int d = a / b;

int e = a / c ;

Division of whole numbers

The remainder is not stored.

This is known as truncation.

a

int

20

b

int

5

c

int

3

d

int

4

e

int

6

?

?

?

20 / 5

20 / 3

6

30 of 51

Modulo Operator

Examples:

int e = a / c ;

int f = a % c ;

Used to obtain the remainder from the division

The remainder is not stored.

This is known as truncation.

The remainder is obtained using % and can then be stored.

f

int

2

e

int

6

?

?

?

20 / 3

6

20 % 3

2

31 of 51

Division by Zero

Examples:

int g = c / b;

int h = b / 0 ;

int h = a / g ;

Exception occurs when the denominator is zero

Division by zero causes an exception to be thrown halting the application.

a

int

20

b

int

5

c

int

3

g

int

0

X

?

?

3 / 5

0

5 / 0

20 / 0

32 of 51

Type Conversion and Casting

The conversion of a value from one type to another

Implicit Conversion:

Automatic conversion from a smaller data type to a larger data type done by the compiler

Explicit Conversion (Casting):

Specifically stating in code what data type a value should be converted to

33 of 51

Implicit Type Conversion

Automatic conversion from a smaller data type to a larger data type done by the compiler

From

To

byte

short

short

int

int

long

long

float

float

double

In a mathematical expression if the values are of two different types, the compiler will automatically apply a widening cast to the smaller typed value.

34 of 51

Implicit Type Conversion

In a mathematical expression if the values are of two different types, the compiler will automatically apply a widening cast to the smaller typed value.

Mathematical Expression

Automatic Conversion

Result

int + int

int + int

int

int + long

long + long

long

int / int

int / int

int

int / double

double / double

double

double / int

double / double

double

float / double

double / double

double

double / float

double / double

double

35 of 51

Explicit Type Conversion or Casting

Use parentheses to specify the new type and apply a cast to the existing type.

Examples:

int a = 20 int b = 5; int c = 3;

double x = (double) c;

double y = a / b;

double z = b / (double) c;

a

int

20

b

int

5

c

int

3

x

double

3.0

c

double

3.0

y

double

4.0

3.0

20 / 5

4

5 / 3.0

1.6666666666666667

z

double

1.6666666666666667

It would size up automatically, but this example shows how to explicitly apply the cast.

36 of 51

Explicit Type Conversion or Casting

Use parentheses to specify the new type and apply a cast to the existing type.

Examples:

double p = 2.5 double q = 5.0;

double r = p + q;

int s = (int) (p + q);

int u = (int) p * (int) q;

int v = (int) (p * q);

s

int

7

p

double

2.5

q

double

5.0

r

double

7.5

2.5 + 5.0

7.5

2.5 + 5.0

(int) 7.5

7

2 * 5

10

2.5 * 5.0

12.5

12

u

int

10

p

int

2

q

int

5

v

int

12

37 of 51

The String class and String variables

String s = “Hello Everyone!”;\

String is a class type, not a primitive data type.

It is a sequence of characters

char

H

e

l

l

o

E

v

e

r

y

o

n

e

!

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

s

String

first index

last index

length is 15

38 of 51

The String class and String variables

String s = “Hello Everyone!”;\

String is a class type, not a primitive data type.

It is a sequence of characters

char

H

e

l

l

o

E

v

e

r

y

o

n

e

!

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

s

String

invalid index

-1 or less

length is 15

invalid index

15 or greater

39 of 51

The String class and String variables

Syntax Examples: String s = “Hello Everyone!”;

The String class, which is part of Java’s standard language package has methods that allow us to work with String objects and their characters.

Method

Behavior

Example

charAt(0)

returns char at index 0

s.charAt(0) returns ‘H’

toUpperCase()

returns the String as all uppercase characters

s.toUpperCase()

returns “HELLO EVERYONE!”

indexOf(‘e’)

returns the index location of the first match

s.indexOf(“e”) returns the value 1

replace(‘e’,’a’);

returns a String with all ‘e’ occurrences replaced with ‘a’

s.replace(‘e’,’a’); returns “Hallo Evaryona!”

Remember ‘E’ is not the same as ‘e’

length()

returns the number of characters in the String

s.length() returns 15 for this example

concat(“ YAY”)

returns a new String containing the original, plus the argument appended to the end of it

s.concat(“ YAY”)

returns “Hello Everyone! YAY”

40 of 51

String concatenation using the + symbol

Example:

String s = “Hello Everyone!”;

String s1 = “This is fun.”;

String greet = s + “ “ + s1;

System.out.println( greet + “ We have only just begun!” );

Connects an existing string with another string or value to form a new larger string

char

H

e

l

l

o

E

v

e

r

y

o

n

e

!

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

s

String

char

T

h

i

s

i

s

f

u

n

.

index

0

1

2

3

4

5

6

7

8

9

10

11

s1

String

greet

String

Printed Output: Hello Everyone! This is fun. We have only just begun!

char

H

e

l

l

o

E

v

e

r

y

o

n

e

!

T

h

i

s

i

s

f

u

n

.

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

41 of 51

String concatenation with non-string values

Example:

int x = 8; int y = 2;

String s = “Hello Everyone!”;

String clue = “I have “ + x + “ legs.”;

System.out.println( “\n” + s + “ “ + clue + “ I have “ + y + ” eyes.\nWhat am I?”);

Connects an existing string with another string or value to form a new larger string

char

H

e

l

l

o

E

v

e

r

y

o

n

e

!

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

s

String

char

I

h

a

v

e

8

l

e

g

s

.

index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

clue

String

Printed Output:

Hello Everyone! I have 8 legs. I have 2 eyes.

What am I?

42 of 51

The Math class and some of its methods

Method

Behavior

Example

sqrt(x)

Square root of x

Math.sqrt(9.0) returns the value 3.0

pow(x, y)

Power: xy

Math.pow(6.0, 2.0) returns the value 36.0

abs(x)

Absolute value of x

Math.abs(-99.5) returns the value 99.5

The Math class, which comes as part of Java’s standard language package, can be used to perform more common math operations by passing in arguments and retrieving the result.

43 of 51

The Random class and generating random numbers

Syntax Examples:

Random randomGen = new Random();

randomGen.nextInt();

randomGen.nextInt(10);

The Random class, which is part of Java’s util package, can be used to generate random numbers with or without a seed.

44 of 51

Exercise 1 Number System Conversion

  • Your current age
  • Your favorite number
  • The current year
  • Zero
  • One
  • Two
  • Three
  • Four
  • Seven
  • Eight

In your notebook convert the following from base ten to base two

45 of 51

Exercise 2 Integer Overflow

int a = 9999999;

System.out.println("a is "+a); //correct value displayed since it is within range

int b = 2147483647;

System.out.println("b is "+b); //correct value displayed since it is within range

int c = b + 1;

System.out.println("c is "+c); //incorrect value displayed since it is NOT within range

In your IDE create and run the application to demonstrate integer overflow

46 of 51

Exercise 3 Cast from int to long to prevent overflow

1. Cast the entire sum to type long as shown before assigning to d. Print d to see the result.

long d = (long) (b + 1);

System.out.println("d is "+d); //incorrect sum is displayed

2. Cast the literal 1 to type long before assigning the sum to e. Print e to see the result.

long e = _________________ ;

System.out.println("e is "+e); //correct sum is displayed

3. Cast b to type long before adding 1 and assigning the sum to f. Print f to the result.

long f = _________________ ;

System.out.println("f is "+f); //correct sum is displayed

Correct result when cast is applied to the variable b only, or 1 only and not the entire sum

Build upon the previous exercise to correct the int overflow problem

47 of 51

Exercise 4 Integer Division and Modulo

final int CENTS_IN_DOLLAR = 100;

final int CENTS_IN_QUARTER = 25;

final int CENTS_IN_DIME = 10;

final int CENTS_IN_NICKEL = 5;

final int CENTS_IN_PENNY = 1;

Scanner kb = new Scanner(System.in);

System.out.println("Enter the initial amount in cents");// prompt user for amount in cents

final int INITAL_AMOUNT_IN_CENTS = kb.nextInt();//use different values 254, 367, 524, 718, 641, 1371, 92, 99

int cents = INITAL_AMOUNT_IN_CENTS;

int numDollars = cents / CENTS_IN_DOLLAR;

cents = cents % CENTS_IN_DOLLAR;

int numQuarters = cents / CENTS_IN_QUARTER;

//FILL IN CODE HERE FOR THE REMAINING COINS

System.out.printf("%2d cents can be broken down as:\n%2d dollars\n%2d quarters\n%2d dimes\n%2d nickels\n%2d pennies ",INITAL_AMOUNT_IN_CENTS, numDollars, numQuarters,numDimes,numNickels, numPennies);

Complete the code to print the dollar and coin details for the initial cent amounts

48 of 51

Exercise 5 Cast from int to double (Explicit & Implicit)

Scanner kb = new Scanner(System.in);

System.out.println("Enter the number of pennies");

final int NUM_OF_PENNIES = kb.nextInt();//run with different amounts 5, 327, 499, 1328, 94, 192

final int PENNIES_IN_A_DOLLAR = 100;

// double dollarsAndCents = NUM_OF_PENNIES/PENNIES_IN_A_DOLLAR; //no cast

// double dollarsAndCents = (double)(NUM_OF_PENNIES/PENNIES_IN_A_DOLLAR);

// double dollarsAndCents = (double)NUM_OF_PENNIES/PENNIES_IN_A_DOLLAR;

// double dollarsAndCents = NUM_OF_PENNIES/(double)PENNIES_IN_A_DOLLAR;

// double dollarsAndCents = (double)NUM_OF_PENNIES/(double)PENNIES_IN_A_DOLLAR;

// double dollarsAndCents = NUM_OF_PENNIES/100.0;

System.out.printf("$%2.2f",dollarsAndCents);

Complete and Run an application using the starter code below.

Uncomment 1 of the 6 commented lines to see the result of casting the numerator or denominator Comment out the line again before running the application with a different line

Be sure to run the application with each 1 of the 6 lines

Use different values when running the application with 1 of the lines uncommented to compare the results

49 of 51

Exercise 6 Strings

String greeting = "Hello Everyone!";

System.out.println(greeting);

final char SPACE_CHARACTER = ' ';

int locationOf_e = greeting.indexOf('e');

int locationOfSpace = greeting.indexOf(SPACE_CHARACTER);

int numCharsInGreeting = greeting.length();

String greetingAsUpper = greeting.toUpperCase();

System.out.println("Index of 'e' is "+locationOf_e);

System.out.println("Index of the space character is "+locationOfSpace);

System.out.println("Let's yell the greeting: " + greetingAsUpper);

greeting = greeting.replace('e', 'a');

System.out.println(greeting);

System.out.println("The greeting is "+numCharsInGreeting+" characters long");

Complete and Run an application using the starter code below.

Ask the user t “Hello Everyone!” to something else and see what happens

Explore the methods of the String class and performing concatenation to see what you can accomplish

50 of 51

Exercise 7 Strings

Scanner kb = new Scanner(System.in);

System.out.println("In 1 sentence, tell me what is on your mind.");

String sentence = kb.nextLine();//retrieve input from the user’s keyboard entry

System.out.println("You said: " + sentence);//print their sentence back to them

//your code goes here to work with the String and print more output to the user

System.out.println("Bye for now");

kb.close();

Complete and Run an application using the starter code below and the instructions.

Use the methods from the String class to do the following:

  • Tell the user what the first character of their sentence was.
  • Tell the user what the last character of their sentence was. Hint: use length() -1
  • Convert the sentence to all lowercase and display it to the user.
  • Check if the sentence contains the char ‘a’ and print the result to the user.
  • Check if the sentence contains the char ‘b’ and print the result to the user.
  • Check if the sentence contains the char ‘z’ and print the result to the user.
  • Replace all ‘a’ with ‘e’ and display the resulting sentence to the user.

51 of 51

Exercise 8 methods from Math and Random

Create and Run an application using the instructions below.

Use the methods from the Math class and the Random class to do the following:

  • Use the Random class to generate a random int from 1 to 500 inclusive.
  • Tell the user what the randomly generated int is.
  • Calculate and display the result of ( 2 * randomNum)
  • Calculate and display the result of squaring the randomNum. Hint use Math class method.
  • Calculate and display the result of the square root of the randomNum. Hint use Math class method.
  • Explore the methods in Math and Random.