Friday, January 4, 2019

Java literals!

Numbers, Strings, and Boolean
# Example
boolean x = true;    // 1 bit
boolean x = false;   // 1 bit
byte b = 1;          // 1 byte
short sh = 1;        // 2 byte
int x = 1;           // 4 byte
long l = 1L;         // 8 byte
float f = 1f;        // 4 byte
double d = 1d;       // 8 byte
char ch = 'a';       // 2 byte unicode

String x = "string";

# each of the primitive type has a helper/wrapper class
Boolean x;
Byte b;
Integer x;
Long l;
Float f;
Double d;
Character ch;
Java cast/convert types
// widing number is automatic, narrowing is not
int i = 789;
long li = i;
short si = (short) i;
int b = 1024;
byte bt = b;               // error
byte bt2 = (byte) b;       // lose data that overflows
double d = 2.88888888;
int di = (int) d;          // lose decimals
Prefix vs Postfix Incrementing or Decrementing
i++
++i
j--
--j
Java print can mix types.
# Example
int a = 1;
int b = 2;
String s = "string";
char[] cstring = "this is a string".toCharArray();

System.out.print ( a );
System.out.print ( a,b );
System.out.print ( s );
System.out.print ( " The number is " + 123 );
System.out.println ( cstring );
Operators
# Example
int x = 0, y = 0, z = 0;
x = x + 1;
x += 1;
x -= 1; 
y = x / 3;
y = x % 3;
x *= y + z;
x = x * (y+z);
x /= y + z;
x = x / (y+z);
What do you think this will do?
x =+ 5
y =- 3
Java print allows you to mix different types.
int x = 0, y = 0;
x =+ 5;
y =- 3;
System.out.println( " x : " + String.valueOf(x) );
System.out.println( " x : " + Integer.toString(x) );
System.out.println( " x : " + x );
System.out.println( y );
x += 5;
y -= 3;
System.out.println( x );
System.out.println( y );

// System.out.println( " x : " , x ); // Error!! But it works in Python

No comments:

Post a Comment