Difference between revisions of "Primitives"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 27: Line 27:
 
* they are stored as '''unsigned''' 16-bit integers. This means they will represent a total of 2^16 positive values (0 to 65535 (2^16-1) )
 
* they are stored as '''unsigned''' 16-bit integers. This means they will represent a total of 2^16 positive values (0 to 65535 (2^16-1) )
 
* contrast with short which also uses 2 bytes. But it's max positive range is 2^15 -1. (Since 1 bit is to used to represent the sign)
 
* contrast with short which also uses 2 bytes. But it's max positive range is 2^15 -1. (Since 1 bit is to used to represent the sign)
 
<u> Comments </u>
 
* Comment start sequences like //, /*. /** are ignored within comment blocks.
 
* So trying to nest multiple-line comments will result in an error
 
 
<syntaxhighlight lang="java5">
 
/* This is the foo algorithm
 
  /* which takes foo's and sort's bars */
 
*/
 
</syntaxhighlight>
 
 
  
 
== Assignments ==
 
== Assignments ==

Revision as of 02:11, 26 August 2011

  • Default type of an integer literal is int.
  • Long can be specified by adding l or L
  • Octal prefix with 0
  • Hex prefix with 0x or 0X
  • Floating point literals default type is double.
float pi = 3.14; // This will be a compiler error, because 3.14 is a fp literal which is double by default
double pi = 3.14; //OK
float pi = 3.14f; //OK
  • Double can also be explicitly by adding the suffix d or D
  • Float is denoted by suffix f or F
  • Integers are stored in 2 complements's notation
  • Leftmost bit is the sign bit, the remaining bits are used to store the value

e.g. of Byte

  • Byte - 1 byte = 8 bits.
  • Leftmost bit is to store the sign. So 7 bits are available for the value, so 2^7 = 128 values
  • Negative range is -128 to -1 (128 numbers)
  • Positive range is 0 to 127 (128 numbers, 0 is stored as a positive number)
  • So a byte's range is -2^7 to (2^7 - 1)
  • char's take up 2 bytes
  • they are stored as unsigned 16-bit integers. This means they will represent a total of 2^16 positive values (0 to 65535 (2^16-1) )
  • contrast with short which also uses 2 bytes. But it's max positive range is 2^15 -1. (Since 1 bit is to used to represent the sign)

Assignments

Watch out!

float f = 2;  //This is legal. 2 is an int which fits in a float.
float f = 2.0; //Illegal. 2.0 is a double which by default won't fit in a float.