420 likes | 1.45k Views
Java and Variables. Overview. Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage Collection Arrays. Declaring a Variable. Variables can be broken into two groups Primitives Object references
E N D
Overview • Declaring a Variable • Primitive Types • Java Keywords • Reference Variables • Object Declaration and Assignment • Objects and Garbage Collection • Arrays
Declaring a Variable • Variables can be broken into two groups • Primitives • Object references • Primitives contain single values • Object references allow us to touch object instances
Declaring a Variable • 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;
Primitive Types • 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
Java Keywords • 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...
Reference Variables • 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
Object Declaration and Assignment • 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
Objects and Garbage Collection • 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
Arrays • 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
Simple Example • Using the code on the web, add a 3rd cat to the cat array and print out its information • Add a new piece of information to all cats and print it out also