Basic Computation logical AND logical OR logical NOT && - - PowerPoint PPT Presentation

basic computation
SMART_READER_LITE
LIVE PREVIEW

Basic Computation logical AND logical OR logical NOT && - - PowerPoint PPT Presentation

Basic Computation logical AND logical OR logical NOT && || ! public static void main(String [] args) Fundamentals of Computer Science Outline Data Types Variables Primitive Data Types The String Class Type


slide-1
SLIDE 1

Basic Computation

Fundamentals of Computer Science

public static void main(String [] args)

logical AND logical OR logical NOT && || !

slide-2
SLIDE 2

Outline

Data Types

 Variables  Primitive Data Types  The String Class  Type Conversion

Expressions

slide-3
SLIDE 3

Variables

 Variables store data such as numbers and letters.

 Think of them as places to store data.  They are implemented as memory locations.

 The data stored in a variable is called its value.

 The value is stored in the memory location.

 Its value can be changed.

slide-4
SLIDE 4

Some Definitions

int a; a = 10; int b; b = 7; int c = a + b; Declaration statement

“I'm going to need an integer and let's call it a” REMEMBER: in Java you are required to declare a variable before using it!

Variable name

“Whenever I say a, I mean the value stored in a”

Literal

“I want the value 10”

Assignment statement

“Variable b gets the literal value 7”

Combined declaration and assignment

“Make me an integer variable called c and assign it the value obtained by adding together a and b” = in CS is not the same as = in math!

4

slide-5
SLIDE 5

Assignment Evaluation

 The expression on the right-hand side of the

assignment operator (=) is evaluated first.

 The result is used to set the value of the variable on

the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

slide-6
SLIDE 6

Constants

 Literal expressions such as 2, 3.7, or 'y' are called

constants.

 Integer constants can be preceded by a + or - sign, but

cannot contain commas.

 Floating-point constants can be written

 With digits after a decimal point or  Using e notation.

 Java provides mechanism to …

 Define a variable  Initialize it  Fix the value so it cannot be changed

public static final double PI = 3.14159;

slide-7
SLIDE 7

Data Types

 A primitive type is used for simple,

non-decomposable values such as an individual number or individual character.

 int, double, and char are primitive types.

 A class type is used for a class of objects and has

both data and methods.

 "Java is fun" is a value of class type String

DEFINITION

  • A data type is a set of values and the legal
  • perations on those values.
slide-8
SLIDE 8

Variables and Data Types

 Variables

 Stores information your program needs  Each has a unique name  Each has a specific type

Java built-in type what it stores example values

  • perations

String sequence of characters "Hello world!" "I love this!" concatenate char characters 'a', 'b', '!' compare int integer values 42 1234 add, subtract, multiply, divide, remainder double floating-point values 9.95 3.0e8 add, subtract, multiply, divide boolean truth values true false and, or, not

8

slide-9
SLIDE 9

Primitive Type Sizes

 Primitive types

 Just a block of memory in your computer  Size of block measured in bits (number of 0s or 1s)  Integers:

9

type bits example byte 8 0110 1110 short 16 0110 1110 1101 1101 int 32 0101 1001 0000 0001 0111 1101 0110 0010 long 64 1101 0011 1001 0001 1101 0101 1010 0101 0111 1010 0011 1010 1011 1100 1111 1111

slide-10
SLIDE 10

Creating a Primitive Variable

10

x

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000000000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

x

byte x;

slide-11
SLIDE 11

Initializing Variables

 A variable that has been declared, but not yet given a

value is said to be uninitialized.

 Uninitialized class variables have the value null.  Uninitialized primitive variables may have a default

value.

 It's good practice not to rely on a default value.

 To protect against an uninitialized variable (and to

keep the compiler happy), assign a value at the time the variable is declared.

 Examples:

int count = 0; char grade = 'A';

slide-12
SLIDE 12

Creating and Initializing a Primitive Variable

12

x

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000001110101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

x

primitive value byte x = 7;

slide-13
SLIDE 13

Integers

 int data type

 An integer value between -231 and +231-1  Between -2,147,483,648 and 2,147,483,647  Operations: add

subtract multiply divide remainder +

  • *

/ % example result comment 10 + 7 17 10 - 7 3 10 * 7 70 10 / 7 1 integer division, no fractional part 10 % 7 3 remainder after dividing by 7 10 / 0 runtime error, you can't divide an integer by 0! Watch out for this! / is integer division if both sides are integers!

