Presentation is loading. Please wait.

Presentation is loading. Please wait.

J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage.

Similar presentations


Presentation on theme: "J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage."— Presentation transcript:

1 J AVA AND V ARIABLES

2 O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage Collection Arrays

3 D ECLARING A V ARIABLE Variables can be broken into two groups Primitives Object references Primitives contain single values Object references allow us to touch object instances

4 D ECLARING A V ARIABLE Just like in C, Java needs you to set the type of each variable Primitive types have the same names as in C but different sizes Java does not have an unsigned type To put a bigger primitive into a smaller primitive, use typecasting int i = (int)12.5f;

5 P RIMITIVE T YPES boolean – true or false char – 16 bits Unicode not ASCII byte – 8 bits -128 to 127 short – 16 bits -32,768 to 32767 int – 32 bits -2,147,483,648 to 2,147,483,647

6 J AVA K EYWORDS Just like C, Java has special words you can not use for variables Eg. throw, package, break, while, final, default, long, short, super, this, enum, catch, etc...

7 R EFERENCE V ARIABLES When an object is declared, it is a reference to any object not the object itself A good analogy would be it’s a pointer You must use the ‘dot’ (. ) operator when working with and object reference variable E.g. myObject.dosomething() myObject.somevariable

8 O BJECT D ECLARATION AND A SSIGNMENT The statement Dog mydog = new Dog(); works in 3 steps: A new reference variable (mydog) is defined Space is made in memory for a Dog object The mydog object reference is set to point to the memory where the Dog object was placed

9 O BJECTS AND G ARBAGE C OLLECTION Since object reference variables only ‘pointer’ to objects, we can change which object they point to easily If an object does not have at least on object reference variable, it is lost and will get destroyed

10 A RRAYS Arrays are objects in Java, hence int[] nums; // not enough nums = new int[7]; // is also needed Other than the definition, they work remarkably like arrays in C The first element is ‘0’ You use [] to access different elements

11 S IMPLE E XAMPLE Using the code on the web, add a 3 rd cat to the cat array and print out its information Add a new piece of information to all cats and print it out also


Download ppt "J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage."

Similar presentations


Ads by Google