46
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University

Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Embed Size (px)

Citation preview

Page 1: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Java BasicsVariables, Expressions, Statements, etc.

CS 21a: Introduction to Computing IDepartment of Information Systems

and Computer ScienceAteneo de Manila University

Page 2: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 2

Java Basics Now that you’ve gotten an overview of

programming in Java, it’s time to see specific things that you can do in Java and how you write code for these using OOP

Methods Variables Identifiers Primitive Types Expressions Operators Statements Strings

Page 3: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 3

Methods

Describes a specific behavior for a class

A method defines a sequence of instructions (or statements) to be carried out when that method is called

Page 4: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 4

Method composition Has a signature and body The method’s signature is written as:

Syntax: <visibility> <return type> <name>

(<input parameters>) Example: public void deposit( int amount )

The method body Statements or instructions inside the curly

braces (block of code)

Page 5: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 5

Calling methods

Other objects can “call” an object’s methods This means that that object will carry out

all the instructions written in the method To call a method, you use what is

known as the “dot notation” x.doSomething(…) means call the

“doSomething” method of x

Page 6: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 6

Variables

Variable: a storage location with a name can contain data of a given type can change value as the program runs

Using variables Declare

Establish its data type and initial value Can also be thought of as “creating the space” for

the value Set/change its value (through assignments) Use/display its value

Page 7: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 7

Attributes and Local Variables

Generally, there are 2 kinds of variables in Java Each kind differs from the other in lifetime and

“scope” restrictions on places in your code where the

variable exists and can be accessed Attributes (aka fields, or instance variables)

Scope within a class more “permanent”

Local variables Scope within a method for temporary use

Page 8: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 8

Attributes aka fields, or instance variables Defined in the body of the class, outside of any

methods (syntax: <visibility> <type> <name>;) Storage space exists as long as owner exists Instance variables belong to a particular instance

of an object (e.g., balance of BankAccount) There’s also such a thing as a class variable or

static variable shared by all instances of a class more on this later

Page 9: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 9

Local Variables Defined inside a method Temporary storage that is only available

while you are running that method Think of it as “scratchpad” storage Parameters are special local variables

hold the input values to a method, e.g., the amount variable in public void deposit( int amount )

Page 10: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 10

BankAccount Example

BankAccount

int balance

BankAccount() (constructor)

int getBalance()void deposit( int amount )

public class BankAccount{ private int balance;

public BankAccount() { this.balance = 0; }

public int getBalance() { return this.balance; }

public void deposit( int amount ) { this.balance = this.balance + amount; } …}

BankAccount.java

acct1: BankAccount

0balance

Suppose acct1 already exists,and another object calls …

acct1.deposit( 100 );

What happens?

A variable named amount is created with value 100 and passed as the parameter to deposit. (It also becomes a local variable within deposit.)

Read the value of this.balance, add to value of amount, and store the value into this.balance again

100

amount0 100

100100

Page 11: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 11

BankAccount Example

BankAccount

int balance

BankAccount() (constructor)

int getBalance()void deposit( int amount )

public class BankAccount{ private int balance;

public BankAccount() { this.balance = 0; }

public int getBalance() { return this.balance; }

public void deposit( int amount ) { this.balance = this.balance + amount; } …}

BankAccount.java

acct1: BankAccount

0balance

Suppose acct1 already exists,and another object calls …

acct1.deposit( 100 );

What happens?

A variable named amount is created with value 100 and passed as the parameter to deposit. (It also becomes a local variable within deposit.)

Read the value of this.balance, add to value of amount, and store the value into this.balance again

0 100

100100

amount variableis destroyedwhen themethodcompletes

Page 12: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 12

Statements Statements are “instructions” that tell the program to “do

something” One or more statements comprise the body of a method Some kinds of statements in Java:

Declarations Assignments Method return Output statements Conditional statements Loops Exception Handling

Statements usually have to end with a ; Except when ending in } for conditionals, loops, exceptions

Page 13: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 13

Declaration Creates the storage space for a variable Used when declaring fields in a class and

when declaring local variables in a method

Generally, in the form of <type> <name>; Optional: initial assignment e.g.,

double interest;int withdrawalLimit = 20000;

Page 14: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 14

Assignment Assigns a value to the variable Generally, in the form <variable name> =

<expression>; e.g., this.balance = this.balance + amount;

