Showing posts with label Primary / primitive data types. Show all posts
Showing posts with label Primary / primitive data types. Show all posts

Monday, 27 June 2011

Binary integral literals

I can’t say I’ve ever felt the absence of this rather unusual feature. Though it seems it was felt compelling enough to be added in. This is primarily a readability advantage – a semantic representation.

public class BinaryLiterals {

public static void main(String[] args) {

// An 8-bit 'byte' literal.
byte aByte = (byte) 0b00100001;

// A 16-bit 'short' literal.
short aShort = (short) 0b1010000101000101;

// Some 32-bit 'int' literals.
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' literal. Note the "L" suffix.
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

}

}

Friday, 22 April 2011

Limits and Size of the primary data types


Limits of the primary datatypes:

Data types Width (in bytes) Minimum value Maximum Value
byte 1 -27 27 - 1
short 2 -215 215-1
int 4 -231 231 - 1
long 8 -263 263 - 1
char 2 0x0 0xffff
float 4 1.401298e-45 3.402823e+38
double 8 4.940656e-324 1.797693e+308


So the sizes in bytes are:
byte - 1 B
short, char - 2B
int, float - 4 B
double, long - 8B

Also to get the limits through java we can get it by their wrapper classes. Click here to see how to get limits programatically.

Primary datatypes and their wrapper classes

Corresponding to all the primitive type there is a wrapper class defined. These wrapper classes are OOP version of the primitive types. These classes provide useful methods for manipulating primitive data values and objects.

The language designers decided that the higher processing speed and memory efficiency of simple, non-class structures for such heavily used data types overruled the elegance of a pure object-only language.The designers decided instead that for each primitive type there would be a corresponding wrapper class. An instance of a wrapper contains, or wraps, a primitive value of the corresponding type.

Some primitive types and their wrapper classes:

Data types Wrapper class
int Integer
short Short
long Long
byte Byte
char Character
float Float
double Double

he wrapper constuctors create class objects from the primitive types. For example, for a double floating point number "d" :
     double d = 5.0;
     Double aD = new Double(d);

Here a Double wrapper object is created by passing the double value in the Double constructor argument.
In turn, each wrapper provides a method to return the primitive value
     double r = aD.doubleValue();

Each wrapper has a similar method to access the primitive value: integerValue() for Integer, booleanValue() for Boolean, and so forth.

Thursday, 21 April 2011

Booleans

Booleans are named after George Boole, a nineteenth century logician. Each boolean variable has one of two values, true or false. These are not the same as the Strings "true" and "false". They are not the same as any numeric value like 1 or 0. They are simply true and false. Booleans are not numbers; they are not Strings. They are simply booleans.
Boolean variables are declared just like any other variable.
boolean test1 = true;
boolean test2 = false;
Note that true and false are reserved words in Java. These are called the Boolean literals. They are case sensitive. True with a capital T is not the same as true with a little t. The same is true of False and false.

The char data type in Java

A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. A char literal is a single one character enclosed in single quote marks like this
char myCharacter = 'g';
Some characters are hard to type. For these Java provides escape sequences. This is a backslash followed by an alphanumeric code. For instance '\n' is the newline character. '\t' is the tab character. '\\' is the backslash itself. The following escape sequences are defined:
\b backspace
\t tab
\n linefeed
\f formfeed
\r carriage return
\" double quote, "
\' single quote, '
\\ backslash, \
The double quote escape sequence is used mainly inside strings where it would otherwise terminate the string. For instance
System.out.println("And then Jim said, \"Who's at the door?\"");
It isn't necessary to escape the double quote inside single quotes. The following line is legal in Java
char doublequote = '"';

Further java also supports Unicode Characters.

Unicode character in java

Java uses the Unicode character set. Unicode is a two-byte character code set that has characters representing almost all characters in almost all human alphabets and writing systems around the world including English, Arabic, Chinese and more.
Unfortunately many operating systems and web browsers do not handle Unicode. For the most part Java will properly handle the input of non-Unicode characters. The first 128 characters in the Unicode character set are identical to the common ASCII character set. The second 128 characters are identical to the upper 128 characters of the ISO Latin-1 extended ASCII character set. It's the next 65,280 characters that present problems.
You can refer to a particular Unicode character by using the escape sequence \u followed by a four digit hexadecimal number. For example
\u00A9 The copyright symbol
\u0022 " The double quote
\u00BD The fraction 1/2
\u0394 Δ The capital Greek letter delta
\u00F8 A little o with a slash through it
You can even use the full Unicode character sequence to name your variables. However chances are your text editor doesn't handle more than basic ASCII very well. You can use Unicode escape sequences instead like this:


