SCJP note Part I (of IV)


Presentation Description

My study note of Sun Certificate of Java Programmer


By: bevin (112 month(s) ago)

That is so nice of you to share all the notes you prepared. Good luck with your future endeavors...

By: maggie.zhou (116 month(s) ago)

You all are welcome.

By: beefchongfan (116 month(s) ago)

Thank you so much Ms. Maggie! Hope you'll pass the J2EE Certification! :-)

By: mikeyong (116 month(s) ago)

Can i dwownload it note as power point?

Presentation Transcript

SCJP Exam Notes(Part I) : 

SCJP Exam Notes(Part I) By Maggie Zhou June, 2008

SCJP Exam facts : 

2 SCJP Exam facts Consists of 72 questions The candidate has 210 minutes(3.5h) to answer (~3 mins/q) At least 47 questions are needed to be correct to pass (around 65%) Must buy a voucher from Sun and book the test at least a week in advance. The test consists of multiple choice and drag-and-drop questions, the latter comprising 20-25% of the questions

Reserved words (1) : 

3 Reserved words (1) First of all: be careful with the Capital or low case; Be careful with the API’s name, such as: Serializable, Runnable, Externalizable,Cloneable All the reserved key words are: (all low case) abstract boolean break byte case catch char class else extends const continue default do double final finally float for goto if implements import int instanceof long interface native new package private protected public return short static strictfp super switch synchronized this throw throws void transient try volatile while assert enum

Reserved words (2) : 

4 Reserved words (2) List some infrequently used: Strictfp: Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way. instanceof: only for class transient : only for variable throw /throws: method method name + throws + exception name; Inside method, use throw new exception(); to throw exception volatile: can be applied only to instance variables native: indicates that a method is implemented in platform-dependent code, often in C. goto/const: keyword isn't used in Java at the moment.

Transient : 

5 Transient Only for instance variable Related to the Serialization transient instance variable: the JVM ignore this variable when you attempt to serialize the object containing it.

Volatile : 

6 Volatile Only for instance variable volatile modifier: the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with the master copy in memory.

Language Fundamentals : 

7 Language Fundamentals "big farms need red tractors". The escape sequences are as follows: '\b' (backspace), '\f' (formfeed), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\\' (backslash), '\"' (double quote), '\'' (single quote).

Source file declaration rules : 

Source file declaration rules

Source file declaration rules : 

9 Source file declaration rules Only one public class, or no public class Can have multiple non-public class File name = public class name Sequence: package xxxx; import xxxx; public class xxxx { }; No requirements for non-public classes

Classes : 


Basic concepts : 

11 Basic concepts Every class in Java is a subclass of class Object, (except of course class Object itself). Classes always have an equals, clone, notify, wait, and other methods, available to use. specialized classes can actually help reduce bugs The top-level class only can be marked as public and default

Class declaration & modifiers : 

Class declaration & modifiers

Modifiers : 

13 Modifiers Access modifiers public (class can use) protected private The fourth access control level: default: package-level access (class can use) Non-access modifiers strictfp is a keyword and can be used to modify a class or a method final abstract

Class Access (1) : 

14 Class Access (1) default class (without add any modifier) Only be visible within the same package. Import won’t work neither; public class gives all classes from all packages access to the public class. still need to import the public class if in different packages.

Class Access (2) : 

15 Class Access (2) final class class can't be subclassed (no inherit from) abstract class class can never be instantiated; if even a single method is abstract, the whole class must be declared abstract; The abstract method: end in a semicolon rather than curly braces. public abstract void xxxx (); Can put nonabstract methods in an abstract class; Can't mark a class as both abstract and final

Extends from abstract class : 

16 Extends from abstract class If not in the same package, must import it. Use class xxxx extends xxxx { } Have to implement all the abstract methods; (exactly same, different argument doesn’t count == OVERLOAD) If overriding the non-abstract method, can use the old method by super.xxxx(); For the abstract method, can not reduce the visibility. (Wrong: public  private, Right: default  protected )

Interface : 

Interface 1.2 Develop code that declares an interface…

Basic concepts : 

18 Basic concepts Interface class declare with the keyword interface As unique abstract class: only has abstract method. can extends one or more other interfaces. (Only interface) interface xxxable extends yyyable, zzzable cannot implement any method Interface types can be used polymorphically public abstract interface xxable { } == public interface xxable { } Method All interface methods are implicitly public and abstract (no need to type public or abstract) methods cannot be marked static, final, strictfp, or native. public abstract void xxxx(); == void xxxx(); Instance variable All variables must be public, static, and final (only constants) interface constants == read-only value

Implementing an Interface : 

19 Implementing an Interface A class can implement more than one interface Provide legal implementations for every method defined in the interface. Can never guaranteed a good implementation An implementation class can itself be abstract Could choose to implement any, all, or none of the methods This class must be abstract if it did not implement all the methods a legal implementation class, must do: Provide concrete (nonabstract) implementations for all methods from the declared interface. Method must be public due to the method is implied public in interface Follow all the rules for legal overrides. Declare no checked exceptions on implementation methods other than those declared by the interface method Maintain the signature of the interface method, and maintain the same return type (or a subtype).

Class member declaration & modifiers : 

Class member declaration & modifiers

Class Members Modifiers(1) basic concepts : 

21 Class Members Modifiers(1) basic concepts Access Member Modifiers: (Method and variable members have same four access control levels) public protected default (no type) private Class access level >> member access level Any local variable declared with an access modifier will not compile. Only one modifier that can ever be applied to local variables—final. Access vs. Inherit A method in one class tries to access a method or a variable of another class, using the dot operator (.). A subclass inherits a member, the subclass has the member:; == xxx();

Class Members Modifiers(2) : 

22 Class Members Modifiers(2) Public Access: all other classes, regardless of the package they belong to, can access the member (assuming the class itself is visible). Inherit: a method invoked (or a variable accessed) without the dot operator (.), it means the method or variable belongs to the class where you see that code. It also means that the method or variable is implicitly being accessed using the this reference. Private Access: can't be accessed out of the class. Inherit: a subclass can't inherit private member.

Class Members Modifiers(3) : 

23 Class Members Modifiers(3) Protected vs. Default almost identical, but with one critical difference -- subclass. default member may be accessed only if the class accessing the member belongs to the same package (package) protected member can be accessed (through inheritance) by a subclass & the subclass is in a different package (package + kids ). Special case: subclass+ outside of package can't use a superclass reference to access a protected member: use variable directly, not xxx.variable; The protected member can be accessed only through inheritance. Only the subclass and its sub-subclasses can access it.

Class Members Modifiers(4) : 

24 Class Members Modifiers(4) Nonaccess Member Modifiers final abstract synchronized native, strictfp static.

Class Members Modifiers(5) : 

25 Class Members Modifiers(5) final Methods: can't-be-overridden prevents a method from being overridden in a subclass final Arguments Void xxxMethod (Final int input1) {} can't be modified within the class a final argument must keep the same value that the parameter had when it was passed into the method. Abstract Methods has no method body. Only have xxxx (); an abstract class can have no abstract method an abstract method require the class must be abstract The first concrete subclass of an abstract class must implement all abstract methods of the superclass. Implementation ≠ overloaded Static Method Can not be override

Class Members Modifiers(6) : 

26 Class Members Modifiers(6) Synchronized Methods indicates that a method can be accessed by only one thread at a time Synchronized can be applied only to method Typical synchronized declaration: public synchronized Record xxxxx (int id) { } Native Methods indicates that a method is implemented in platform-dependent code, often in C. Native can be applied only to method Typical native declaration: (there’s no body) public native xxxx (); Strictfp Methods strictfp forces floating points (and any floating-point operations) to adhere to the IEEE 754 standard. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on.

Methods with Variable Argument Lists(var-args) : 

27 Methods with Variable Argument Lists(var-args) Basic concepts: Arguments: The things you specify between the parentheses when you're invoking a method. Parameters: The things in the method's signature that indicate what the method must receive when it's invoked. Declaration rules for var-args: void doStuff2(char c, int... x) { } Var-arg type: must specify the type of the argument(s) this parameter of your method can receive. Basic syntax: To declare a method using a var-arg parameter, you follow the type with an ellipsis (…), a space, and then the name of the array that will hold the parameters received. Other parameters: It's legal to have other parameters in a method that uses a var-arg. Var-args limits: The var-arg must be the last parameter in the method's signature, and you can have only one var-arg in a method.

Constructor Declarations : 

28 Constructor Declarations Every class has a constructor constructors look an awful lot like methods constructor can't have a return type. must have the same name as the class can't be marked static, final or abstract Can be marked as public, private, protected If didn’t define the constructor, complier will create one for you. Once defined any constructor, compiler won’t do that automatically.

Variable Declarations(1) Primitives & Reference variables : 

29 Variable Declarations(1) Primitives & Reference variables Primitives: can be one of eight types: char, boolean, byte, short, int, long, double, or float. Once has been declared, primitive type can never change, ( value can change). Reference variables is used to refer to (or access) an object. is declared to be of a specific type and that type can never be changed. can be used to refer to any object of the declared type, or of a subtype of the declared type (a compatible type). a reference variable refer to a subtype is about polymorphism.

Variable Declarations(2) Declaring Primitives & Reference Variables : 

30 Variable Declarations(2) Declaring Primitives & Reference Variables Primitive variables & Reference Variables can be declared as: class variables (static), instance variables, method parameters, local variables. can declare in a single line int x, y, z;

Variable Declarations(3) Primitive Types & Ranges : 

31 Variable Declarations(3) Primitive Types & Ranges boolean char byte short int long float double ture /false (virtual-machine dependent. ) 16bits 0~65535 char c = ‘c’; 8bits -128 ~ 127 16bits -32768 ~ 32767 32bits -2147483648 ~ 2147483647 64bits –xxx ~ xxx 32bits float f = 1.6f; 64bits certain number of 8-bit bytes, leftmost bit is used to represent the sign, where a 1 means negative and 0 means positive

Variable Declarations(4) Instance Variables : 

32 Variable Declarations(4) Instance Variables are defined inside the class, but outside of any method, are only initialized when the class is instantiated. are the fields that belong to each unique object. Basic concepts Can use any of the four access levels (which means they can be marked with any of the three access modifiers) Can be marked final transient Cannot be marked abstract synchronized, only for method strictfp, native, static, because then they'd become class variables.

Variable Declarations(4) Local (Automatic/Stack/Method) Variables : 

33 Variable Declarations(4) Local (Automatic/Stack/Method) Variables are variables declared within a method are destroyed when the method has completed. local variables don't get default values, So must be initialized with a value before be used. are always on the stack, not the heap (object is on the heap) local object == locally declared reference variable shadowing : Can declare a local variable with the same name as an instance variable. Use keyword this refers to the object currently running. Can be marked final Cannot be marked Access modifiers: public, private, protected, default transient, volatile, abstract, static

Final : 

34 Final Final variable is impossible to be re-initialized, once it has been initialized with an explicit value (not default value) primitives: the assigned value can't be altered reference variable: can't ever be reassigned to refer to a different object, while the data within the object can be modified. Final is applied to: Class: cannot have subclass Method: cannot be overridden Variable: cannot be reassigned value/object

Static : 

35 Static Exist independently of any instances created for the class. Same value: all instances of a given class share the same value for any given static variable. Exist before you ever make a new instance of a class Can be marked Methods Variables A class nested within another class, but not within a method Initialization blocks Enum, but not the Enum as separate class Cannot be marked Constructors (makes no sense; a constructor is used only to create instances) Classes (unless they are nested) Interfaces Method local inner classes Inner class methods and instance variables Local variables

Enums : 


Basic Concepts : 

37 Basic Concepts Restrict a variable to having one of only a few pre-defined values enum CoffeeSize { BIG, HUGE, OVERWHELMING } CoffeeSize cs = CoffeeSize. BIG; Add “;” also ok: enum CoffeeSize { BIG, HUGE, OVERWHELMING }; Not required that enum constants be in all caps, but it is better Can be declared: outside a class: only can use public or default modifier a class member But not be declared within a method Cannot use public constructor Represented as static and final == constant

