18-variables

18-variables - Mehran Sahami CS 106A Handout#18 Variables...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Mehran Sahami Handout #18 CS 106A October 12, 2007 Variables, variables, everywhere… Based on a handout by Patrick Young. Local Variables Local variables are created local to the method (or the block—see “Block Scope” section below) in which they are defined. They are destroyed when execution of the method has been completed. Local variables can only be accessed from within the method in which they are declared. Because of their transient nature, local variables cannot store persistent information about an object between method calls. Local Variables Example Consider, for example, the following snippet of code. class AnExample extends ConsoleProgram { public void methodOne { int a = readInt("Enter a: "); println("a = " + a); } public void methodTwo { int b = a; // BUG!: cannot refer to variable a in methodOne println("b = " + b); } } The variables a and b are local variables declared within different methods in the class AnExample . Because these variables are local variables, a can only be referred to within methodOne and variable b can only be accessed within methodTwo . Our attempt to initialize b using the value of a is illegal, as code in methodTwo cannot access local variables from methodOne or any other method. Because local variable values do not persist after their containing method has completed, the variable a will be destroyed when methodOne has completed execution. The next time methodOne is called, a new variable a will be created. Block Scope While we typically think of local variables as local to a particular method, in Java local variables are actually local to a block of code. While a method defines a block of code (since the opening and closing braces of the method define a block), for and while loops, if -statements, and other constructs are also considered blocks of code. If we declare a local variable inside one of these constructs, the local variable will be created when it is declared in the block and destroyed when the block ends execution.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
– 2 – Consider the following example: class AnExample extends ConsoleProgram { public void methodThree { int a = 4; for (int i = 0; i < 5; i++) {
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 5

18-variables - Mehran Sahami CS 106A Handout#18 Variables...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online