Monday, June 25, 2012

Assignments


Stack and Heap

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


package br.com.ocjp.assignments;
class MotherBoard { }
class Computer {
MotherBoard motherboard;
String brand;
void setBrand(String brandName) { // <===== local variable
brand = brandName;
}
void build(Computer pc) { // <===== local variable
motherboard = new MotherBoard();
pc.setBrand("MacBook");
}
}
public class StackHeap {
public static void main(String[] args) {
Computer c; // <===== local variable
c = new Computer();
c.build(c);
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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.

class Octal {
public static void main(String [] args) {
int six = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
System.out.println("Octal 010 = " + eight);
}
}
view raw gistfile1.java hosted with ❤ by GitHub
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

class HexTest {
public static void main (String [] args) {
int x = 0X0001;
int y = 0x7fffffff;
int z = 0xDeadCafe;
System.out.println("x = " + x + " y = " + y + " z = " + z);
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Floating-Point Literals

package br.com.ocjp.assignments;
public class FloatingPoint {
public static void main(String[] args) {
float m = 100.88; // does not compile
float n = 100.88f;
}
}
view raw gistfile1.java hosted with ❤ by GitHub
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

public class PrimitiveAssignments {
public static void main(String[] args) {
short sh = 300; // by default integer literals are int
short sh1 = 127 * 5; // By default a result of an expression is an int
//short sh2 = 127 * 1000; Does not compile because the int returned does not fit in a range of short
short sh3 = 5;
short sh4 = 127;
//short sh5 = sh3 * sh4; //Does not compile because the value of a variable can change at runtime, needs a cast
short sh5 = (short)(sh3 * sh4); // Works fine using casting.
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Floating Assignments

public class FloatingAssignments {
public static void main(String[] args) {
//float f = 32.5; Does not compile because a floating literals are always double
float f = (float) 32.3; // Works fine, using casting
float g = 32.3f; // Works fine, suffix f
float h = 32.3F; // Works fine, suffix F
}
}
view raw gistfile1.java hosted with ❤ by GitHub

! 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:

public class Autoboxing {
public static void main(String[] args) {
Short s = Short.valueOf("10");
Short s1 = s;
System.out.println(s == s1); // Prints true once that s and s1 refer to the same object
s--; // We can use s as a primitive type
System.out.println(s); // Prints 9
System.out.println(s == s1); // Prints false, again wrapper classes are not immutable like Strings.
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Comparasion of Boxing

Let's do something really weird

package br.com.ocjp.autoboxing;
public class AutoBoxing1 {
public static void main(String[] args) {
Long x = Long.valueOf(10);
Long y = Long.valueOf(10);
System.out.print("x and y are == "); // What????
System.out.println(x == y);
System.out.println("x and y are equals " + x.equals(y)); // it's not a surprise
System.out.println("Another example....");
Long x1 = Long.valueOf(130);
Long y1 = Long.valueOf(130);
System.out.print("x1 and y1 are == "); // normal behaviour
System.out.println(x1 == y1);
System.out.println("x1 and y1 are equals " + x1.equals(y1)); //normal behaviour
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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:

public class WrapperJava {
public static void main(String[] args) {
Integer n1 = Integer("10");
Integer n2 = Integer(10);
Float f1 = new Float("5.3");
Float f2 = new Float("5.3f");
Float f3 = new Float("5.3d");
Float f4 = new Float(5.3);
Float f5 = new Float(5.3f);
Character c1 = new Character('d');
//... so on
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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

package br.com.ocjp.autoboxing;
public class Examples {
public static void main(String[] args) {
// valueOf
Byte b1 = Byte.valueOf((byte)100);
Byte b2 = Byte.valueOf("101");
System.out.println(b1); // Prints 100
System.out.println(b2); // Prints 101
// parseXXX
byte b3 = Byte.parseByte("100");
byte b4 = Byte.parseByte("010", 8);
byte b5 = Byte.parseByte("F", 16);
System.out.println(b3); // Prints 100
System.out.println(b4); // Prints 8
System.out.println(b5); // Prints 15
// xxxValue
Integer i = Integer.valueOf("F",16);
byte b6 = i.byteValue();
System.out.println(b6); //Prints 15
// toString /toString(xxx) and toString(xxx,radix)
System.out.println(i.toString()); //Prints 15
System.out.println(Float.toString(10.59f));//Prints 10.59
// Watch out, only Long and Integer have a toString(xxx,radix) method.
System.out.println(Long.toString(15, 16)); //Prints f
// Again only for Long and Integer
// toXxxString()
String s1 = Integer.toBinaryString(1);
String s2 = Integer.toHexString(8);
String s3 = Integer.toHexString(15);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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
class Animal {
void makeNoise() {
System.out.println("Generic noise");
}
}
class Dog extends Animal {
void makeNoise() {
System.out.println("Bark");
}
void playDead() {
System.out.println("Playing");
}
}
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Dog();
Dog d = (Dog)a; // downcast
a.playDead();
}
}
view raw gistfile1.java hosted with ❤ by GitHub
The compiler trusts in us even if you're trying to cast object that does not refer a dog.
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Animal();
Dog d = (Dog)a; // downcasting
a.playDead();
}
}
view raw gistfile1.java hosted with ❤ by GitHub
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.
class Computer {
void turnOn() {
System.out.println("Turning on Computer");
}
}
class MacBook extends Computer {
void turnOn() {
System.out.println("Turning on MacBook");
}
void openMacX() {
System.out.println("Openning a MacX");
}
}
public class ComputerTest {
public static void main(String x[]) {
MacBook m = new MacBook();
Computer c = m; // upcasting - implicitly
Computer c = (Computer)m; //upcasting - explicitly
}
}
view raw gistfile1.java hosted with ❤ by GitHub
Finally the casting can be at one line.
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Dog();
Dog d = (Dog)a; // downcasting
a.playDead();
((Dog)a).playDead(); // at one line
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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.

public class Computer {
public void turnOn() {
System.out.println("The Computer is turned on");
}
}
class MacBook extends Computer {
public void turnOn() {
System.out.println("The MacBook is turned on");
}
public void openMacOS() {
System.out.println("The MacOS is opened");
}
}
class ComputerTest {
public static void main(String[] args) {
Computer c = new MacBook();
c.turnOn();
c.openMacOS(); // we cannot invoke this method
Computer c = new Computer();
c.turnOn();
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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.
import java.io.FileNotFoundException;
import java.io.IOException;
class Computer {
public void turnON() throws IOException {
System.out.println("Turned on computer");
}
}
class MacBook extends Computer {
public void turnON() throws RuntimeException, FileNotFoundException {
System.out.println("Turned on macBook");
}
}
view raw gistfile1.java hosted with ❤ by GitHub

-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().

import java.io.FileNotFoundException;
import java.io.IOException;
class Computer {
public Object turnON() throws IOException {
System.out.println("Turned on computer");
return null;
}
}
class MacBook extends Computer {
public String turnON() throws RuntimeException, FileNotFoundException {
System.out.println("Turned on macBook");
try {
super.turnON();
} catch (IOException e) { // we have to handle this exception
e.printStackTrace();
}
return null;
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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. 
class Employee {
Gender gender;
}
public class Something {
enum Gender { MALE , FEMALE };
public static void main(String[] args) {
Employee e = new Employee();
e.gender = Something.Gender.FEMALE;
}
}
view raw gistfile1.java hosted with ❤ by GitHub



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. 
enum Gender {
MALE,
FEMALE
}
class Employee {
Gender gender;
}
public class TestEnum {
public static void main(String[] args) {
Employee e = new Employee();
e.gender = Gender.MALE;
}
}
view raw gistfile1.java hosted with ❤ by GitHub

    
 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.
enum Gender {
MALE("M","Male"),
FEMALE("F","Female");
private String shortCode;
private String description;
Gender(String shortCode, String description) {
this.shortCode = shortCode;
this.description = description;
}
public String getShortCode() {
return shortCode;
}
public String getDescription() {
return description;
}
}
view raw gistfile1.java hosted with ❤ by GitHub
 

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.
enum Gender {
MALE("M","Male"),
FEMALE("F","Female") {
public String printSomething() {
return "Enum Gender for Female";
}
};
private String shortCode;
private String description;
Gender(String shortCode, String description) {
this.shortCode = shortCode;
this.description = description;
}
public String getShortCode() {
return shortCode;
}
public String getDescription() {
return description;
}
public String printSomething() {
return "Enum Gender";
}
}
view raw gistfile1.java hosted with ❤ by GitHub
 



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".