114
An Introduction to Software Development Using JAVA Java Java

An Introduction to Software Development Using JAVA Java

Embed Size (px)

Citation preview

Page 1: An Introduction to Software Development Using JAVA Java

An Introduction to Software Development Using JAVA

JavaJava

Page 2: An Introduction to Software Development Using JAVA Java

2-2

Objectives:

• Understand the software development process, tools, and priorities

• Understand compilers and interpreters

• Learn about Java Virtual Machine, bytecodes

• Learn to set up and run simple console applications, GUI applications, and applets in Java

• Learn basic facts about OOP

Page 3: An Introduction to Software Development Using JAVA Java

2-3

Software Today:

6,460,000,000

Page 4: An Introduction to Software Development Using JAVA Java

2-4

Software Applications

• Large business systems

• Databases

• Internet, e-mail, etc.

• Military

• Embedded systems

• Scientific research

• AI

• Word processing and other small business and personal productivity tools

• Graphics / arts / digital photography

• Games

Page 5: An Introduction to Software Development Using JAVA Java

2-5

Software Development

• Emphasis on efficiency fast algorithms small program size limited memory use

• Often cryptic code

• Not user-friendly

• Emphasis on programmer’s

productivity team development reusability of code easier maintenance portability

• Better documented

• User-friendly

1950-1960's: Now:

Page 6: An Introduction to Software Development Using JAVA Java

2-6

Programming Languages

1940 1950 1960 1970 1980 1990 2000

Machinecode

Assembly languages

FortranBasic

Pascal

Scheme

C C++

JavaLISP

Smalltalk Smalltalk-80

C#

Logo

Python

Page 7: An Introduction to Software Development Using JAVA Java

2-7

Software Development Tools

• Editor programmer writes

source code

• Compiler translates the source

into object code (instructions specific to a particular CPU)

• Linker converts one or several

object modules into an executable program

• Debugger steps through the

program “in slow motion” and helps find logical mistakes (“bugs”)

Page 8: An Introduction to Software Development Using JAVA Java

2-8

The First “Bug”

“(moth) in relay”

Mark II Aiken Relay Calculator (Harvard University, 1945)

Page 9: An Introduction to Software Development Using JAVA Java

2-9

Compiled Languages:Edit-Compile-Link-Run

Editor Sourcecode

Compiler Objectcode

Linker Executableprogram

Editor Sourcecode

Compiler Objectcode

Editor Sourcecode

Compiler Objectcode

Page 10: An Introduction to Software Development Using JAVA Java

2-10

Interpreted Languages:Edit-Run

Editor Sourcecode

Interpreter

Page 11: An Introduction to Software Development Using JAVA Java

2-11

Compiler vs. Interpreter

• Compiler: checks syntax generates

machine-code instructions

not needed to run the executable program

the executable runs faster

• Interpreter: checks syntax executes appropriate

instructions while interpreting the program statements

must remain installed while the program is interpreted

the interpreted program is slower

Page 12: An Introduction to Software Development Using JAVA Java

2-12

Java’s Hybrid Approach:Compiler + Interpreter

• A Java compiler converts Java source code into instructions for the Java Virtual Machine.

• These instructions, called bytecodes, are the same for any computer / operating system.

• A CPU-specific Java interpreter interprets bytecodes on a particular computer.

Page 13: An Introduction to Software Development Using JAVA Java

2-13

Java’s Compiler + Interpreter

Editor

Hello.java

Compiler

Hello.class

Interpreter

Hello,World!

Interpreter

Page 14: An Introduction to Software Development Using JAVA Java

2-14

Why Bytecodes?

• Platform-independent

• Load from the Internet faster than source code

• Interpreter is faster and smaller than it would be for Java source

• Source code is not revealed to end users

• Interpreter performs additional security checks, screens out malicious code

Page 15: An Introduction to Software Development Using JAVA Java

2-15

JDK — Java Development Kit

• javac Java compiler

• java Java interpreter

• appletviewer tests applets without a

browser

• javadoc generates HTML

documentation (“docs”) from source

• jar packs classes into jar

files (packages)

All these are command-line tools, no GUI

Page 16: An Introduction to Software Development Using JAVA Java

2-16

JDK (cont’d)

• Available free from Sun Microsystems

• All documentation is online:

• Many additional Java resources on the Internet

http://java.sun.com/javase/index.jsp

Page 17: An Introduction to Software Development Using JAVA Java

2-17

Java IDE

• GUI front end for JDK

• Integrates editor, javac, java, appletviewer, debugger, other tools: specialized Java editor with syntax highlighting,

autoindent, tab setting, etc. clicking on a compiler error message takes you to

the offending source code line

• Usually JDK is installed separately and an IDE is installed on top of it.

Page 18: An Introduction to Software Development Using JAVA Java

2-18

Types of Programs

• Console applications • GUI applications

• Applets

Page 19: An Introduction to Software Development Using JAVA Java

2-19

Console Applications

C:\javamethods\Ch02> path=%PATH%;C:\Program Files\Java\jdk 1.5.0_07\binC:\javamethods\Ch02> javac Greetings2.javaC:\javamethods\Ch02> java Greetings2Enter your first name: JosephineEnter your last name: JaworskiHello, Josephine JaworskiPress any key to continue...

• Simple text dialog:prompt input, prompt input ... result

Page 20: An Introduction to Software Development Using JAVA Java

2-20

Command-Line ArgumentsC:\javamethods\Ch02> javac Greetings.javaC:\javamethods\Ch02> java Greetings Josephine Jaworski

Hello, Josephine Jaworski

public class Greetings{ public static void main(String[ ] args) { String firstName = args[ 0 ]; String lastName = args[ 1 ]; System.out.println("Hello, " + firstName + " " + lastName); }}

Command-line arguments are passed to mainas an array of Strings.

Page 21: An Introduction to Software Development Using JAVA Java

2-21

Command-Line Args (cont’d)

• Can be used in GUI applications, too

• IDEs provide ways to set them (or prompt for them)

Josephine Jaworski

Page 22: An Introduction to Software Development Using JAVA Java

2-22

Greetings2.javaimport java.util.Scanner;

public class Greetings2{ public static void main(String[ ] args) { Scanner kboard = new Scanner(System.in); System.out.print("Enter your first name: "); String firstName = kboard.nextLine( ); System.out.print("Enter your last name: "); String lastName = kboard.nextLine( ); System.out.println("Hello, " + firstName + " " + lastName); System.out.println("Welcome to Java!"); }}

Prompts

Page 23: An Introduction to Software Development Using JAVA Java

2-23

GUI Applications

Menus

Buttons

Clickable panel

Slider

Page 24: An Introduction to Software Development Using JAVA Java

2-24

HelloGui.javaimport java.awt.*;import javax.swing.*;

public class HelloGui extends JFrame{ < ... other code >

public static void main(String[ ] args) { HelloGui window = new HelloGui( ); // Set this window's location and size: // upper-left corner at 300, 300; width 200, height 100 window.setBounds(300, 300, 200, 100); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); }}

GUI libraries

Page 25: An Introduction to Software Development Using JAVA Java

2-25

HelloApplet.java

import java.awt.*;import javax.swing.*;

public class HelloApplet extends JApplet{ public void init( ) { ... } < ... other code >}

No main in applets: the init method is called by JDK’s appletviewer or the browser

Page 26: An Introduction to Software Development Using JAVA Java

2-26

OOP —Object-Oriented Programming

• An OOP program models a world of active objects.

• An object may have its own “memory,” which may contain other objects.

• An object has a set of methods that can process messages of certain types.

Page 27: An Introduction to Software Development Using JAVA Java

2-27

OOP (cont’d)

• A method can change the object’s state, send messages to other objects, and create new objects.

• An object belongs to a particular class, and the functionality of each object is determined by its class.

• A programmer creates an OOP application by defining classes.

Page 28: An Introduction to Software Development Using JAVA Java

2-28

The Main OOP Concepts:

• Inheritance: a subclass extends a superclass; the objects of a subclass inherit features of the superclass and can redefine them or add new features.

• Event-driven programs: the program simulates asynchronous handling of events; methods are called automatically in response to events.

Page 29: An Introduction to Software Development Using JAVA Java

2-29

Inheritance

• A programmer can define hierarchies of classes

• More general classes are closer to the top

Person

Child Adult

Baby Toddler Teen

Page 30: An Introduction to Software Development Using JAVA Java

2-30

OOP Benefits

• Facilitates team development

• Easier to reuse software components and write reusable software

• Easier GUI (Graphical User Interface) and multimedia programming

Page 31: An Introduction to Software Development Using JAVA Java

2-31

Review:

• What are some of the current software development concerns?

• What are editor, compiler, debugger used for?

• How is a compiler different from an interpreter?

• Name some of the benefits of Java’s compiler+interpreter approach.

• Define IDE.

Page 32: An Introduction to Software Development Using JAVA Java

2-32

Review (cont’d):

• What is a console application?

• What are command-line arguments?

• What is a GUI application?

• What is the difference between a GUI application and an applet?

• What is OOP?

• Define inheritance.

Page 33: An Introduction to Software Development Using JAVA Java

2-33

Introduction • Present the syntax of Java

• Introduce the Java API

• Demonstrate how to build stand-alone Java programs Java applets, which run within browsers e.g.

Netscape

• Example programs

Page 34: An Introduction to Software Development Using JAVA Java

2-34

Why Java?• It’s the current “hot” language

• It’s entirely object-oriented

• It has a vast library of predefined objects and operations

• It’s more platform independent this makes it great for Web programming

• It’s more secure

• It isn’t C++

Page 35: An Introduction to Software Development Using JAVA Java

2-35

Applets, Servlets and Applications• An applet is designed to be embedded in a

Web page, and run by a browser

• Applets run in a sandbox with numerous restrictions; for example, they can’t read files and then use the network

• A servlet is designed to be run by a web server

• An application is a conventional program

Page 36: An Introduction to Software Development Using JAVA Java

2-36

Building Standalone JAVA Programs (on UNIX)• Prepare the file foo.java using an editor

• Invoke the compiler: javac foo.java

• This creates foo.class

• Run the java interpreter: java foo

Page 37: An Introduction to Software Development Using JAVA Java

2-37

Java Virtual Machine

• The .class files generated by the compiler are not executable binaries so Java combines compilation and interpretation

• Instead, they contain “byte-codes” to be executed by the Java Virtual Machine other languages have done this, e.g. UCSD Pascal

• This approach provides platform independence, and greater security

Page 38: An Introduction to Software Development Using JAVA Java

2-38

HelloWorld (standalone)

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); }}

• Note that String is built in

• println is a member function for the System.out class

Page 39: An Introduction to Software Development Using JAVA Java

2-39

Comments are almost like C++• /* This kind of comment can span multiple lines */

• // This kind is to the end of the line

• /** * This kind of comment is a special * ‘javadoc’ style comment */

Page 40: An Introduction to Software Development Using JAVA Java

2-40

Primitive data types are like C• Main data types are int, double, boolean, char

• Also have byte, short, long, float

• boolean has values true and false

• Declarations look like C, for example, double x, y; int count = 0;

Page 41: An Introduction to Software Development Using JAVA Java

2-41

Expressions are like C

• Assignment statements mostly look like those in C; you can use =, +=, *= etc.

• Arithmetic uses the familiar + - * / %

• Java also has ++ and --

• Java has boolean operators && || !

• Java has comparisons < <= == != >= >

• Java does not have pointers or pointer arithmetic

Page 42: An Introduction to Software Development Using JAVA Java

2-42

Control statements are like C• if (x < y) smaller = x;

• if (x < y){ smaller=x;sum += x;}else { smaller = y; sum += y; }

• while (x < y) { y = y - x; }

• do { y = y - x; } while (x < y)

• for (int i = 0; i < max; i++) sum += i;

• BUT: conditions must be boolean !

Page 43: An Introduction to Software Development Using JAVA Java

2-43

Control statements II

• Java also introduces the try statement, about which more later

switch (n + 1) { case 0: m = n - 1; break; case 1: m = n + 1; case 3: m = m * n; break; default: m = -n; break;}

Page 44: An Introduction to Software Development Using JAVA Java

2-44

Java isn't C!

• In C, almost everything is in functions

• In Java, almost everything is in classes

• There is often only one class per file

• There must be only one public class per file

• The file name must be the same as the name of that public class, but with a .java extension

Page 45: An Introduction to Software Development Using JAVA Java

2-45

Java program layout

• A typical Java file looks like:

import java.awt.*;import java.util.*;

public class SomethingOrOther { // object definitions go here . . .}

This must be in a file named SomethingOrOther.java !

Page 46: An Introduction to Software Development Using JAVA Java

2-46

What is a class?• Early languages had only arrays

all elements had to be of the same type

• Then languages introduced structures (called records, or structs) allowed different data types to be grouped

• Then Abstract Data Types (ADTs) became popular grouped operations along with the data

Page 47: An Introduction to Software Development Using JAVA Java

2-47

So, what is a class?

• A class consists of a collection of fields, or variables, very much like

the named fields of a struct all the operations (called methods) that can be

performed on those fields can be instantiated

• A class describes objects and operations defined on those objects

Page 48: An Introduction to Software Development Using JAVA Java

2-48

Name conventions

• Java is case-sensitive; maxval, maxVal, and MaxVal are three different names

• Class names begin with a capital letter

• All other names begin with a lowercase letter

• Subsequent words are capitalized: theBigOne

• Underscores are not used in names

• These are very strong conventions!

Page 49: An Introduction to Software Development Using JAVA Java

2-49

The class hierarchy

• Classes are arranged in a hierarchy

• The root, or topmost, class is Object

• Every class but Object has at least one superclass

• A class may have subclasses

• Each class inherits all the fields and methods of its (possibly numerous) superclasses

Page 50: An Introduction to Software Development Using JAVA Java

2-50

An example of a class

class Person { String name; int age;

void birthday ( ) { age++; System.out.println (name + ' is now ' + age); }}

Page 51: An Introduction to Software Development Using JAVA Java

2-51

Another example of a class

class Driver extends Person { long driversLicenseNumber; Date expirationDate;}

Page 52: An Introduction to Software Development Using JAVA Java

2-52

Creating and using an object

• Person john;john = new Person ( );john.name = "John Smith";john.age = 37;

• Person mary = new Person ( );mary.name = "Mary Brown";mary.age = 33;mary.birthday ( );

Page 53: An Introduction to Software Development Using JAVA Java

2-53

An array is an object

• Person mary = new Person ( );

• int myArray[ ] = new int[5]; or:

• int myArray[ ] = {1, 4, 9, 16, 25};

• String languages [ ] = {"Prolog", "Java"};

Page 54: An Introduction to Software Development Using JAVA Java

2-54

Objects and Classes

Page 55: An Introduction to Software Development Using JAVA Java

2-55

Objectives:

• See an example of a small program written in OOP style and discuss the types of objects used in it

• Learn about the general structure of a class, its fields, constructors, and methods

• Get a feel for how objects are created and how to call their methods

• Learn a little about inheritance in OOP

Page 56: An Introduction to Software Development Using JAVA Java

2-56

OOP

• An OO program models the application as a world of interacting objects.

• An object can create other objects.

• An object can call another object’s (and its own) methods (that is, “send messages”).

• An object has data fields, which hold values that can change while the program is running.

Page 57: An Introduction to Software Development Using JAVA Java

2-57

Objects

• Can model real-world objects

• Can represent GUI (Graphical User Interface) components

• Can represent software entities (events, files, images, etc.)

• Can represent abstract concepts (for example, rules of a game, a particular type of dance, etc.)

Page 58: An Introduction to Software Development Using JAVA Java

2-58

Classes and Objects

• A class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions.

• An object is called an instance of a class. A program can create and use more than one object (instance) of the same class.

Page 59: An Introduction to Software Development Using JAVA Java

2-59

Class Object• A blueprint for

objects of a particular type

• Defines the structure (number, types) of the attributes

• Defines available behaviors of its objects

Attributes

Behaviors

Page 60: An Introduction to Software Development Using JAVA Java

2-60

Class: Car Object: a car

Attributes: String model Color color int numPassengers double amountOfGas

Behaviors: Add/remove a passenger Get the tank filled Report when out of gas

Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5

Behaviors:

Page 61: An Introduction to Software Development Using JAVA Java

2-61

Class vs. Object

• A piece of the program’s source code

• Written by a programmer

• An entity in a running program

• Created when the program is running (by the main method or a constructor or another method)

Page 62: An Introduction to Software Development Using JAVA Java

2-62

Class vs. Object

• Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects

• Specifies the possible behaviors of its objects

• Holds specific values of attributes; these values can change while the program is running

• Behaves appropriately when called upon

Page 63: An Introduction to Software Development Using JAVA Java

2-63

Classes and Source Files

• Each class is stored in a separate file

• The name of the file must be the same as the name of the class, with the extension .java

public class Car{ ...}

Car.java By convention, the name of a class (and its source file) always starts with a capital letter.

(In Java, all names are case-sensitive.)

Page 64: An Introduction to Software Development Using JAVA Java

2-64

Libraries

• Java programs are usually not written from scratch.

• There are hundreds of library classes for all occasions.

• Library classes are organized into packages. For example:

java.util — miscellaneous utility classes

java.awt — windowing and graphics toolkit

javax.swing — GUI development package

Page 65: An Introduction to Software Development Using JAVA Java

2-65

import

• Full library class names include the package name. For example:

java.awt.Color

javax.swing.JButton

• import statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton;

...

JButton go = new JButton("Go");

Fully-qualified name

Page 66: An Introduction to Software Development Using JAVA Java

2-66

import (cont’d)

• You can import names for all the classes in a package by using a wildcard .*:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

• java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes.

Imports all classes from awt, awt.event, and swing packages

Page 67: An Introduction to Software Development Using JAVA Java

2-67

public class SomeClass

• Fields

• Constructors

• Methods}

Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects

Procedures for constructing a new object of this class and initializing its fields

Actions that an object of this class can take (behaviors)

{

Class header

SomeClass.java

import ... import statements

Page 68: An Introduction to Software Development Using JAVA Java

2-68

public class Foot{ private Image picture; private CoordinateSystem coordinates;

public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem (x, y, pic); }

public void moveForward (int distance) { coordinates.shift (distance, 0); }

public void moveSideways (int distance) { coordinates.shift (0, distance); } ...}

Fields

Constructor

Methods

Page 69: An Introduction to Software Development Using JAVA Java

2-69

Fields

• A.k.a. instance variables

• Constitute “private memory” of an object

• Each field has a data type (int, double, String, Image, Foot, etc.)

• Each field has a name given by the programmer

Page 70: An Introduction to Software Development Using JAVA Java

2-70

private [static] [final] datatype name;

Fields (cont’d)

Usually private

May be present: means the field is a constant

int, double, etc., or an object: String, Image, Foot

You name it!

May be present: means the field is shared by all objects in the class

private Foot leftFoot;

Page 71: An Introduction to Software Development Using JAVA Java

2-71

Constructors

• Short procedures for creating objects of a class

• Always have the same name as the class

• Initialize the object’s fields

• May take parameters

• A class may have several constructors that differ in the number and/or types of their parameters

Page 72: An Introduction to Software Development Using JAVA Java

2-72

Constructors (cont’d)

public class Foot{ private Image picture; private CoordinateSystem coordinates;

public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem(x, y, pic); } ...}

The name of a constructor is always the same as the name of the class

A constructor can take parameters