String Mj\u00F8lner = "Hammer of Thor";

 but frankly this is way more trouble than it's worth.

Java primary data types : Integers

The integer types are for numbers without fractional parts. Negative values are allowed.
  • int      4 bytes
  • Short  2 bytes
  • Long   8 bytes
  • Byte   1 byte

In most situations, the int type is the most practical. If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays when storage space is at a premium.

Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code. This alleviates a major pain for the programmer who wants to move software from one platform to another, or even between operating systems on the same platform. In contrast, C and C++ programs use the most efficient integer type for each processor. As a result, a C program that runs well on a 32-bit processor may exhibit integer overflow on a 16-bit system. Because Java programs must run with the same results on all machines, the ranges for the various types are fixed.

Long integer numbers have a suffix L (for example, 4000000000L). Hexadecimal numbers have a prefix 0x (for example, 0xCAFE). Octal numbers have a prefix 0. For example, 010 is 8. Naturally, this can be confusing, and we recommend against the use of octal constants.

Cpp vs Java on integers

Note that Java does not have any unsigned types.

Wednesday, 20 April 2011

Java vs Cpp : Integers

In C and C++, int denotes the integer type that depends on the target machine. On a 16-bit processor, like the 8086, integers are 2 bytes. On a 32-bit processor like the Sun SPARC, they are 4-byte quantities. On an Intel Pentium, the integer type of C and C++ depends on the operating system: for DOS and Windows 3.1, integers are 2 bytes. When 32-bit mode is used for Windows programs, integers are 4 bytes. In Java, the sizes of all numeric types are platform independent.

Primary data types and their default values

Each primitive data type has a default value specified. Variable of primitive data type may be initialized.
Only class member variables are automatically initialized. Method variables need explicit initialization.

Primitive Data type Default Value
byte 0
short 0
int 0
long 0L or 0l
float 0.0f
double 0.0d
boolean false
char '\u0000'

Sunday, 17 April 2011

Binary representation of negative numbers in java : 2's complement

Negative numbers in Java are represented using 2's complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2's complement of that binary representation.

Okay, so how do find 2's complement of a binary number? Simply by adding '1' to the 1's complement of that number. But, how to find 1's complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

Example
int i = -4;
...

Step #1: Binary Equivalent of the positive value (4 in this case)

0000 0000 0000 0000 0000 0000 0000 0100

Step #2: 1's complement of the binary rep of 4 by inverting the bits

1111 1111 1111 1111 1111 1111 1111 1011

Step #3: Finding 2's complement by adding 1 to the corresponding 1's complement

1111 1111 1111 1111 1111 1111 1111 1011
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1100

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.

Monday, 11 April 2011

Convert Exponential form to Decimal number format in Java

While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form.
For example : In following we are multiplying 2.35 with 10000 and the result is printed.
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + a.doubleValue());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + a.doubleValue());
Result:
1)  2.85E-4
2) 2.85E8
Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.
import java.math.BigDecimal;
//..
//..
 
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + BigDecimal.valueOf(a).toPlainString());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + BigDecimal.valueOf(a).toPlainString());
Result:
1)  0.000285
2) 285000000
The only disadvantage of the above method is that it generates lonnnnggg strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal point and printing the output.
import java.text.DecimalFormat;
//..
//..
 
Double a = 2.85d / 10000;
DecimalFormat formatter = new DecimalFormat("0.0000");
System.out.println(formatter .format(a));
Result:
0.0003

Thursday, 31 March 2011

Conversion from primitive types to String and vice-versa

Conversion to String
Converting from primitive type to String can be done by using wrapper classes's static toString method.
Eg.
double i = 42.0;
String str = Double.toString(i);


Case of ascii format to string:
You can convert an ASCII code to String using toString() method of Character wrapper class as shown below:
 int i = 64;
 String aChar = new Character((char)i).toString();


Conversion from string:
Then in this case use parseWrapper method. Example:
For float :

String s = "31.2";
float f = Float.parseFloat(s);

Getting the limits of primitive types

To get the primitive type limits in java just use wrapper class' public static variables ... eg. MIN_VALUE,MAX_VALUE . Eg. 
Byte.MIN_VALUE  will give minimum value for byte. Similarily for Double, Float, Integer,  Short..etc