Java Programming Basics

Download Report

Transcript Java Programming Basics

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

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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 2
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 3
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)
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 4
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 5
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 6
Attributes and Local Variables

Generally, there are 2 kinds of variables in Java

Each kind differs from the other in lifetime and
“scope”


Attributes (aka fields, or instance variables)



restrictions on places in your code where the variable
exists and can be accessed
Scope within a class
more “permanent”
Local variables


Scope within a method
for temporary use
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 7
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 8
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 )
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 9
BankAccount Example
Suppose acct1 already exists,
and another object calls …
public class BankAccount
{
acct1.deposit(
100 );
private int balance;
BankAccount
What happens?
public BankAccount()
int balance
{
BankAccount() (constructor)
int getBalance()
void deposit( int amount )
this.balance = 0;
}
public int getBalance()
{
return this.balance;
}
amount
acct1: BankAccount
balance
0
100
100
}
BankAccount.java
A variable named
amount is
created with
value 100 and
passed as the
parameter to
deposit. (It also
becomes a local
variable within
deposit.)
public void deposit( int amount )
100
0
{
this.balance = this.balance + amount;
}
…
100
Read the value of this.balance, add to
L4: Java
Basics
value
of and
amount,
value
Copyright 2005, by the authors of these
slides,
Ateneo deand store the
Slide 10
Manila University. All rights
intoreserved
this.balance again
BankAccount Example
Suppose acct1 already exists,
and another object calls …
BankAccount
public class BankAccount
{
acct1.deposit(
100 );
private int balance;
What happens?
public BankAccount()
int balance
{
BankAccount() (constructor)
int getBalance()
void deposit( int amount )
amount variable
is destroyed
when the
method
completes
acct1: BankAccount
balance
0
100
this.balance = 0;
}
public int getBalance()
{
return this.balance;
}
}
BankAccount.java
A variable named
amount is
created with
value 100 and
passed as the
parameter to
deposit. (It also
becomes a local
variable within
deposit.)
public void deposit( int amount )
100
0
{
this.balance = this.balance + amount;
}
…
100
Read the value of this.balance, add to
L4: Java
Basics
value
of and
amount,
value
Copyright 2005, by the authors of these
slides,
Ateneo deand store the
Slide 11
Manila University. All rights
intoreserved
this.balance again
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 12
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;
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 13
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 14
Java keyword: new



Use new to create instances of a class
Calls the constructor of the class
b = new BankAccount();
A valid expression
representing
the object created
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 15
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();
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 16
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 …
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 17
Identifiers

An identifier is a name in a Java program


Rules in forming an identifier:





used for variables, classes, methods, ...
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 18
Java Conventions for Identifiers

Class names



Variable and method names




Start with a lowercase letter, capitalize first letters of succeeding words
aka “camelCase”
Examples: dimeCount, unitPriceInDollars, onButtonPressed
Constants



Start with a capital letter, capitalize first letters of succeeding words
Examples: HelloAgain, ComputePriceApplet
All uppercase, use _ in between words
Examples: PI, MAX_ELEMENT
Note: Do not use $ in your names, even if you can!
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 19
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 20
Understanding Data Types
Important components of a data type:



Range of values
Literals
Possible operations
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 21
The int Data Type

Range: -2,147,483,648 to 2,147,483,647


Literals



The range is limited because these are the numbers
that can be represented by a 32-bit binary number
sequence of digits
Examples: 22, 16, 1, 426, 0, 12900
Operations: usual arithmetic operations


+, -, *, /, %
negative numbers obtained using - as prefix
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 22
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
b7 b6 b5 b4 b3 b2 b1 b0
Range
0 to 2n - 1
0 1 1 0 0 1 0 0
27 26 2 5 24 23 22 21 20
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…
011001002 = 26 + 25 +
22
= 64 + 32 + 4
Copyright 2005, by the authors of these slides, and Ateneo de
= 10010rights reserved
Manila University. All
L4: Java Basics
Slide 23
The double Data Type

Values: decimal numbers


Range: 4.94e-324 to 1.80e+308
Limited precision:




Literals (examples)




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)
100.5, 0.33333, 200000.0
-8E10 (-80000000000), 2.1e-3 (0.0021)
Operations: arithmetic ops (division?)
float: lower precision (fewer digits)
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 24
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;
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 25
Operators and Expressions
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 26
Operators in Java

Arithmetic operators


Special operators



+, -, *, /, %
(, ) performs grouping
= (assignment)
Other operators
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 27
Understanding Operators

Operands



Return value



count (binary/unary)
type
Calculation performed
value and type returned
Effects

does this operator cause a change in the value of a
variable?
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 28
Example: %


Modulo (aka “mod”) or Remainder operator
Operands



Returns:


Binary operation
Both operands are ints
the (int) remainder when left operand is divided by
the right operand
Effects:

none
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 29
Another Example: =


Assignment Operator
Operands



Returns:


the value of the right operand
Effect:


Binary operation
Left operand must be a variable
value of left variable becomes set to the value of the
right operand
Note that a = b = c = 0; is valid.
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 30
Other Operators

Increment and decrement operators



Assignment operators


++, -post- or pre+=, -=, *=, /=, …
“Built-in” Functions


not really operators (but similar)
Math.abs(), Math.sqrt(), Math.pow(), ...
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 31
Post-increment Operator: ++


Example: number++
Operands



Returns:


the original value of the operand
Effect:


Unary operator
Operand must be a variable
variable is incremented
Note: the variable is incremented after its value
is returned
L4: Java Basics
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
Slide 32
Pre-increment Operator: ++


Example: ++number
Operands



Returns:


the new (incremented) value of the operand
Effect:


Unary operator
Operand must be a variable
variable is incremented
Note: the variable is incremented before its
value is returned
L4: Java Basics
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
Slide 33
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
used
a = 5;
b = a++;
// values of a & b?
a = 5;
b = ++a;
// values of a & b?
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 34
Decrement Operator: -Analogous definitions for


Post-decrement
Pre-decrement
number---number
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 35
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 36
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 37
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 38
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;
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 39
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 40
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 41
Expressions

Expression



Uses



a sequence of variables, literals, operators, and/or
method/function calls
has a return value and type
right operand of an assignment
argument for System.out.println()
Expression-statement

an expression terminated by a semicolon
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 42
Statements
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 43
So far …

Variable


Expression




contains data
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 44
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;
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 45
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
Copyright 2005, by the authors of these slides, and Ateneo de
Manila University. All rights reserved
L4: Java Basics
Slide 46