13

slide-14
SLIDE 14

Increment and Decrement Operators

 Used to increase (or decrease) the value of a

variable by 1

 Easy to use, important to recognize  The increment operator

count++ or ++count

 The decrement operator

count-- or --count

Equivalent operations:

count++; ++count; count = count + 1; count--;

  • -count;

count = count - 1;

slide-15
SLIDE 15

Floating-Point Numbers

 double data type

 Floating-point number (as specified by IEEE 754)  Operations:

add subtract multiply divide +

  • *

/ example result 9.95 + 2.99 12.94 1.0 - 2.0

  • 1.0

1.0 / 2.0 0.5 1.0 / 3.0 0.3333333333333333 1.0 / 0.0 Infinity 0.0 / 123.45 0.0 0.0 / 0.0 NaN

15

slide-16
SLIDE 16

e Notation

 e notation is also called scientific notation or

floating-point notation.

 Examples

 865000000.0 can be written as 8.65e8  0.000483 can be written as 4.83e-4

 The number in front of the e does not need to

contain a decimal point.

slide-17
SLIDE 17

Imprecision in Floating-Point Numbers

 Floating-point numbers often are only

approximations since they are stored with a finite number of bits.

 Hence 1.0/3.0 is slightly less than 1/3.  1.0/3.0 + 1.0/3.0 + 1.0/3.0

is less than 1.

slide-18
SLIDE 18

Booleans

18

 boolean data type

 Either true or false  Controls logic and flow of control in

programs

 Operations:

logical AND logical OR logical NOT && || !

Note: two symbols for logical AND and OR, not one!

slide-19
SLIDE 19

Booleans

19

 boolean data type

a !a true false false true logical AND logical OR logical NOT && || ! a b a && b a || b false false false false false true false true true false false true true true true true

!a → “Is a set to false?” a && b → “Are both a and b set to true?” a || b → “Is either a or b (or both) set to true?”

slide-20
SLIDE 20

Characters

20

 char data type

 Holds a single character  Single apostrophe, e.g. 'a', 'z'

public class CharExample { public static void main(String [] args) { char ch1 = 'y'; char ch2 = 'o'; String result = "" + ch1; result = result + ch2; result = result + ch2; result = result + ch2; System.out.println(result); } } % java CharExample yooo

Double quotes with nothing in between, an empty String

slide-21
SLIDE 21

Assignment Compatibilities

 Java is said to be strongly typed.

 You can't, for example, assign a floating point value to a

variable declared to store an integer.  Sometimes conversions between numbers are

possible. doubleVariable = 7; is possible even if doubleVariable is of type double, for example.

slide-22
SLIDE 22

Creating and Initializing a Primitive Variable

22

x

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000001110101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

x

primitive value byte x = 7;

slide-23
SLIDE 23

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

Changing the Value of a Primitive Variable

23

x x

primitive value byte x = 7; x = x + 1;

slide-24
SLIDE 24

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

Creating and Initializing a Primitive Variable

24

x x

primitive values

y y

byte x = 7; x = x + 1; short y = 7;

slide-25
SLIDE 25

011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101

You can't put a big cup into a small one

25

byte x = 7; x = x + 1; short y = 7; x = y;

x x

primitive values

y y

You may know 7 can fit in a byte, but compiler doesn't!

slide-26
SLIDE 26

Assignment Compatibilities

 A value of one type can be assigned to a variable

  • f any type further to the right

byte --> short --> int --> long

  • -> float --> double

 But not to a variable of any type further to the left.

 You can assign a value of type char to a variable of

type int.

slide-27
SLIDE 27

The Class String

 A value of type String is a

 Sequence of characters  Treated as a single item.

 Declaring

String greeting;

greeting = "Hello!";

  • r

String greeting = "Hello!";

  • r

String greeting = new String("Hello!");

 Printing

System.out.println(greeting);

slide-28
SLIDE 28

Concatenation of Strings

 Two strings are concatenated using the +

  • perator.

String greeting = "Hello"; String sentence; sentence = greeting + " officer"; System.out.println(sentence);

 Any number of strings can be concatenated using

the + operator.

slide-29
SLIDE 29

Concatenating Strings and Integers

 String data type

 A sequence of characters  Double quote around the characters  Concatenation using the + operator