The left-hand side (variable name) must be a variable Because you will assign a value to it Cannot be a method or a constant or an expression that does

not specify a variable as a storage space The right-hand side can be any expression that results

in the same type as the left-hand side variable If the types are different, the compiler gives you an

error In C, the compiler usually does NOT give an error. That is why

Java is easier to program in than C

Page 15: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 15

Java keyword: new

Use new to create instances of a class Calls the constructor of the class b = new BankAccount();

A valid expressionrepresentingthe object created

Page 16: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 16

Method Return When inside a method, you can exit the

method and return a value by saying: return <expression>; Where <expression> is an expression that has the

same type as the return type of the method signature

Quits the method immediately The caller of the method gets the return value

(and possibly it to another variable) e.g., bobBalance = bobAccount.getBalance();

Page 17: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 17

Output Statements There is a special method called

System.out.println( … ) that can print different types of data E.g., System.out.println( “Hello World” ); int x = 2 + 3;

System.out.println( x ); // what will this print?

We won’t need to use much for now because BlueJ allows us to directly see values of variables

But useful for debugging …

Page 18: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 18

Identifiers An identifier is a name in a Java program

used for variables, classes, methods, ... Rules in forming an identifier:

consists of letters and digits, $, _ should start with letter or underscore canNOT contain spaces

Examples: ateneo score5 total_credit bigBlue _one4three x if

Some identifiers are reserved words

Page 19: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 19

Java Conventions for Identifiers Class names

Start with a capital letter, capitalize first letters of succeeding words

Examples: HelloAgain, ComputePriceApplet Variable and method names

Start with a lowercase letter, capitalize first letters of succeeding words

aka “camelCase” Examples: dimeCount, unitPriceInDollars, onButtonPressed

Constants All uppercase, use _ in between words Examples: PI, MAX_ELEMENT

Note: Do not use $ in your names, even if you can!

Page 20: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 20

Data Types Describes “what” a variable can contain Helps a compiler impose rules Some primitive data types in Java:

int, char, float, long, double, boolean Each primitive type also have a proper

syntax for expressing literals e.g., 234 is an integer literal, ‘A’ is a character

literal, 2.1e-3 is a double floating point literal

Page 21: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 21

Understanding Data Types

Important components of a data type:

Range of values Literals Possible operations

Page 22: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 22

The int Data Type Range: -2,147,483,648 to 2,147,483,647

The range is limited because these are the numbers that can be represented by a 32-bit binary number

Literals sequence of digits Examples: 22, 16, 1, 426, 0, 12900

Operations: usual arithmetic operations +, -, *, /, % negative numbers obtained using - as prefix

Page 23: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 23

Binary Numbers Humans can naturally count up to 10 values, But computers can count only up to 2 values (OFF and ON, or

0 and 1) Humans use decimal, computers use binary Example: an 8-bit number is called a byte

0

20

b0

0

21

b1

1

22

b2

0

23

b3

0

24

b4

1

25

b5

1

26

b6

0

27

b7

011001002 = 26 + 25 + 22

= 64 + 32 + 4 = 10010

Range0 to 2n - 1

Note: In Java, a byte is actually signed, and has a range of -128 to +127. The last bit has a place value of -128 instead of 128. More on this later…

Page 24: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 24

The double Data Type Values: decimal numbers

Range: 4.94e-324 to 1.80e+308 Limited precision:

n.nnnnnnnnnnnnnnn ... X 10(+/-)mmm

Even though you can specify up to 10308, you don’t actually get 308 digits of precision, just a few (check how many)

Again, this is because we are limited (in this case, to 64 bits)

Literals (examples) 100.5, 0.33333, 200000.0 -8E10 (-80000000000), 2.1e-3 (0.0021)

Operations: arithmetic ops (division?) float: lower precision (fewer digits)

Page 25: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 25

Constants Literal values in a program

Appear often enough and may be associated with an appropriate name

Declare at the level of the methods (right after the opening curly brace for the class)

Prefix the declaration with public static final Examples (note naming convention)

public static final int MAX = 100; public static final double PI = 3.1415926; public static final double DIME_VALUE = 0.10;

Page 26: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 26

Operators and Expressions

Page 27: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 27

Operators in Java

Arithmetic operators +, -, *, /, %

Special operators (, ) performs grouping = (assignment)

Other operators

Page 28: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 28

Understanding Operators Operands

count (binary/unary) type

