Discussion 1

8/27/02 Tue

  1. Differences of C and Java
  2. Numbers

Differences of C and Java

Variables must be declared at the beginning of a block code.

Java

public class decl {
        public static void main(String[] arg) {
                int x = 0;
                x++;
                int y = x + 1;
                System.out.println("x = " + Integer.toString(x) + ", y = " + 
                                        Integer.toString(y));
        }
}

C

int main()
{
        int x = 0;
        x++;
        int y = x + 1;
        printf("x = %d, y = %d\n", x, y);
        return 0;
}
This code generates the following error message.
> !gcc
gcc -o decl decl.c
decl.c: In function `main':
decl.c:6: parse error before `int'
decl.c:7: `y' undeclared (first use in this function)
decl.c:7: (Each undeclared identifier is reported only once
decl.c:7: for each function it appears in.)
Correction:
int main()
{
        int x = 0;
        int y;
        x++;
        y = x + 1;
        printf("x = %d, y = %d\n", x, y);
        return 0;
}

No run-time checks for uninitialized variables, array bounds, etc.

Java
public class decl1 {
        public static void main(String[] arg) {
                int x;
                System.out.println("x = " + Integer.toString(x));
        }
}
This generates the following compile error message:
javac decl1.java
decl1.java:4: Variable x may not have been initialized.
                System.out.println("x = " + Integer.toString(x));
C
int main()
{
        int x;
        printf("x = %d\n", x);

        return 0;
}

This C doesn't generate any error message.
If we execute the code:
> ./decl1
x = -4261020
Uninitialized values are used!
Java
public class decl2 {
        public static void main(String[] arg) {
                int a[] = { 0, 1, 2, 3, 4};
                System.out.println("a[5] = " + Integer.toString(a[5]));
        }
}

Run-time error check
java.lang.ArrayIndexOutOfBoundsException: 5
        at decl2.main(decl2.java:4)
C

int main()
{
        int a[] = {0, 1, 2, 3, 4};
        printf("a[5] = %d\n", a[5]);

        return 0;
}
If we execute the code above:
> ./decl2
a[5] = -4261020
Uninitialized values are used!
 
Back to Top

Numbers

Why we learn numbers?

Everything is represented in numbers in a computer:

Name a few things that are represented in numbers

Characters

 

Base Conversion 

1011 1101 0110 (binary) = ? (hex) = ? (dec)

10101 (binary) = 0001 0101 (binary) = ? (hex) = ? (dec)

4E5 (hex) = ? (binary) = ? (dec)

Negative number representation

For -7 (dec),

-111 (sign and magnitude)

1000 (1's complement assuming the numbers are in 4-bit)

1001 (2's complement assuming the numbers are in 4-bit)

2's complement is the representation of negative numbers in a computer. This is because the same hardware can be used both for positive and negative numbers.

 

Back to Top

Revised: 08/27/02 .