Initializes fields

Page 73: An Introduction to Software Development Using JAVA Java

2-73

Constructors (cont’d)

public class Foot{

...

public Foot (int x, int y, Image pic) { ... } ...}

// FootTest.java ... Image leftShoe = ...; ... Foot leftFoot = new Foot (5, 20, leftShoe); ...

An object is created with the new operator

The number, order, and types of parameters must match

Constructor

Page 74: An Introduction to Software Development Using JAVA Java

2-74

Constructors (cont’d)

JButton go = new JButton("Go");

Page 75: An Introduction to Software Development Using JAVA Java

2-75

Methods

• Call them for a particular object:

leftFoot.moveForward(20);

amy.nextStep( );

ben.nextStep( );

go.setText("Stop");

Page 76: An Introduction to Software Development Using JAVA Java

2-76

Methods (cont’d)

• The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters:

g.drawString ("Welcome", 120, 50);

public void drawString ( String msg, int x, int y )

{

...

}

Page 77: An Introduction to Software Development Using JAVA Java

2-77

Methods (cont’d)

• A method can return a value to the caller

• The keyword void in the method’s header indicates that the method does not return any value

public void moveSideways(int distance) { ... }

Page 78: An Introduction to Software Development Using JAVA Java

2-78

Encapsulation and Information Hiding

• A class interacts with other classes only through constructors and public methods

• Other classes do not need to know the mechanics (implementation details) of a class to use it effectively

• Encapsulation facilitates team work and program maintenance (making changes to the code)

Page 79: An Introduction to Software Development Using JAVA Java

2-79

Methods (cont’d)

• Constructors and methods can call other public and private methods of the same class.

• Constructors and methods can call only public methods of another class.

Class X

private field

private method

Class Y

public method public method

Page 80: An Introduction to Software Development Using JAVA Java

2-80

Inheritance

• In OOP a programmer can create a new class by extending an existing class

Superclass(Base class)

Subclass(Derived class)

subclass extends superclass

Page 81: An Introduction to Software Development Using JAVA Java

2-81

A Subclass...

• inherits fields and methods of its superclass

• can add new fields and methods

• can redefine (override) a method of the superclass

• must provide its own constructors, but calls superclass’s constructors

• does not have direct access to its superclass’s private fields

Page 82: An Introduction to Software Development Using JAVA Java

2-82

public class Pacer extends Walker{ public Pacer (int x, int y, Image leftPic, Image rightPic) { super (x, y, leftPic, rightPic); }

public void turnAround () { Foot lf = getLeftFoot (); Foot rf = getRightFoot (); lf.turn (180); rf.turn (180); lf.moveSideways (-PIXELS_PER_INCH * 8); rf.moveSideways (PIXELS_PER_INCH * 8); }}

A new method

Calls Walker’s constructor using super

Constructor

Calls Walker’s accessor methods

Page 83: An Introduction to Software Development Using JAVA Java

2-83

public class Walker{ ... public int distanceTraveled() { return stepsCount * stepLength; } ...}

Overrides Walker’s distanceTraveled method

public class Slowpoke extends Walker{ ... public int distanceTraveled() { return super.distanceTraveled ( ) / 10; } ...}

Calls superclass’s distanceTraveled method

Page 84: An Introduction to Software Development Using JAVA Java

2-84

Objectives:

• Discuss primitive data types

• Learn how to declare fields and local variables

• Learn about arithmetic operators, compound assignment operators, and increment / decrement operators

• Discuss common mistakes in arithmetic

Page 85: An Introduction to Software Development Using JAVA Java

2-85

Variables

• A variable is a “named container” that holds a value.

• q = 100 - q;

means: 1. Read the current value of q 2. Subtract it from 100 3. Move the result back into q

count

5

mov ax,qmov bx,100sub bx,axmov q,bx

Page 86: An Introduction to Software Development Using JAVA Java

2-86

Variables (cont’d)

• Variables can be of different data types: int, char, double, boolean, etc.

• Variables can hold objects; then the type is the class of the object.

