SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
Mahmoud Ouf
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
Mahmoud Ouf
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
SzeChingChen
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
Jomel Penalba
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
Andy Juan Sarango Veliz
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
Ahmad Idrees
 
Java language fundamentals
Java language fundamentalsJava language fundamentals
Java language fundamentals
Kapish Joshi
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
Hemajava
HemajavaHemajava
Hemajava
SangeethaSasi1
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
Danairat Thanabodithammachari
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
mcollison
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
Shohan Ahmed
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 

Viewers also liked (20)

Dose baixa versus dose elevada
Dose baixa versus dose elevadaDose baixa versus dose elevada
Dose baixa versus dose elevada
MediTec Group AB FerroCare Division
 
10. Function I
10. Function I10. Function I
10. Function I
Joseph Murphy
 
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
Emil Lupu
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State University
Reggie Niccolo Santos
 
Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010
Matthias Biehl
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
Aakash Singh
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
Tushar Shende
 
Escape sequences
Escape sequencesEscape sequences
Escape sequences
Way2itech
 
Storage classes
Storage classesStorage classes
Storage classes
Leela Koneru
 
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
Anurag University Hyderabad
 
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
 
Storage classes
Storage classesStorage classes
Storage classes
Puneet Rajput
 
C pointers
C pointersC pointers
C pointers
Aravind Mohan
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
Nitesh Bichwani
 
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 codes
Yazdan Yousafzai
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
Static variable
Static variableStatic variable
Static variable
Himanshu Shekhar
 
USB Type-C R1.1 Introduction
USB Type-C R1.1 IntroductionUSB Type-C R1.1 Introduction
USB Type-C R1.1 Introduction
Ting 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
 
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
Emil Lupu
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State University
Reggie Niccolo Santos
 
Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010Model Evolution Workshop at MODELS 2010
Model Evolution Workshop at MODELS 2010
Matthias Biehl
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
Aakash Singh
 
Escape sequences
Escape sequencesEscape sequences
Escape sequences
Way2itech
 
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 codes
Yazdan Yousafzai
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
USB Type-C R1.1 Introduction
USB Type-C R1.1 IntroductionUSB Type-C R1.1 Introduction
USB Type-C R1.1 Introduction
Ting 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
 
Ad

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
BienvenidoVelezUPR
 
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
Hamad Odhabi
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince 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 II
Eduardo Bergavera
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Unit2_2.pptx Chapter 2 Introduction to C#
Unit2_2.pptx Chapter 2 Introduction to C#Unit2_2.pptx Chapter 2 Introduction to C#
Unit2_2.pptx Chapter 2 Introduction to C#
Priyanka Jadhav
 
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
Radhika Talaviya
 
Ch07
Ch07Ch07
Ch07
Arriz San Juan
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
Ferdin Joe John Joseph PhD
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
NadeemEzat
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Java class
Java classJava class
Java class
Arati Gadgil
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
 
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
Danairat Thanabodithammachari
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
AbdullahJana
 
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
Ali Raza Zaidi
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
Mukesh Tekwani
 
IntroductionJava Programming - Math Class
IntroductionJava Programming - Math ClassIntroductionJava Programming - Math Class
IntroductionJava Programming - Math Class
sandhyakiran10
 
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
Hamad Odhabi
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince 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 II
Eduardo Bergavera
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Unit2_2.pptx Chapter 2 Introduction to C#
Unit2_2.pptx Chapter 2 Introduction to C#Unit2_2.pptx Chapter 2 Introduction to C#
Unit2_2.pptx Chapter 2 Introduction to C#
Priyanka Jadhav
 
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
Radhika Talaviya
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
NadeemEzat
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
AbdullahJana
 
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
Ali Raza Zaidi
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
IntroductionJava Programming - Math Class
IntroductionJava Programming - Math ClassIntroductionJava Programming - Math Class
IntroductionJava Programming - Math Class
sandhyakiran10
 
Ad

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
It 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 Technologies
It Academy
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side Technologies
It 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 UML
It Academy
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
It 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 Relationships
It 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 Strings
It Academy
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
It 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 Strings
It Academy
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
It Academy
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
It 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
 
Chapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side TechnologiesChapter 12:Understanding Server-Side Technologies
Chapter 12:Understanding Server-Side Technologies
It 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 Technologies
It Academy
 
Chapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side TechnologiesChapter 11:Understanding Client-Side Technologies
Chapter 11:Understanding Client-Side Technologies
It 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 UML
It Academy
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
It 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 Relationships
It 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 Strings
It 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 Strings
It Academy
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
It 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
 

Recently uploaded (20)

Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 

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
  翻译: