Monday, June 25, 2012

Assignments


Stack and Heap

Stack handles Local variables.
Heap handles Instance variables and objects.



Stack
setBrand() brandName
build() pc
main() c

Heap
Computer
MotherBoard
String

Integer Literals

Decimal, Octal and Hexadecimal are by default int, unless we type L as a suffix

long so = 0xFFFFl;  // Note the lowercase 'l'

Octal Literals => Octal integers use only the digits 0 to 7.
The preceding 0 identifies an Octal integer.

We can have up to 21 digits in an octal number, not including the leading zero.

Hexadecimal Literals => Are constructed using 16 distinct symbols not including the prefix 0x or the optional suffix extension L

0 1 2 3 4 5 6 7 8 9 a b c d e f


Floating-Point Literals

By default floating-point literals are defined as a double(64 bits), that's why the first statement does not compile, the second statement is using a suffix "f"(could be "F") which says to compiler we're talking the risk(loss of precision), Finally we cannot use a semicon instead of a dot.

Boolean Literals

!Important
Java does not allow a number like 0 or 1, only true and false are valid

Character Literals

You can assign a number literal, assuming it will fit into the unsigned 16-bit
range (65535 or less).

Not legal assignments.

char e = -29;   // Possible loss of precision; needs a cast
char f = 70000  // Possible loss of precision; needs a cast

Primitive Assignments

Image of all primitives

As you know literal integer is always int, futhermore the result of a expression involving an int results in an int value.

byte a = 3;     // No problem, 3 fits in a byte
byte b = 8;     // No problem, 8 fits in a byte
byte c = b + c; // Does not compile because the result is an int.

Primitive Casting

Casts can be implicit or explicit, where implicit cast we don't have to type anything, implicit casts happen when we try to assign a smaller thing(like short) to a bigger container(like long).

int num = 100;
long num1 = num; // Implicit cast, an int value always fits in a long

An explicit casts looks like this:
float ft = 100.001f;
int num = (int)ft; // Explicit cast, the float could lose info

Let's review


Floating Assignments


! Important
 +=, -=, *=, and /= will all put in an implicit cast.

 byte b = 127;
 b+= 7;




Autoboxing - Part 2


The most import thing to know about Autoboxing is that wrapper classes are not immutable and since Java 5 we can work with them like primitives, for instance:


Comparasion of Boxing

Let's do something really weird


What happened at line 10? Why it prints true?  The operator == compares if the instance variable points to the same object in the heap,in this case we have 2 objects, so it should print false, however in this case the comparison is primitive to primitive, it happeans because the wrapper objects are unwrapped, but watch out, it is not applicable for all wrapper classes and values, find below what classes are allowed:

- Boolean
- Byte
- Short,Integer and Long ( range -128 to 127)
- Character ( from \u0000 to \u007f (7f is 127 in decimal))

Finally make sure that a variable instance is not pointing to a null otherwise we'll get an exception (NullPointerException)

Foundation of Autoboxing - Part 1


The main purpose of AutoBoxing(unBoxing) is provide a way to work with primitives as Objects, in order we can use Generics and so on.

Find below the Wrapper classes:



Creating Wrapper Objects

Most of Wrappers provide a constructor that gets as an argument a primitive value and a String object. Only the Wrapper class Character gets one argument which is a char primitive.
Let's see some examples:


All the wrapper classes mentioned so far contain a method called valueOf(), this method is a static method and can get different arguments depending on the wrapper, for instance:

Byte/Short/Integer/Long

[Wrapper] static valueOf(primitive)
[Wrapper] static valueOf(String)
[Wrapper] static valueOf(primitive, int radix) // radix defines the base like decimal, octal or hexadecimal.

Float/Double/Boolean

[Wrapper] static valueOf(primitive)
[Wrapper] static valueOf(String)

Character
[Wrapper] static valueOf(primitive)

Conversion 

Also we can make a conversion using the wrapper classes by calling the methods xxxValue(), all these methods don't have arguments, for instance:

Wrapper classes
The following classes extend Number -> Byte/Double/Float/Integer/Long/Short



Slightly different from the valueOf() method, the static method parseXXX() has two "flavours" similar to valueOf(), furthermore these methods are applicable only for the 6(six) integer classes and not to mention that the return of these is a primitive type instead of a wrapper class.

[Wrapper] static valueOf(String)
[Wrapper] static valueOf(primitive, int radix) // radix defines the base like decimal, octal or hexadecimal.

Example of valueOf, xxxValue and parseXxx


Finally the last thing that you have to pay attention is, valueOf and parseXxx throw a NumberFormatException if the format of a string is not valid.

Tuesday, June 19, 2012

Reference Variable Casting


This section takes care of Casting(DownCasting and UpperCasting) Downcast: Casting down the inheritance tree to a more specific class The compiler trusts in us even if you're trying to cast object that does not refer a dog. The code above compiles well but you'll get an exception(java.lang.ClassCastException) at runtime, it occurrs because the compiler only verifies an inheritance tree, in this case Dog is a subtype of Animal. !Important Watch out, the code above compiles the exception is throwns at runtime. Upcasting: Unlike downcasting you don't have to type anything like the previous example Dog d = (Dog)a, the upcasting is implicitly, in other words you're restricting the number of methods that you can invoke. Finally the casting can be at one line.

Monday, June 18, 2012

Overridden Methods


When we think about inheritance one of the important things to learn is overridden methods, in this post I will provide you an overview of this feature of oriented-object, also this post is intented to help you to get all the rules involved to get an OCJP certification.

Let's start with an example

e.g.


If you run this code above you will get:

The MacBook is turned on
The Computer is turned on

The reference variable determines at runtime which method will run depending on instanced object.
Notice that the method openMacOS() cannot be invoked using the reference variable Computer, this variable doesn't know anything about specific methods defined by MacBook class.
Also the overridding method cannot have a more restrictive access modifier, in this case the method turnOn() cannot be private, protected or default.

Let's review the rules.

1. The argument list must be exactly the same as the method that you're overrinding otherwide you're overloading a method.
2. The return type must be the same as, or a subtype of an overridden method declared in a superclass.
3. The access level can't be more restrictive than the overridden method's, but can be less restrictive.
4.

5.
-The overriding method CAN throw any unchecked (runtime) exception
-If the method declared in a superclass throws a checked exception the overriding method must throw a checked exceptions that match in a test IS-A.
6. Look at the modifiers: method marked as final or static cannot be overriden.
7. Methods that cannot be inherited cannot be overriden, so watch out the access modifiers.

Invoking a Superclass Version

We can invoke the superclass method by using super.methodName().


Talking about Enums declarations

First off all we have to get a better understanding of enums declaration, it seems to be easier however there are some tricks involved. 
Let's start from the easiest part how to declare a enum or better where enums are allowed to be declared: 

1. Enums can be declared within a class like a member: 

e.g. 


Ok, that's a easy one, but be aware that the semicolon at the end of the statement is not required when there is no more statements below the enum. 
Notice that the class name is preceding the enum, it's required to access enums that are declared within a class. 

2. Enuns can be declared outside a class 

e.g. 
    
 The most important thing here is when you declare a enum outside a class it cannot be marked as private or protected like a non-inner class 
 Different from enums declared within a class here we can access the enum by using only its name. 
  
 ! Important 
 Let's see what is allowed for enums declarations. 
  
 1. We cannot declare a enum within a method. 
 2. An enum declared outside a class cannot be marked as private or protected. 
 3. None of these modifiers are allowed for enums declared outside a class: final, static and abstract. 
 4. We can mark methods that are declared in a enum outside a class as final, static and syncronized but not abstract. 
 5. All access modifiers and static modifier are allowed for enums declared as a member(inside a class). 
  
 Declaring constructors, instance variables and methods in an enum.
  
 We can declare constructors, instance variables and methods inside an enum like you do for classes, each element of enum is a instance of enum that could contain its state and behavior. 

 e.g.  

The import things here are: 

1. We cannot invoke directly the constructor, as you can see the arguments of constructors are declared with the element, in this case MALE and FEMALE. 
2. We can declare more than one argument for the constructor as well as overload it. 

The last feature that enums provide us is: 

 e.g.  



It's like a default method for the element FEMALE, all the elements when invoke printSomething() get a message "Enum Gender", unlike when FEMALE invokes that method it will get "Enum Gender for Female".