• The programmer gives names to variables.

• Names of variables usually start with a lowercase letter.

Page 87: An Introduction to Software Development Using JAVA Java

2-87

Variables (cont’d)

• A variable must be declared before it can be used:

int count;

double x, y;

JButton go;

Walker amy;

String firstName;

Type

Name(s)

Page 88: An Introduction to Software Development Using JAVA Java

2-88

Variables (cont’d)

• The assignment operator = sets the variable’s value:

count = 5;x = 0;go = new JButton("Go");firstName = args[0];

Page 89: An Introduction to Software Development Using JAVA Java

2-89

Variables (cont’d)

• A variable can be initialized in its declaration:

int count = 5;JButton go = new JButton("Go");String firstName = args[0];

Page 90: An Introduction to Software Development Using JAVA Java

2-90

Variables: Scope

• Each variable has a scope — the area in the source code where it is “visible.”

• If you use a variable outside its scope, the compiler reports a syntax error.

• Variables can have the same name when their scopes do not overlap.

{ int k = ...; ...}

for (int k = ...){ ...}

Page 91: An Introduction to Software Development Using JAVA Java

2-91

Fields

• Fields are declared outside all constructors and methods.

• Fields are usually grouped together, either at the top or at the bottom of the class.

• The scope of a field is the whole class.

Page 92: An Introduction to Software Development Using JAVA Java

2-92

Fields (cont’d)public class SomeClass{

}

Fields

Constructors and methods

Scope

public class SomeClass{

}Fields

Constructors and methodsScope

Or:

Page 93: An Introduction to Software Development Using JAVA Java

2-93

Local Variables

• Local variables are declared inside a constructor or a method.

• Local variables lose their values and are destroyed once the constructor or the method is exited.

• The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared.

Page 94: An Introduction to Software Development Using JAVA Java

2-94

Local Variables (cont’d)public class SomeClass{ ... public SomeType SomeMethod (...) {

{

} } ...}

ScopeLocal variable declared

Local variable declared

Page 95: An Introduction to Software Development Using JAVA Java

2-95

Variables (cont’d)

• Use local variables whenever appropriate; never use fields where local variables should be used.

• Give prominent names to fields, so that they are different from local variables.

• Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, k for indices, etc.).

Page 96: An Introduction to Software Development Using JAVA Java

2-96

Variables (cont’d)

• Common mistakes:

public void someMethod (...){ int x = 0; ... int x = 5; // should be: x = 5; ...

Variable declared twice within the same scope — syntax error

Page 97: An Introduction to Software Development Using JAVA Java

2-97

Variables (cont’d)

• Common mistakes:

private double radius;...public Circle (...) // constructor{ double radius = 5; ...

Declares a local variable radius; the value of the field radius remains 0.0

Page 98: An Introduction to Software Development Using JAVA Java

2-98

Primitive Data Types

• int

• double

• char

• boolean

• byte

• short

• long

• float

Used inJava Methods

Page 99: An Introduction to Software Development Using JAVA Java

2-99

Strings

• String is not a primitive data type

• Strings work like any other objects, with two exceptions: Strings in double quotes are recognized as literal

constants + and += concatenate strings (or a string and a

number or an object, which is converted into a string)

"Catch " + 22 "Catch 22"

Page 100: An Introduction to Software Development Using JAVA Java

2-100

Literal Constants

'A', '+', '\n', '\t'

-99, 2010, 0

0.75, -12.3, 8., .5

“coin.gif", "1776", "y", "\n"

new line

tab

char

int

double

String

Page 101: An Introduction to Software Development Using JAVA Java

2-101

Symbolic Constants

• Symbolic constants are initialized final variables:

private final int stepLength = 48;

private static final int BUFFER_SIZE = 1024;

public static final int PIXELS_PER_INCH = 6;

Page 102: An Introduction to Software Development Using JAVA Java

2-102

Why Symbolic Constants?

• Easy to change the value throughout the program, if necessary

• Easy to change into a variable

• More readable, self-documenting code

• Additional data type checking by the compiler

Page 103: An Introduction to Software Development Using JAVA Java

2-103

Arithmetic

• Operators: +, -, /, * , %

• The precedence of operators and parentheses is the same as in algebra

• m % n means the remainder when m is divided by n (for example, 17 % 5 is 2;

2 % 8 is 2)

• % has the same rank as / and *

• Same-rank binary operators are performed in order from left to right

Page 104: An Introduction to Software Development Using JAVA Java

2-104

Arithmetic (cont’d)

• The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions.

• If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.

Page 105: An Introduction to Software Development Using JAVA Java

2-105

Arithmetic (cont’d)

• Caution: if a and b are ints, then a / b is truncated to an int…

17 / 5 gives 3

3 / 4 gives 0

• …even if you assign the result to a double:

double ratio = 2 / 3;The double type of the result doesn’t help: ratio still gets the value 0.0.

Page 106: An Introduction to Software Development Using JAVA Java

2-106

Arithmetic (cont’d)

• To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3;

double ratio = 2 / 3.0;

int m = ..., n = ...;

double factor = (double)m / (double)n;

double factor = (double)m / n;

double r2 = n / 2.0;

Casts

Page 107: An Introduction to Software Development Using JAVA Java

2-107

Arithmetic (cont’d)

• A cast to int can be useful:

int ptsOnDie = (int)(Math.random() * 6) + 1;

int miles = (int)(km * 1.61 + 0.5);

Returns a double

Converts kilometers to miles, rounded to the nearest integer

Page 108: An Introduction to Software Development Using JAVA Java

2-108

Arithmetic (cont’d)

• Caution: the range for ints is from -231 to 231-1 (about -2·109 to 2·109)

• Overflow is not detected by the Java compiler or interpreter:

n = 8 10^n = 100000000 n! = 40320n = 9 10^n = 1000000000 n! = 362880n = 10 10^n = 1410065408 n! = 3628800n = 11 10^n = 1215752192 n! = 39916800n = 12 10^n = -727379968 n! = 479001600n = 13 10^n = 1316134912 n! = 1932053504n = 14 10^n = 276447232 n! = 1278945280

Page 109: An Introduction to Software Development Using JAVA Java

2-109

Arithmetic (cont’d)• Compound assignment

operators:

a = a + b; a += b;

a = a - b; a -= b;

a = a * b; a *= b;

a = a / b; a /= b;

a = a % b; a %= b;

• Increment and decrement operators:

a = a + 1; a++;

a = a - 1; a--;

Do not use these in larger expressions

Page 110: An Introduction to Software Development Using JAVA Java

2-110

From Numbers to Strings• The easiest way to convert x into a string is to

concatenate x with an empty string:

String s = x + "";

• The same rules apply to System.out.print(x)

'A'

123

-1

.1

3.14

Math.PI

"A"

"123"

"-1"

"0.1"

"3.14"

"3.141592653589793"

Empty string

Page 111: An Introduction to Software Development Using JAVA Java

2-111

From Objects to Strings• The toString method is called:

public class Fraction{ private int num, denom; ... public String toString () { return num + "/" + denom; }}

Fraction f = new Fraction (2, 3);System.out. println (f) ;

Output: 2/3

f.toString() is called automatically

Page 112: An Introduction to Software Development Using JAVA Java

2-112

Review:

• What is a variable?

• What is the type of a variable that holds an object?

• What is meant by the scope of a variable?

• What is the scope of a field?

• What is the scope of a local variable?

Page 113: An Introduction to Software Development Using JAVA Java

2-113

Review (cont’d):

• Is it OK to give the same name to variables in different methods?

• Is it OK to give the same name to a field and to a local variable of the same class?

• What is the range for ints?

• When is a cast to double used?

Page 114: An Introduction to Software Development Using JAVA Java

2-114

Review (cont’d):

• Givendouble dF = 68.0;

double dC = 5 / 9 * (dF - 32);

what is the value of dC?

• When is a cast to int used?