Declaring Constructors, Methods, and Variables : 

38 Declaring Constructors, Methods, and Variables Can contain constructors, methods, variables, and constant class bodies. Be careful if there is method defined, you need add ; to the end of variable ++ Enum constructors Can NEVER invoke an enum constructor directly can define more than one argument to the constructor can overload the enum constructors Particular constant to override a method defined in the enum (Please see example at the end of SCJP 1.5 chapter)

++ Exam watch: : 

39 ++ Exam watch: Enum == String  compile error, they can not pass casting Switch case use Enum.Attribute  compile error, need use the Attribute only for example: not COLOR.BLUE, only use BLUE Must remember: Enum cannot define within method, you made many times mistakes about this Enum values() return the references not the values

-- 2.1 --Encapsulation : 

-- 2.1 --Encapsulation 5.1 Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

Encapsulation -Basic Concepts : 

41 Encapsulation -Basic Concepts Encapsulation helps hide implementation behind an interface (APIs). Your class be maintainability, flexibility, and extensibility Keep instance variables protected (with an access modifier, often private). Force calling code to use public accessor methods to access the instance variable. Use the JavaBeans naming convention to name methods: set<someProperty>and get<someProperty>.

-- 2.2 --Inheritance, Is-A, Has-A : 

-- 2.2 --Inheritance, Is-A, Has-A 5.5 Develop code that implements "is-a" and/or "has-a" relationships.

inheritance : 

43 inheritance Inheritance benefits: To promote code reuse To use polymorphism A class can only extends one class (only one parent class) inherit public and protected variables and methods of the superclass. To avoid "Deadly Diamond of Death,“, JAVA use interface to instead of the multiple inheritance. Underlying IS-A, polymorphism, overriding, overloading, and casting All classes (except class object), are subclasses of type object, and therefore they inherit Object's methods.

IS-A vs. HAS-A : 

44 IS-A vs. HAS-A IS-A is based on class inheritance or interface implementation. this thing is a type of that thing Keywords: extends: for class inheritance implements: for interface implementation HAS-A based on usage, rather than inheritance class A HAS-A B if code in class A has a reference to an instance of class B.

-- 2.3 --Polymorphism : 

-- 2.3 --Polymorphism 5.2 Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

Reference variable : 

46 Reference variable Polymorphism reference accesses the variable related to the type of reference variable Polymorphism means “many forms.” Reference variable it the only way to access an object A reference variable can be of only one type, and once declared, that type can never be changed But it can refer to any object of the same type or any subtype As a variable, reference can be reassigned to other objects, (unless the reference is declared final). ++ Can be declared as a class type or an interface type. As an interface type, variable can reference any object of any class that implements the interface.

Compiler vs. JMV : 

47 Compiler vs. JMV Compiler only knows about the declared reference type. JVM at runtime knows what the object really is. Polymorphic method only apply to instance methods. Variable type determines the methods that can be invoked. (method  variable type) You can always refer to an object with a more general reference variable type (a superclass or interface), but at runtime, the ONLY things that are selected based on the actual object (rather than the reference type) are instance methods. ++ Not static methods. Not variables. (Base on the reference type) Only instance methods are invoked based on the real object's type.

-- 2.4 --Overriding / Overloading : 

-- 2.4 --Overriding / Overloading 1.5 Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method. 5.4 Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

Overriding (1) : 