Return value Calculation performed value and type returned

Effects does this operator cause a change in the value

of a variable?

Page 29: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 29

Example: % Modulo (aka “mod”) or Remainder operator Operands

Binary operation Both operands are ints

Returns: the (int) remainder when left operand is divided

by the right operand Effects:

none

Page 30: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 30

Another Example: = Assignment Operator Operands

Binary operation Left operand must be a variable

Returns: the value of the right operand

Effect: value of left variable becomes set to the value of

the right operand Note that a = b = c = 0; is valid.

Page 31: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 31

Other Operators Increment and decrement operators

++, -- post- or pre-

Assignment operators +=, -=, *=, /=, …

“Built-in” Functions not really operators (but similar) Math.abs(), Math.sqrt(), Math.pow(), ...

Page 32: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 32

Post-increment Operator: ++

Example: number++ Operands

Unary operator Operand must be a variable

Returns: the original value of the operand

Effect: variable is incremented

Note: the variable is incremented after its value is returned

Page 33: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 33

Pre-increment Operator: ++

Example: ++number Operands

Unary operator Operand must be a variable

Returns: the new (incremented) value of the operand

Effect: variable is incremented

Note: the variable is incremented before its value is returned

Page 34: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 34

About ++ Notice that a++; and ++a; are

similar return value is ignored in both cases could be used as shorthands for a = a + 1;

But they are not the same! Difference is seen when the return value is

useda = 5; a = 5;b = a++; b = ++a;// values of a & b? // values of a & b?

Page 35: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 35

Decrement Operator: --

Analogous definitions for

Post-decrement number-- Pre-decrement --number

Page 36: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 36

Assignment Operators

There is a shorthand for constructs such as sum = sum + number;

sum += number; += is an operator:

such an operator exists for virtually every arithmetic operator

+=, -=, *=, /=, %=, ... effect: variable is updated returned value: the updated value

Page 37: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 37

Built-in Functions Provided in Java to provide for more

complex operations Example: Math.pow()

double result = Math.pow( 5.5, 3.0 ); can be viewed as a binary operation that

calculates some power of a number javap java.lang.Math

prints a list of available math functions

Page 38: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 38

Operand Types vs Result Type

There are cases where the type of the result differs from the types of the operands

Examples division between an int and a double

returns a double Math.round() has an operand (argument)

that is a float but returns an int

Page 39: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 39

Caveats on Operand types

Be Careful! For arithmetic operators, return value depends on types

Example double x = 5 / 2; // puts 2 (not 2.5) in x

Why? because 5 is an int, and 2 is an int Fix? double x = 5.0 / 2;

Page 40: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 40

Casting Primitive Types

int a = 5; int b = 2;double x = a / b;

Problem: still returns 2 Fix? Do a “cast”

tells Java to change data type double x = (double)a / (double)b

Note: casting can also be used for rounding (down) int x = Math.sqrt( 2.0 ); // won’t work int x = (int)Math.sqrt( 3.0 ); // returns 1 int x = (int)Math.round( Math.sqrt( 3.0 ) ); // returns 2

Page 41: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 41

Strings and Concatenation Consider the statement:

System.out.println( “Hello” ); “Hello” is of type String The + operation can be used for String

concatenation works between Strings, and also between Strings and

primitive types Examples

System.out.println( “basket” + “ball” ); System.out.println( “the sum is ” + sum );

// sum is first converted to a String

Page 42: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 42

Expressions Expression

a sequence of variables, literals, operators, and/or method/function calls

has a return value and type Uses

right operand of an assignment argument for System.out.println()

Expression-statement an expression terminated by a semicolon

Page 43: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 43

Statements

Page 44: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 44

So far … Variable

contains data Expression

sequence of variables, operators, literals, and function calls

has return value used for operations on data

Statement tells Java to actually carry out the computation may contain expressions is included in the body of a method

Page 45: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 45

Statements in Java

Declarations Example: double distance = 3.5;

Expression-statements Examples:

x = 5; area = PI * radius * radius; ++count; a = b = c = 0; result = Math.pow( 2.0, 0.5 ) / 3;

Page 46: Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo

Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved

L4: Java BasicsSlide 46

Statements, continued Input and output statements are in fact

expression-statements Examples

x = JOptionPane.showInputDialog( “Enter x” ); System.out.println( answer );

contain function calls Other statements

Decision statements (conditional execution) Loops Others