CS-1201
OBJECT ORIENTED
PROGRAMMING
DIVING IN (ADVANCING O N
BASICS)
EXAMPLE
/ Compute distance light travels using long variables.
class Light {
public static void main(String
args[]) { int lightspeed;
long days;
long
seconds;
long // approximate speed of light in miles
distance; per second
lightspeed // specify number of days here
= // convert to seconds
186000; // compute distance
days =
1000;
seconds = days * 24 * 60 * //
160704000000
Output
60; distance = lightspeed 001000 days light will travel about
In
* seconds;
EXAMPLE
// char variables behave like
integers.
class CharDemo2 {
public static void main(String
args[]) { char ch1;
ch1 = 'X';
System.out.println("ch1 contains " +
ch1); ch1++; / increment ch1
Output
System.out.println("ch1 is now " + ch1 contains
ch1); X ch1 is
now Y
}
THE SCOPE OF VARIABLES
◾ Objects declared in the outer scope will be visible to code
within the inner scope.
◾ However, the reverse is
not true.
◾ Objects declared within the inner scope will not be
visible outside it.
EXAMPLE: SCOPE OF VARIABLES
/ Demonstrate block scope.
class Scope {
public static void main(String args[])
{
int x; // known to all code
within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; / known only to this
block
/ x and y both known here.
System.out.println("x and y: " +
x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known
here
THE SCOPE OF VARIABLES
◾ Variables are created when their scope is entered, and
destroyed when their scope is left.
◾ Lifetime of a variable is confined to its scope.
◾ Although blocks can be nested, we cannot declare a
variable to have the same name as one in an outer
scope.
EXAMPLE
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{// creates a new scope
int bar = 2; //Compile time error, bar already defined!
}
} }