Section A.1. Variables


[Page 543 (continued)]

A.1. Variables

Variables allow us to associate names with values. In Java you must declare a variable before you use it. To declare a variable you specify a type and a name followed by a semicolon.

type name;


You can also set the value of the variable when you declare it to the result of an expression.

type name = expression;


The type can be any of the primitive types (int, boolean, byte, char, double, float, long, short), a class name, or an interface name. The convention is to start variable names with a lowercase letter and uppercase the first letter of each additional word.

> int i; > double totalBill = 32.43 + 20 * 32.43; > String name = "Mark Guzdial"; > Picture pictureObj; > List studentList = null;



[Page 544]

Variable names can be made up of letters, digits, underscores, or currency symbols. They can start with any of these except a digit. Variables can be any word except the reserved words. The reserved words are:

abstract

assert

boolean

break

byte

case

catch

char

class

const (unused)

continue

default

do

double

else

enum

extends

false

final

finally

float

for

goto (unused)

if

implements

import

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

true

try

void

volatile

while

  


Most of the reserved words are also keywords. The only ones that are not keywords are null, true, and false. All of the Java reserved words have only lowercase letters.

We can use System.out.print or System.out.println to print the value of a variable. The second one will also force a new line after the value has printed.

> int x = 10 > System.out.println(x); 10 > String name = "Barbara Ericson"; > System.out.println(name); Barbara Ericson




Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net