J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage.
Published byModified over 5 years ago
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:
O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage Collection Arrays
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
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;
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
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...
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
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
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
A RRAYS Arrays are objects in Java, hence int nums; // not enough nums = new int; // 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
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