4fwhythef charactercnewcharactera

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ns = " + s + "\nl = " + l + "\nb = " + b); } What does this print? } CPSC 324 ‐‐ Spring 2010 26 13 1/14/10 Java Primitive Data Types Floating point types –  again, these are not dependent on the architecture •  float –  float f = 3.14159F; –  4 bytes (about +/- 3.40282347E+38, 6-7 sig. digits) •  double –  double d = 3.14159; –  8 bytes (much larger than float, 15 sig. digits) Note if you don’t put “F” (or “f ”), defaults to double! CPSC 324 ‐‐ Spring 2010 27 Java Primitive Data Types Character and boolean types •  char –  char c = ‘a’; // this is not the same as the string “a” –  Unicode (‘\uXYZ’ for XYZ the unicode number) •  boolean –  boolean b = true; // can also use false –  You cannot convert between boolean values and integers (e.g., 0 is not false) CPSC 324 ‐‐ Spring 2010 28 14 1/14/10 Classes for primitive types: “Boxing” •  It is sometimes convenient to use primitive  values as objects •  Java provides classes for each primitive type Integer i = new Integer(10); // i refers to an object, not 10 Float f = new Float(4.4F); // why the “F”? Character c = new Character(‘a’); System.out.print(“i = ” + i.intValue()); // get and print 10 –  Integer, Float, Character are classes –  and i, f, and c are references to objects of these classes –  We will go into classes and objects later … CPSC 324 ‐‐ Spring 2010 29 Java classes for primitive types •  Recall that –  Java distinguishes between primitive & non-primitive types –  Types are checked statically (at compile-time) in Java •  Assume we have two variables defined: Integer obj = new Integer(5); // object type int prim = 10; // primiPve type •  Should this expression compile? prim = prim – obj; // int – Integer This is an example of “unboxing” Java takes the value out of the object to ensure type safety CPSC 324 ‐‐ Spring 2010 30 15 1/14/10 Java classes for primitive types •  What about this expression? obj = prim + obj; // int + Integer This is an example of “autoboxing” Java puts the value into an object to ensure type safety •  Older versions of Java didn’t support either of these –  Later we’ll see where this is really useful •  When possible though, you should use the primitive types, not the “boxed” versions of the primitive types CPSC 324 ‐‐ Spring 2010 31 Variables •  Every variable is declared with a type double salary; // salary is of type double int vacaPonDays; // vacaPonDays is of type int boolean done; // done is of type boolean •  Variables must be initialized before they are used! int vacationDays; if(vacationDays > 100) // compile error!!! System.out.print(“You really need a vacation!”); VariableIniP...
View Full Document

Ask a homework question - tutors are online