49 Overriding (1) overriding == re-implementing a method you inherited Inherits a method from a superclass, the subclass can override the method (unless marked as final) ++ In concrete class, force to override the abstract methods (implement it) from abstract class. an overriding method must fulfill the contract of the superclass == Guarantee the subclass be able to do everything the superclass can do. Superclass Version + additional code use the keyword super: super.overriddenMethodName(); Rules: Overriding method’s argument list == the overridden method’s. (don't match  overloaded). The return type must be the same as the original overridden method (or a subtype == covariant returns.)

Overriding (2) : 

50 Overriding (2) ++ The access level CAN’T be more restrictive than the overridden method's. (be careful with INTERFACE, its methods are all public, so you must mark method as public) The access level CAN be less restrictive than that of the overridden method. Instance methods can be overridden only if they are inherited by the subclass. A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected ( the default methods can not be see out of the package).

Overriding (3) : 

51 Overriding (3) ++ Must not throw new or broader checked exceptions. May throw fewer or narrower checked exceptions, or any unchecked exception. ++ Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. ++ If a method can't be inherited, you cannot override it. (always check class first) private methods are not inherited You cannot override a method marked final. You cannot override a method marked static.

Overloading : 

52 Overloading Polymorphism applies to overriding, not to overloading. Let you reuse the same method name in a class, but with different arguments ++ Overloaded methods MUST change the argument list. Overloaded methods CAN change the return type. ++ Overloaded methods CAN change the access modifier. ++ Overloaded methods CAN declare new or broader checked exceptions. A method can be overloaded in the same class or in a subclass. Be careful with the overridden and overloaded. They are similar but different. key is: argument list is different ++ Static method is only overloaded, it is hidden.

++ Overridden vs. Overrided : 

53 ++ Overridden vs. Overrided Real object type (not the reference variable type), determines which overridden method is used at runtime Reference variable type (not the real object type) to determine which overloaded method is invoked. the choice of which overloaded method to call is NOT dynamically decided at runtime. static methods & variables base on the reference type

-- 2.5 --Reference Variable Casting : 

-- 2.5 --Reference Variable Casting 5.2 Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

Basic concept : 

55 Basic concept Two types of reference variable casting: downcasting and upcasting. Downcasting: use generic reference variable types to refer to more specific object types make an explicit cast to do this can access the subtype's members with this new reference variable. ++ Compile but fail later by runtime Upcasting: assign a reference variable to a supertype reference variable explicitly or implicitly. This is an inherently safe operation The assignment restricts the access capabilities of the new variable.

-- 2.6 --Legal Return Types : 

-- 2.6 --Legal Return Types 1.5 Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.

Rules for returning a value : 

57 Rules for returning a value ++ Nothing can be returned from a void, but you can return nothing. You're allowed to simply say return, in any method with a void return type. you can't return nothing from a method with a non-void return type. ++ Can return null with an object reference return type ++ An array is a legal return type, both to declare and return as a value. With a primitive return type, you can return any value or variable that can be implicitly cast to the declared return type. With an object reference return type, you can return any object type that can be implicitly cast to the declared return type. an object reference return type  can return subtype an interface return type  any implementer of the interface.

Return Type Declarations : 

58 Return Type Declarations On overloaded methods can declare any return type you like cannot only change the return type, it is illegal with the method overloaded. (must change the argument list.) Overriding -- Covariant Returns Can change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (superclass) method

-- 2.7 -- Constructors and Instantiation : 

-- 2.7 -- Constructors and Instantiation 1.6 Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class. 5.4 Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

Constructors : 

60 Constructors Constructors are the code that runs whenever you use the keyword new (initialization blocks + Constructor) Every class, even an abstract class, has at least one constructor. (Interfaces do not have constructors. Interfaces are not part of an object's inheritance tree.) Two key points: Have no return type Names must exactly match the class name. All constructors are used to initialize instance variable state. A constructor will call every superclass in its object's inheritance tree. UP: calls its superclass constructor, which calls its superclass constructor, and so on all the way up to the Object constructor. DOWN: The Object constructor executes and then returns to the calling constructor, and so on back down to the actual instance being created.

Default Constructor : 

61 Default Constructor Very common (and desirable) for a class to have a no-arg constructor A default constructor will be automatically generated by the compiler. ALWAYS a no-arg constructor. Has the same access modifier as the class. Includes a super() (no-arg call the super constructor ) ++ Once create a constructor with arg, you won't have a default no-arg constructor (you need to type it in yourself) Can create own no-arg constructor. A no-arg constructor is not necessarily the default constructor

Rules for Constructors (1) : 

62 Rules for Constructors (1) ++ The first statement of every constructor must be a call to either this() or super(). Compiler will add a call to super() unless you have already put in a call to this() or super(). The only way a constructor can be invoked is from within another constructor (using super() or this()). A constructor can invoke another constructor of the same class using the keyword this(). super() If your superclass does not have a no-arg constructor, you must create a constructor and insert a call to super() with arguments matching those of the superclass constructor. this() May appear only as the first statement in a constructor. Calls to this() and super() cannot be in the same constructor.

Rules for Constructors (2) : 

63 Rules for Constructors (2) Instance members are accessible only after the super constructor runs. ++ Constructors can use any access modifier, even private. Private constructor means only code within the class itself can instantiate an object of that type. ++ Constructors are never inherited, thus they cannot be overridden. Constructors can be overloaded, The argument list determines which overloaded constructor is called. ++ Only static variables and methods can be accessed as part of the call to super() or this(). Because: static variable/blocks are execute before constructor, and belong to class Example: super (Animal.NAME) is OK, because NAME is declared as a static variable.

Overloaded Constructors : 

64 Overloaded Constructors ++ Remember: no default constructor once you create one. Offer flexible ways to instantiate objects from your class Once you call “this”, the default super() won’t be inserted. ++ All the constructor calls this() could cause the dead lock problem. It is a compiler error

-- 2.8 -- Static : 

-- 2.8 -- Static 1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Static Variables and Methods : 

66 Static Variables and Methods Use static methods to implement behaviors that are not affected by the state of any instances. Static members are tied to the class, not an instance static = class, nonstatic = instance. There is only one copy of any static member Static variable: Will be shared by all instances of that class (Only one copy) Can be accessed without having an instance of a class. Static method: Can't access a nonstatic (instance) variable, because there is no instance can't directly invoke a nonstatic method Most common mistakes is attempting to access an instance variable from the static main() method Go with reference variable

Accessing Static Methods / Variables : 

67 Accessing Static Methods / Variables Can use a static method or variable without having any instances of that class at all Do not need use the dot operator on the class name ++ Also allow use the dot operator to access static members an object reference variable to access a static member ++ Decide by reference type, not the real object type ++ Static methods can't be overridden but can be redefined redefining ≠ overriding , overridden method = hidden

++ Initialization order : 

68 ++ Initialization order Always be: Static block (static method create but not run) Then: initial blocks + constructor

-- 2.9 -- Coupling and Cohesion : 

-- 2.9 -- Coupling and Cohesion 5. 1 Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

OO Basic concepts : 

70 OO Basic concepts Do with the quality of an OO design, the goals for an application are Ease of creation Ease of maintenance Ease of enhancement good OO design calls for loose coupling and shuns tight coupling high cohesion, and shuns low cohesion.

Coupling : 

71 Coupling Coupling is the degree to which one class knows about another class. Loosely coupled: class A has about class B, is what class B has exposed through its interface Tightly coupled: class A relies on parts of class B that are not part of class B's interface REALLY BAD: class A knows non-API stuff about class B, and class B knows non-API stuff about class A Desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage.

Cohesion : 

72 Cohesion Cohesion is the degree to which a class has a single, well-focused purpose All about how a single class is designed Higher cohesiveness: The more focused a class is key benefits: much easier to maintain (less frequently changed) more reusable than other classes

-- 3.1 -- Stack and Heap : 

-- 3.1 -- Stack and Heap

Quick Review : 

74 Quick Review Instance variables and objects live on the heap. Local variables live on the stack

-- 3.2 --Literals, Assignments, and Variables : 

-- 3.2 --Literals, Assignments, and Variables 1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names. 7.6 Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=) …

Literal Values for All Primitive Types : 

76 Literal Values for All Primitive Types Integer Literals: Decimal as is octal 0 + … Hexadecimal 0X/0x + …(not case sensitive) Literals: Float: … + F/f (not case sensitive), default double Long: + L/l (not case sensitive), default int Boolean Literals: true or false Character Literals: single character in single quotes, \u + ….number Out of the range, you need cast it: 6553 Literal Values for Strings: in double quotes

Assignment Operators (1) : 

77 Assignment Operators (1) Variables are just bit holders Reference variable: A variable referring to an object Primitive Assignments literal integer is always implicitly an int For other primitive: compiler puts in the cast ++ Primitive Operators: always implicit an int the result of an expression involving anything int-sized or smaller is always an int ++ byte x = (byte) 1 + 2; ++ x += 7;  still be byte, needn’t cast Cast: implicit  small to int, explicit  large to small Explicit: The large-value-into-small-container Implicit: The small-value-into-large-container

Assignment Operators (2) : 

78 Assignment Operators (2) Assigning Floating-Point Numbers every floating-point literal is implicitly a double (64 bits) cast the value or ….+F/f Assigning a Literal That Is Too Large for the Variable cut off the leftmost and get the lower bits to suit small container Negative number: keep the left most as the sign, then flip all of the bits, and then add 1 ++ +=,-=,* = , and /= will all put in an implicit cast.

Assignments: Primitive Variable vs. Reference Variable : 

79 Assignments: Primitive Variable vs. Reference Variable Assigning Primitive Variable  Primitive Variable the right-hand variable are copied Assigning Reference Variable Reference Variable Won’t copy, just assign the right reference variable links to the object which the left reference variable linking Reference Variable Assignments assign a newly created object to an object reference variable Makes a reference variable named AAA, of type XXX Creates a new XXX object on the heap Assigns the newly created XXX object to the reference variable AAA assign null to an object reference variable means the variable is not referring to any object. ++ CAN assign a subclass, CAN’T assign a superclass

++ Variable Scope : 

80 ++ Variable Scope Four basic scopes: Static variables have the longest scope; they are created when the class is loaded, and they survive as long as the class stays loaded in the JVM. Instance variables are the next most long-lived; they are created when a new instance is created, and they live until the instance is removed. Local variables are next; they live as long as their method remains on the stack. As we'll soon see, however, local variables can be alive, and still be "out of scope". Block variables live only as long as the code block is executing. ++ Typical of errors: access an instance variable from a static context (main()) access a local variable from a nested method use a block variable after the code block has completed ++ Pay extra attention to code block scoping errors. You might see them in switches, try-catches, for, do, and while loops.

Instance variable vs. Local variables : 

81 Instance variable vs. Local variables Instance variable: declared within the class but outside any method or constructor Local variable: declared within a method or in the argument list of the method stack, temporary, automatic, or method variables

Primitive and Object Type Instance Variables : 

82 Primitive and Object Type Instance Variables Variables are defined at the class level will auto initialized Primitive instance: are initialized to a default value each time a new instance is created object reference: null byte, short, int, long : 0 float, double 0.0 boolean: false char : '\u0000' A good idea to initialize all your variables Object reference : A null value of object reference means it is not referring to any object on the heap. ++ Array Instance: Array elements are always, always, always given default values, regardless of where the array itself is declared or instantiated The default values depends on the elements of array get when they're instance variables

Local (Stack, Automatic) Primitives and Objects : 

83 Local (Stack, Automatic) Primitives and Objects Local variables are defined within a method, and they include a method's parameters Local variable must be assigned a value in the code, or the compiler will complain. Local Primitives: always, always, always must be initialized before you attempt to use them CAN declare a local variable without initializing it as long as you don't use the variable (but what for……) CAN’T do initialization within a logically conditional block (if block or for loop without a literal value of true or false in the test), the compiler can produce an error. Local Object References: local references are not given a default value you must explicitly initialize the local variable Just set the darn thing to null explicitly, until you're ready to initialize it to something else ++ Local Arrays: array elements are given their default values (0, false, null, '\u0000', etc.) regardless of whether the array is declared as an instance or local variable

Assigning One Reference Variable to Another : 

84 Assigning One Reference Variable to Another The reference pattern is copied, but not the object content. In Java, String objects are given special treatment: String objects are immutable; you can't change the value of a String object any time we make any changes at all to a String, the VM will update the reference variable to refer to a different object. ++ Must always: String s = ……, otherwise you will lost your result.

authorStream Live Help