AMath 05 Chapter 1
AMath 05 Chapter 1
CASTING
ACCESS MODIFIERS
PREPARED BY:
DANILYN A. FLORES
SCOPE OF VARIABLES
In addition to a variable’s data type and name, a variable
has scope.
Scope
determines where in the program the variable is accessible.
also determines the lifetime of a variable
Lifetime
how long the variable can exist in memory
The outer pair of curly braces is called the outer block, and the
inner pair of curly braces is called the inner block.
3
If variables are declared in the outer block, they are visible (or usable) by the
program lines inside the inner blocks. However, if variables are declared in the
inner block, they are not visible (or usable) in the outer blocks.
A variable’s scope is inside the block where it is declared, starting from the
point where it is declared, and in the inner blocks.
2 Types of Casting:
Implicit – data is converted from a smaller type to a larger type
Explicit – data is converted from a larger type to a smaller type
explicit cast is not always done because of possible loss of
precision
8
double x = 10.2;
int y = 2;
int result = (int)(x/y);
10
11
Side Effect
Modification in a variable’s value outside it’s scope that could affect other
variables
14
15
For example:
public class StudentRecord {
String name;
String getName() {
return name; }
}
16
2. public
Class members are accessible to anyone, both inside and outside the
class. Any object that interacts with the class can have access to the
public members of the class.
17
18
3. protected
Only the methods of the class and the subclasses of that class have
access to the class members.
19
For example:
public class StudentRecord {
protected String name;
protected String getName() {
return name; }
}
20
4. private
Class members are accessible only by the class they are defined in.
21
For example:
public class StudentRecord {
private String name;
private String getName() {
return name; }
}
22
1. Determine and label the scope of each variable in the given code.
25
[1] Amilbahar, S.J., Flores, D.A. (2010). Computer Programming II. Unpublished Workbook, University of Southern Mindanao,
Kabacan, Cotabato.
[2] Burd, B. (2017). Beginning Programming with Java For Dummies (5th Ed). New Jersey: John Wiley and Sons, Inc.
[3] Flask, R. (ND). Java for Beginners 2nd Edition [PDF File]. Retrieved from
http://staff.um.edu.mt/__data/assets/pdf_file/0010/57169/jn.pdf
[4] Mayfield, B. (2016). From Problem Analysis to Program Design Lab Manual (3rd ed.). Philippines: Cengage Learning Asia Pte
Ltd.
[5] https://funprogramming.org/50-What-are-global-and-local-variables.html
[6] https://www.geeksforgeeks.org/type-conversion-in-c/
[7] https://www.w3schools.com/java/java_wrapper_classes.asp
[8] https://www.w3schools.com/java/java_data_types.asp