Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes: Ch 3: Using Classes and Objects (2 of 2)
Logistics
Topic Outline:
Review: Academic Honesty + Collaboration and Cheating Policy
Ch 3:
Using Classes and Objects
Math class redux
Style
Converting Strings and Other Types
String x =
"123";
int i = Integer.parseInt(x);
System.out.println(i);
| b | boolean |
| d | decimal integer |
| o | octal integer |
| h | hex integer |
| H | Hex integer |
| f | Floating-point number |
| e | Floating-point number in scientific notation |
| g | Floating-point number in compact form |
e) Examples
// convert to hexadecimal
int y = 165;
System.out.printf("%d\n",y); // 165
System.out.printf("%h\n",y); // a5
System.out.printf("%H\n",y); // A5
// different forms of floating-point numbers
double d = Math.pow(Math.PI,20);
System.out.printf("%e\n",d); // 8.769957e+09
System.out.printf("%f\n",d); // 8769956796.082693
System.out.printf("%g\n",d); // 8.76996e+09
f) Field width
int y = 123, z = 45;
System.out.printf("123456789\n"); // 123456789
System.out.printf("%4d%4d\n",y,z); // 123 45
System.out.printf("%1d%4d\n",y,z); // 123 45
g) Flags: Left-Justified ('-'), Use-Sign ('+'), and Zero-Padded ('0')
int y = 123, z = 45;
System.out.printf("123456789\n"); // 123456789
System.out.printf("%4d%+4d\n",y,z); // 123 +45
System.out.printf("%-4d%+4d\n",y,z); // 123 +45
System.out.printf("%+05d%4d\n",y,z); // +0123 45
h) Precision
double d = 45.678;
System.out.printf("%.0f\n",d); // 46
System.out.printf("%.1f\n",d); // 45.7
System.out.printf("%.2f\n",d); // 45.68
System.out.printf("%+06.2f\n",d); // +45.68
System.out.printf("%+07.2f\n",d); // +045.68
Wrapper classes + Autoboxing
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem