SlideShare a Scribd company logo
1 of 38
Understanding Variable Scope and
Class Construction

1
Understanding Variable Scope
• Exam Objective 4.2 Given an algorithm as pseudo-code,
determine the correct scope for a variable used in the algorithm
and develop code to declare variables in any of the following
scopes: instance variable, method parameter, and local variable.

2
Variables and Initialization
Member variable A member variable of a class is created when an
instance is created, and it is destroyed when the object is destroyed.
Subject to accessibility rules and the need for a reference to the object,
member variables are accessible as long as the enclosing object exists.
Automatic variable An automatic variable of a method is created on entry
to the method and exists only during execution of the method, and
therefore it is accessible only during the execution of that method. (You’ll see
an exception to this rule when you look at inner classes, but don’t worry
about that for now.)
Class variable A class variable (also known as a static variable) is created
when the class is loaded and is destroyed when the class is unloaded.
There is only one copy of a class variable, and it exists regardless of the
number of instances of the class, even if the class is never instantiated.
Static variables are initialized at class load time
Ben Abdallah Helmi Architect en
3
J2EE
All member variables that are not explicitly assigned a value upon declaration are
automatically assigned an initial value. The initialization value for member
variables depends on the member variable’s type.
A member value may be initialized in its own declaration line:
1. class HasVariables {
2. int x = 20;
3. static int y = 30;
When this technique is used, nonstatic instance variables are initialized just before
the class constructor is executed; here x would be set to 20 just before invocation
of any HasVariables constructor.

Static variables are initialized at class load time; here y would be set to 30 when the
HasVariables class is loaded.

Ben Abdallah Helmi Architect en
4
J2EE
Automatic variables (also known as method local variables are not initialized by the system; every automatic variable must be explicitly
initialized before being used. For example, this method will not compile:

1. public int wrong() {

2. int i;

3. return i+5;

4. }
The compiler error at line 3 is, “Variable i may not have been initialized.” This error often appears when initialization of an automatic variable
occurs at a lower level of curly braces than the use of that variable. For example, the following method returns the fourth root of a
positive number:
1. public double fourthRoot(double d) { 2. double result;
3. if (d >= 0) {
4. result = Math.sqrt(Math.sqrt(d));
5. } 6. return result; 7. }
Here the result is initialized on line 4, but the initialization takes place within the curly braces of lines 3 and 5. The compiler will flag line 6,
complaining that “Variable result may not have been initialized.” A common solution is to initialize result to some reasonable default as
soon as it is declared:
1. public double fourthRoot(double d) {

2. double result = 0.0; // Initialize
3. if (d >= 0) {
4. result = Math.sqrt(Math.sqrt(d));
5. } 6. return result; 7. }

Ben Abdallah Helmi Architect en
5
J2EE
5. Consider the following line of code:
int[] x = new int[25];
After execution, which statements are true? (Choose all that
apply.)
A. x[24] is 0
B. x[24] is undefined
C. x[25] is 0
D. x[0] is null
E. x.length is 25
Ben Abdallah Helmi Architect en
6
J2EE
5. A, E. The array has 25 elements, indexed from 0
through 24. All elements are initialized to 0.

Ben Abdallah Helmi Architect en
7
J2EE
Argument Passing: By Reference or by
Value
1. public void bumper(int bumpMe) {
2. bumpMe += 15;
3. }
Line 2 modifies a copy of the parameter passed by the
caller. For example
1. int xx = 12345;
2. bumper(xx);
3. System.out.println(“Now xx is “ + xx);
line 3 will report that xx is still 12345.
Ben Abdallah Helmi Architect en
8
J2EE
When Java code appears to store objects in variables or pass
objects into method calls, the object references are stored or
passed.

1. Button btn;
2. btn = new Button(“Pink“);
3. replacer(btn);
4. System.out.println(btn.getLabel());
5.
6. public void replacer(Button replaceMe) {
7. replaceMe = new Button(“Blue“);
8. }
Line 2 constructs a button and stores a reference to that button in
btn. In line 3, a copy of the reference is passed into the replacer()
method.
the string printed out is “Pink”.
Ben Abdallah Helmi Architect en
9
J2EE
1. Button btn;
2. btn = new Button(“Pink“);
3. changer(btn);
4. System.out.println(btn.getLabel());
5.
6. public void changer(Button changeMe) {
7. changeMe.setLabel(“Blue“);
8. }
the value printed out by line 4 is “Blue”.
Ben Abdallah Helmi Architect en
10
J2EE
Arrays are objects, meaning that programs deal with
references to arrays, not with arrays themselves. What
gets passed into a method is a copy of a reference to an
array. It is therefore possible for a called method to
modify the contents of a caller’s array.

Ben Abdallah Helmi Architect en
11
J2EE
6.Consider the following application:
class Q6 {
public static void main(String args[]) {
Holder h = new Holder();
h.held = 100;
h.bump(h);
System.out.println(h.held);
}
}
class Holder {
public int held;
public void bump(Holder theHolder) {
theHolder.held++; }
}
}
What value is printed out at line 6?
A. 0
B. 1
C. 100
D. 101

Ben Abdallah Helmi Architect en
12
J2EE
6. D. A holder is constructed on line 3. A reference to
that holder is passed into method bump() on line 5.
Within the method call, the holder’s held variable is
bumped from 100 to 101.

Ben Abdallah Helmi Architect en
13
J2EE
7. Consider the following application:
1. class Q7 {
2. public static void main(String args[]) {
3. double d = 12.3;
4. Decrementer dec = new Decrementer();
5. dec.decrement(d);
6. System.out.println(d);
7. }
8. }
9.
10. class Decrementer {
11. public void decrement(double decMe) {
12. decMe = decMe - 1.0;

13. }
14. }
Review Questions 31
What value is printed out at line 6?
A. 0.0
B. 1.0

C. 12.3
D. 11.3

Ben Abdallah Helmi Architect en
14
J2EE
7. C. The decrement() method is passed a copy of the
argument d; the copy gets decremented, but the
original is untouched.

Ben Abdallah Helmi Architect en
15
J2EE
20. Which of the following are true? (Choose all that
apply.)
A. Primitives are passed by reference.
B. Primitives are passed by value.
C. References are passed by reference.
D. References are passed by value.

Ben Abdallah Helmi Architect en
16
J2EE
20. B, D. In Java, all arguments are passed by value.

Ben Abdallah Helmi Architect en
17
J2EE
18
Constructing Methods
• Exam Objective 4.4 Given an algorithm with multiple inputs
and an output, develop method code that implements the
algorithm using method parameters, a return type, and the
return statement, and recognize the effects when object
references and primitives are passed into methods that
modify them.

19
• The SCJA exam will likely have a question asking the
difference between passing variables by reference and
value. The question will not directly ask you the difference.
• It will present some code and ask for the output. In the group
of answers to select from, there will be an answer that will be
correct if you assume the arguments are passed by value,
and another answer that will be correct if the arguments
were passed by reference.
• It is easy to get this type of question incorrect if passing
variables by reference and value are poorly understood.
20
Declaring a Return Type
• A return statement must be the keyword return followed
by a variable or a literal of the declared return type. Once
the return statement is executed, the method is finished.

21
Two-Minute Drill

• A variable’s scope defines what parts of the code have
access to that variable.
• An instance variable is declared in the class, not inside of
any method. It is in scope for the entire method and remains
in memory for as long as the instance of the class it was
declared in remains in memory.
• Method parameters are declared in the method declaration;
they are in scope for the entire method.
• Local variables may be declared anywhere in code. They
remain in scope as long as the execution of code does not
leave the block they were declared in.
22
• Code that invokes a method may pass arguments to it for
input.
• Methods receive arguments as method parameters.
• Primitives are passed by value.
• Objects are passed by reference.
• Methods may return one variable or none at all. It can be
a primitive or an object.
• A method must declare the data type of any variable it
returns.
• If a method does not return any data, it must use void as
its return type.

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

More Related Content

What's hot

What's hot (20)

Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Java language fundamentals
Java language fundamentalsJava language fundamentals
Java language fundamentals
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Hemajava
HemajavaHemajava
Hemajava
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Control Structures
Control StructuresControl Structures
Control Structures
 

Viewers also liked

Goal Decomposition and Abductive Reasoning for Policy Analysis and Refinement
Goal Decomposition and Abductive Reasoning for Policy Analysis and RefinementGoal Decomposition and Abductive Reasoning for Policy Analysis and Refinement
Goal Decomposition and Abductive Reasoning for Policy Analysis and RefinementEmil Lupu
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityReggie Niccolo Santos
 
Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010Matthias Biehl
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityAakash Singh
 
Escape sequences
Escape sequencesEscape sequences
Escape sequencesWay2itech
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
Presentation influence texture or crystallography orientations on magnetic pr...
Presentation influence texture or crystallography orientations on magnetic pr...Presentation influence texture or crystallography orientations on magnetic pr...
Presentation influence texture or crystallography orientations on magnetic pr...aftabgardon
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Himanshu Kaushik
 
Lecture ascii and ebcdic codes
Lecture ascii and ebcdic codesLecture ascii and ebcdic codes
Lecture ascii and ebcdic codesYazdan Yousafzai
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programmingRumman Ansari
 
USB Type-C R1.1 Introduction
USB Type-C R1.1 IntroductionUSB Type-C R1.1 Introduction
USB Type-C R1.1 IntroductionTing Ou
 
What is Niemann-Pick Type C Disease?
What is Niemann-Pick Type C Disease?What is Niemann-Pick Type C Disease?
What is Niemann-Pick Type C Disease?Michael G. Stults
 

Viewers also liked (20)

Dose baixa versus dose elevada
Dose baixa versus dose elevadaDose baixa versus dose elevada
Dose baixa versus dose elevada
 
10. Function I
10. Function I10. Function I
10. Function I
 
Goal Decomposition and Abductive Reasoning for Policy Analysis and Refinement
Goal Decomposition and Abductive Reasoning for Policy Analysis and RefinementGoal Decomposition and Abductive Reasoning for Policy Analysis and Refinement
Goal Decomposition and Abductive Reasoning for Policy Analysis and Refinement
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State University
 
Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Escape sequences
Escape sequencesEscape sequences
Escape sequences
 
Storage classes
Storage classesStorage classes
Storage classes
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Presentation influence texture or crystallography orientations on magnetic pr...
Presentation influence texture or crystallography orientations on magnetic pr...Presentation influence texture or crystallography orientations on magnetic pr...
Presentation influence texture or crystallography orientations on magnetic pr...
 
Storage classes
Storage classesStorage classes
Storage classes
 
C pointers
C pointersC pointers
C pointers
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
 
Lecture ascii and ebcdic codes
Lecture ascii and ebcdic codesLecture ascii and ebcdic codes
Lecture ascii and ebcdic codes
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
 
Static variable
Static variableStatic variable
Static variable
 
USB Type-C R1.1 Introduction
USB Type-C R1.1 IntroductionUSB Type-C R1.1 Introduction
USB Type-C R1.1 Introduction
 
What is Niemann-Pick Type C Disease?
What is Niemann-Pick Type C Disease?What is Niemann-Pick Type C Disease?
What is Niemann-Pick Type C Disease?
 

Similar to Chapter 5:Understanding Variable Scope and Class Construction

CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxNadeemEzat
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asmaAbdullahJana
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Ali Raza Zaidi
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 

Similar to Chapter 5:Understanding Variable Scope and Class Construction (20)

CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Ch07
Ch07Ch07
Ch07
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
 
Java class
Java classJava class
Java class
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
17515
1751517515
17515
 
Clean code
Clean codeClean code
Clean code
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 

More from It Academy

Chapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesChapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesIt Academy
 
Chapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesChapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesIt Academy
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesIt Academy
 
Chapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLChapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLIt Academy
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismIt Academy
 
Chapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsChapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsIt Academy
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)It Academy
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)It Academy
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)It Academy
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)It Academy
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)It Academy
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)It Academy
 
chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)It Academy
 
chp 3 : Modifiers (scjp/ocjp)
chp 3 : Modifiers (scjp/ocjp)chp 3 : Modifiers (scjp/ocjp)
chp 3 : Modifiers (scjp/ocjp)It Academy
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 

More from It Academy (20)

Chapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesChapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side Technologies
 
Chapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration TechnologiesChapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 10:Understanding Java Related Platforms and Integration Technologies
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side Technologies
 
Chapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UMLChapter 9:Representing Object-Oriented Concepts with UML
Chapter 9:Representing Object-Oriented Concepts with UML
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
Chapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their RelationshipsChapter 6:Working with Classes and Their Relationships
Chapter 6:Working with Classes and Their Relationships
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)chap 6 : Objects and classes (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
 
chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)
 
chp 3 : Modifiers (scjp/ocjp)
chp 3 : Modifiers (scjp/ocjp)chp 3 : Modifiers (scjp/ocjp)
chp 3 : Modifiers (scjp/ocjp)
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Chapter 5:Understanding Variable Scope and Class Construction

  • 1. Understanding Variable Scope and Class Construction 1
  • 2. Understanding Variable Scope • Exam Objective 4.2 Given an algorithm as pseudo-code, determine the correct scope for a variable used in the algorithm and develop code to declare variables in any of the following scopes: instance variable, method parameter, and local variable. 2
  • 3. Variables and Initialization Member variable A member variable of a class is created when an instance is created, and it is destroyed when the object is destroyed. Subject to accessibility rules and the need for a reference to the object, member variables are accessible as long as the enclosing object exists. Automatic variable An automatic variable of a method is created on entry to the method and exists only during execution of the method, and therefore it is accessible only during the execution of that method. (You’ll see an exception to this rule when you look at inner classes, but don’t worry about that for now.) Class variable A class variable (also known as a static variable) is created when the class is loaded and is destroyed when the class is unloaded. There is only one copy of a class variable, and it exists regardless of the number of instances of the class, even if the class is never instantiated. Static variables are initialized at class load time Ben Abdallah Helmi Architect en 3 J2EE
  • 4. All member variables that are not explicitly assigned a value upon declaration are automatically assigned an initial value. The initialization value for member variables depends on the member variable’s type. A member value may be initialized in its own declaration line: 1. class HasVariables { 2. int x = 20; 3. static int y = 30; When this technique is used, nonstatic instance variables are initialized just before the class constructor is executed; here x would be set to 20 just before invocation of any HasVariables constructor. Static variables are initialized at class load time; here y would be set to 30 when the HasVariables class is loaded. Ben Abdallah Helmi Architect en 4 J2EE
  • 5. Automatic variables (also known as method local variables are not initialized by the system; every automatic variable must be explicitly initialized before being used. For example, this method will not compile: 1. public int wrong() { 2. int i; 3. return i+5; 4. } The compiler error at line 3 is, “Variable i may not have been initialized.” This error often appears when initialization of an automatic variable occurs at a lower level of curly braces than the use of that variable. For example, the following method returns the fourth root of a positive number: 1. public double fourthRoot(double d) { 2. double result; 3. if (d >= 0) { 4. result = Math.sqrt(Math.sqrt(d)); 5. } 6. return result; 7. } Here the result is initialized on line 4, but the initialization takes place within the curly braces of lines 3 and 5. The compiler will flag line 6, complaining that “Variable result may not have been initialized.” A common solution is to initialize result to some reasonable default as soon as it is declared: 1. public double fourthRoot(double d) { 2. double result = 0.0; // Initialize 3. if (d >= 0) { 4. result = Math.sqrt(Math.sqrt(d)); 5. } 6. return result; 7. } Ben Abdallah Helmi Architect en 5 J2EE
  • 6. 5. Consider the following line of code: int[] x = new int[25]; After execution, which statements are true? (Choose all that apply.) A. x[24] is 0 B. x[24] is undefined C. x[25] is 0 D. x[0] is null E. x.length is 25 Ben Abdallah Helmi Architect en 6 J2EE
  • 7. 5. A, E. The array has 25 elements, indexed from 0 through 24. All elements are initialized to 0. Ben Abdallah Helmi Architect en 7 J2EE
  • 8. Argument Passing: By Reference or by Value 1. public void bumper(int bumpMe) { 2. bumpMe += 15; 3. } Line 2 modifies a copy of the parameter passed by the caller. For example 1. int xx = 12345; 2. bumper(xx); 3. System.out.println(“Now xx is “ + xx); line 3 will report that xx is still 12345. Ben Abdallah Helmi Architect en 8 J2EE
  • 9. When Java code appears to store objects in variables or pass objects into method calls, the object references are stored or passed. 1. Button btn; 2. btn = new Button(“Pink“); 3. replacer(btn); 4. System.out.println(btn.getLabel()); 5. 6. public void replacer(Button replaceMe) { 7. replaceMe = new Button(“Blue“); 8. } Line 2 constructs a button and stores a reference to that button in btn. In line 3, a copy of the reference is passed into the replacer() method. the string printed out is “Pink”. Ben Abdallah Helmi Architect en 9 J2EE
  • 10. 1. Button btn; 2. btn = new Button(“Pink“); 3. changer(btn); 4. System.out.println(btn.getLabel()); 5. 6. public void changer(Button changeMe) { 7. changeMe.setLabel(“Blue“); 8. } the value printed out by line 4 is “Blue”. Ben Abdallah Helmi Architect en 10 J2EE
  • 11. Arrays are objects, meaning that programs deal with references to arrays, not with arrays themselves. What gets passed into a method is a copy of a reference to an array. It is therefore possible for a called method to modify the contents of a caller’s array. Ben Abdallah Helmi Architect en 11 J2EE
  • 12. 6.Consider the following application: class Q6 { public static void main(String args[]) { Holder h = new Holder(); h.held = 100; h.bump(h); System.out.println(h.held); } } class Holder { public int held; public void bump(Holder theHolder) { theHolder.held++; } } } What value is printed out at line 6? A. 0 B. 1 C. 100 D. 101 Ben Abdallah Helmi Architect en 12 J2EE
  • 13. 6. D. A holder is constructed on line 3. A reference to that holder is passed into method bump() on line 5. Within the method call, the holder’s held variable is bumped from 100 to 101. Ben Abdallah Helmi Architect en 13 J2EE
  • 14. 7. Consider the following application: 1. class Q7 { 2. public static void main(String args[]) { 3. double d = 12.3; 4. Decrementer dec = new Decrementer(); 5. dec.decrement(d); 6. System.out.println(d); 7. } 8. } 9. 10. class Decrementer { 11. public void decrement(double decMe) { 12. decMe = decMe - 1.0; 13. } 14. } Review Questions 31 What value is printed out at line 6? A. 0.0 B. 1.0 C. 12.3 D. 11.3 Ben Abdallah Helmi Architect en 14 J2EE
  • 15. 7. C. The decrement() method is passed a copy of the argument d; the copy gets decremented, but the original is untouched. Ben Abdallah Helmi Architect en 15 J2EE
  • 16. 20. Which of the following are true? (Choose all that apply.) A. Primitives are passed by reference. B. Primitives are passed by value. C. References are passed by reference. D. References are passed by value. Ben Abdallah Helmi Architect en 16 J2EE
  • 17. 20. B, D. In Java, all arguments are passed by value. Ben Abdallah Helmi Architect en 17 J2EE
  • 18. 18
  • 19. Constructing Methods • Exam Objective 4.4 Given an algorithm with multiple inputs and an output, develop method code that implements the algorithm using method parameters, a return type, and the return statement, and recognize the effects when object references and primitives are passed into methods that modify them. 19
  • 20. • The SCJA exam will likely have a question asking the difference between passing variables by reference and value. The question will not directly ask you the difference. • It will present some code and ask for the output. In the group of answers to select from, there will be an answer that will be correct if you assume the arguments are passed by value, and another answer that will be correct if the arguments were passed by reference. • It is easy to get this type of question incorrect if passing variables by reference and value are poorly understood. 20
  • 21. Declaring a Return Type • A return statement must be the keyword return followed by a variable or a literal of the declared return type. Once the return statement is executed, the method is finished. 21
  • 22. Two-Minute Drill • A variable’s scope defines what parts of the code have access to that variable. • An instance variable is declared in the class, not inside of any method. It is in scope for the entire method and remains in memory for as long as the instance of the class it was declared in remains in memory. • Method parameters are declared in the method declaration; they are in scope for the entire method. • Local variables may be declared anywhere in code. They remain in scope as long as the execution of code does not leave the block they were declared in. 22
  • 23. • Code that invokes a method may pass arguments to it for input. • Methods receive arguments as method parameters. • Primitives are passed by value. • Objects are passed by reference. • Methods may return one variable or none at all. It can be a primitive or an object. • A method must declare the data type of any variable it returns. • If a method does not return any data, it must use void as its return type. 23
  • 24. 24
  • 25. 25
  • 26. 26
  • 27. 27
  • 28. 28
  • 29. 29
  • 30. 30
  • 31. 31
  • 32. 32
  • 33. 33
  • 34. 34
  • 35. 35
  • 36. 36
  • 37. 37
  • 38. 38