String firstName = “Michele"; String lastName = "Van Dyne"; String fullName = firstName + " " + lastName; String favNumber = "42"; System.out.println(fullName + "'s favorite number is " + favNumber); Michele Van Dyne's favorite number is 42

29

slide-30
SLIDE 30

String Methods

 An object of the String class stores data

consisting of a sequence of characters.

 Objects have methods as well as data

 Recall a data type is a set of values and the operations

allowed on those values

For numeric data types, these are mathematical

  • perations

For class data types, these operations are its methods

slide-31
SLIDE 31

The Method length()

 The method length() returns an int.  You can use a call to method length() anywhere an

int can be used.

int count = command.length(); System.out.println("Length is " + command.length()); count = command.length() + 3;

slide-32
SLIDE 32
  • Positions start with 0, not 1.
  • The 'J' in "Java is fun." is in position 0
  • A position is referred to an index.
  • The 'f' in "Java is fun." is at index 8.

String Indices

slide-33
SLIDE 33

Escape Characters

 How would you print

"Java" refers to a language. ?

 The compiler needs to be told that the quotation

marks (") do not signal the start or end of a string, but instead are to be printed.

System.out.println( "\"Java\" refers to a language.");

Each escape sequence is a single character even though it is written with two symbols.

slide-34
SLIDE 34

Examples

System.out.println("abc\\def"); System.out.println("new\nline");

char singleQuote = '\'';

System.out.println (singleQuote);

'

abc\def

new line

slide-35
SLIDE 35

The Unicode Character Set

 Most programming languages use the ASCII

character set.

 Java uses the Unicode character set which includes

the ASCII character set.

 The Unicode character set includes characters

from many different alphabets (but you probably won't use them).

slide-36
SLIDE 36

The Empty String

 A string can have any number of characters,

including zero.

 The string with zero characters is called the empty

string.

 The empty string is useful and can be created in

many ways including

String s3 = "";

slide-37
SLIDE 37

args Array

37

public static void main(String [] args)

identifier meaning value type args[0] 1st thing on command line after Java class name "bananas" String args[1] 2nd thing on command line "12" String args[2] 3rd thing on command line after Java class "0.21" String args.length # of things on command line 3 int % java CostCalc bananas 12 0.21 To buy 12 bananas you will need $2.52 Program input comes in as Strings from command line (for now)

slide-38
SLIDE 38

Type Casting

 A type cast temporarily changes the value of a variable

from the declared type to some other type.

 For example,

double distance; distance = 9.0; int points; points = (int)distance;

 Illegal without (int)

 The value of (int)distance is 9,  The value of distance, both before and after the cast, is 9.0.  Any nonzero value to the right of the decimal point is truncated

rather than rounded.

slide-39
SLIDE 39

Type Conversion

 Java is strongly typed

 Helps protect you from mistakes (aka "bugs")

public class TypeExample0 { public static void main(String [] args) { int orderTotal = 0; double costItem = 29.95;

  • rderTotal = costItem * 1.06;

System.out.println("total=" + orderTotal); } } % javac TypeExample0.java TypeExample0.java:7: possible loss of precision found : double required: int

  • rderTotal = costItem * 1.06;

^

39

slide-40
SLIDE 40

Type Conversion

 Converting from one type to another:

 Manually → using a cast  A cast is accomplished by putting a type inside ()'s  Casting to int drops fractional part  Does not round!

public class TypeExample1 { public static void main(String [] args) { int orderTotal = 0; double costItem = 29.95;

  • rderTotal = (int) (costItem * 1.06);

System.out.println("total=" + orderTotal); } } % java TypeExample1 total=31

40

slide-41
SLIDE 41

Type Conversion

 Automatic conversion

 Numeric types:  If no loss of precision → automatic promotion

public class TypeExample2 { public static void main(String [] args) { double orderTotal = 0.0; int costItem = 30;

  • rderTotal = costItem * 1.06;

System.out.println("total=" + orderTotal); } } % java TypeExample2 total=31.8

41

slide-42
SLIDE 42

Type Conversion

 Automatic conversion

 String concatenation using the + operator converts numeric

types to also be a String

public class TypeExample3 { public static void main(String [] args) { double costItem = 29.95; String message = "The widget costs "; message = message + costItem; message = message + "!"; System.out.println(message); } } % java TypeExample3 The widget costs 29.95!

42

slide-43
SLIDE 43

Static Methods

 Java has lots of helper methods

 Things that take value(s) and return a result  e.g. Math functions  e.g. Type conversion: String → int

String → double

 e.g. Random number generation

 For now, we'll stick to static methods

 Live in some particular Java class  e.g. Math, Integer or Double  Call using class name followed by dot

43

slide-44
SLIDE 44

Converting Text to a Numeric Type

44

method description Integer.parseInt(String a) converts text a into an int Double.parseDouble(String a) convert text a into a double

public class CostCalc { public static void main(String [] args) { String product = args[0]; int qty = Integer.parseInt(args[1]); double cost = Double.parseDouble(args[2]); double total = qty * cost; System.out.print("To buy " + qty); System.out.print(" " + product); System.out.println(" you will need $" + total); } }

% java CostCalc elections 2 1e6 To buy 2 elections you will need $2000000.0

slide-45
SLIDE 45

Parentheses and Precedence

 Parentheses can communicate the order in which

arithmetic operations are performed

 examples:

(cost + tax) * discount (cost + (tax * discount)

 Without parentheses, an expressions is evaluated

according to the rules of precedence.

slide-46
SLIDE 46

Integers

 int data type

 Normal rules of mathematical precedence  e.g. multiplication/division before addition/subtraction  Use ()'s to force a different order of calculation

example result comment 10 + 7 * 2 24 multiplication comes before addition (10 + 7) * 2 34 ()'s force addition to occur first 10 / 7 + 2 3 integer division result is 1 which is added to 2 10 - 7 - 2 1 (10 - 7) - 2 1 10 - (7 - 2) 5

46

slide-47
SLIDE 47

Precedence Rules

 When binary operators have equal precedence, the operator

  • n the left acts before the operator(s) on the right.
slide-48
SLIDE 48

Specialized Assignment Operators

 Assignment operators can be combined with

arithmetic operators

 (including -, *, /, and %)

amount = amount + 5;

can be written as amount += 5;

yielding the same results.

slide-49
SLIDE 49

Comparisons

49

 Given two numbers → return a boolean

  • perator meaning

true example false example == equal 7 == 7 7 == 8 != not equal 7 != 8 7 != 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 Is the sum of a, b and c equal to 0? (a + b + c) == 0 Is grade in the B range? (grade >= 80.0) && (grade < 90.0) Is sumItems an even number? (sumItems % 2) == 0

slide-50
SLIDE 50

Leap Year Example

50

public class LeapYear { public static void main(String [] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // Leap year if divisible by 4 but not by 100 isLeapYear = (year % 4 == 0) && (year % 100 != 0); // But also leap year if divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }

 Years divisible by 4 but not by 100 → leap year  Years divisible by 400 → leap year

% java LeapYear 2000 true

slide-51
SLIDE 51

Type Conversion Quiz

 Automatic: no loss of precision

 int will convert to a double if need be  double cannot automatically convert to int

 Manual: cast or using a method

51

expression resulting type resulting value (int) 3.14159 Math.round(3.6) 2 * 3.0 2 * (int) 3.0 (int) 2 * 3.0

slide-52
SLIDE 52

String Conversion Quiz

 String conversion, using:

 Integer.parseInt()  Double.parseDouble()

52

expression resulting type resulting value Integer.parseInt("30") Double.parseDouble("30") Integer.parseInt("30.1") Double.parseDouble("30.1") Integer.parseInt("$30") Double.parseDouble(3.14)

slide-53
SLIDE 53

String Concatenation Quiz

 + is addition for numeric types  + is concatenation for String type  numeric types convert to String if needed

 Strings never (automatically) go back to number

53

expression resulting type resulting value "testing " + 1 + 2 + 3 "3.1" + 4159 "2" + " + " + "3" 1 + 2 + 3 + "66"

slide-54
SLIDE 54

Summary

Data Types

 Variables Primitive Data Types  The String Class  Type Conversion

Expressions

slide-55
SLIDE 55

First Lab

 Friday 3:00 – 5:50pm, NRB 228  Start work on assignment 0

 Due next Thursday, 9/1, before midnight!

 Help installing/using Java and Eclipse

 Already installed on lab machines  Bring your own laptop if you want  See resources page on web site for install tips

 Read entire assignment before starting the lab

 Assignment page is the contract  Has helpful frequently asked questions

55