Data Structures using Java Part 3: Primitives, java.lang, conditionals, return

Primitive Types:
1. byte : an 8 bit integer (-128 to 127)
2. short: a 16 bit integer (-32768 to 32767)
3. int: a 32 bit integer (- 2 billion to well +2 billon)
4. long: a 64 bit integers (well..) eg. 124L or 134l
5. double: a 64 bit floating point number eg.67.0
6. float: a 32 bit floating point number eg. 12.4f or 5.5F
7. boolean: its true or false
8. char: a single character

A double or float should always have a decimal point, else it will be treated as an int.

                       Object Types            Primitive Types
                       ---------------           ----------------
1. Contains         Reference              Value
2. Definition        Class                    Built into java
3. Creation         "new"                    "4", true
4. Initialisation    constructor            Default value generally 0 or false
5. Usage            methods                Operators (+, - , *)

java.lang library
1. Math class

a = Math.abs(y); // finds the absolute value of y and there are more methods like sqrt, sin

2. Integer class

int x = Interger.parseInt("2010"); // converts the string into a number

3. Double class

double d = Double.parseDouble("3.412"); // converts string to double

Integers can be assigned to variables of longer type. Otherwise you need to cast the type explicitly to get the desired valure and to avoid compile time errors.

int i = 100;
long l = 45l;
l = i;// this is okay
i = l;// compile time error
i = (int)l; //this is called a cast. throws the 32 bits off for the int!

1. if..else

boolean pass = score >= 75;
if (pass){
System.out.println("you passed");
// that is your score is less than 75

2. switch

The switching case cannot be a floating point and definitely not an object. All other types can be used.


case 2 : days = 28;
case 4:
case 6:
case 9:
case 11: days = 30;
default: days = 31;

The return keyword
1. Causes a method to end immediately when executed.
2. Control returns to the calling method.

public void something (int x){

if ( x == 10){
return; // if x is 10 do not continue with the function
// the rest of the code runs if not equal to 10

3. Useful for returning a value from a function, which is a method to return a non void type value. The add() function just returns the sum of a and b to the calling function.

public int add(int a , int b){
return (a + b);
Data Structures using Java Part 3: Primitives, java.lang, conditionals, return

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s