Saturday, 17 November 2007

Java basics: data types and operators

Hey guys, today I'll give you a quick view of Java data types and operators.

In Java, there are 3 main data types: primitive, object and array.
  • Primitive: byte, short, int, long, float, double, char and boolean. You can declare a primitive variable like this:
    int a = 1337;
    double b = 13.37;
    char c = '$';
    boolean d = true;
  • Object: Java is object-oriented, therefore you can see objects everywhere. Even string is a special type of object. You can declare an object with the keyword new:
    Object o = new Object();
    Applet a = new Applet();
    String s = new String("Hello world!");
    String t = "Hello world!"; // String is special, after all ;)
  • Array: Just like in other languages, you can use arrays in Java too. An array is declared with the keyword new, and you can use an index to access an array's member:
    int[] a = new int[2];
    a[0] = 13; // note that array indexes start at 0
    a[1] = 37;
    Object[] o = new Object[2]; // array of objects
    o[1] = "Hello worrd!";
    o[2] = new Integer(1);
    int[][] b = new int[2][2]; // multidimensional array
    b[0][0] = 1;
    b[0][1] = 3;
    b[1][0] = 3;
    b[1][1] = 7;
Here are some common operators that you can use on them:

+ (addition, also string concatenation), - (subtraction), * (multiplication).
/ division, note that it returns the integral quotient if applied between integral values.
% (modulo) returns the remainder in division.
= (assignment) assigns a value to a variable.
++ (increment) increments a variable by 1.
-- (decrement) decrements a variable by 1.
== (equal), != (not equal), < (less than), > (greater than), <= (less than or equal), >= (greater than or equal)
! (not operator for boolean)
&& (conditional and), || (conditional or)
bitwise operators: ~ (not), & (and), | (or), ^ (xor), << (shift left), >> (shift right), >>> (unsigned shift), you can see an explanation about them here.

Confused? Try using them in your program and see how they work. You can use the HelloWorld template in the previous lesson :)

No comments: