Java Basics 1.02

Numeric are Primitives

  • Simple value
  • Stored in fastest memory
  • Numeric/Boolean
  • all lowercase
  • int varprimitive

 

Type

Bits

Min

Max

byte

8

-128

127

short

16

-32,768

32,767

int

32

-2,147,483,648

2,147,483,647

long

64

-9.22337E+18

9.22337E+18

float

32

 

 

double

64

 

 

 

Setting Literal Values

  • byte b = 1;
  • short s = 10;
  • int i = 10;
  • long l = 100L;
  • float f = 150.5f;
  • double d = 150.5d;

Without extra char, Java will cast it automatically, not using memory most efficiently

 

Helper Classes

 

Data Type

Helper Class

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

 

Numeric Wrapper Class

  • Double provides tools for convering float values
  • double doubleValue = 156.5d;
  • Double doubleObj = new Double(doubleValue);
  • byte myByteValue = boubleObj.byteValue();
  • int myIntValue = doubleObj.intValue();
  • float myFloatValue = doubleObj.floatValue();
  • Strig myString = double.Obj.toString();

 

 

BigDecimal

For currency values that have guaranteed precision

 

Problem

BigDecimal payment = new BigDecimal(1115.37);

System.out.println(payment.toString());

>1115.36999999908796...

...Result determined by OS, Processor, etc

 

Solution

double d = 1115.737;

String ds = Double.toString(d);

BigDecimal bd = new BigDecimal(ds);

System.out.println(“the value is “ + db.toString());

>Value is 1115.37

 

 

Converting Primitives Upward/Downward

Converting upwards:

  • int intvalue = 120;
  • double doubleResult = intValue; // = 120.0 (double)

 

Converting downwards:

double doublevalue = 3.99;

int intResult = doubleValue; // won’t even compile due to accuracy loss

int intResult = (int)doubleValue; // explicit accuracy loss by truncating

= 3

 

  • double
  • float
  • long
  • int
  • short
  • byte

 

 

Wrapping Around when converting Downward

  • double > byte

 

int i = 128;

byte b = (byte)i;

> -128

 

Casting Syntax VS Helper Class

Casting

  • Doesn’t add another object to memory
  • Can’t use afterwards

double doubleValue = 3.99;

int intResult = (int)doubleValue;

 

Helper Class

  • Creates instance of Helper Class in memory
  • Good when needing to do things with it later

double doubleValue = 3.99;

double doubleObj = new Double(doubleValue);

int intResult = doubleObj.intValue();