Sams Teach Yourself C in 21 Days

(singke) #1
Another difference between C++ and Java is this: although C++ permits you to use
object-oriented programming, Java requires that you do. You are assured that the advan-
tages of object-oriented programming are present throughout the entire program.
What about C#? C# is a newer language that is based on C and C++. Like Java, using
object-oriented programming concepts is not optional, rather it is required. Like Java, C#
removes some of the dangers and complexities of C++ while adding in simpler support
for OOP.

Java’s Platform Independence ......................................................................

When Java was first introduced, perhaps the one thing that was most exciting for pro-
grammers was its promised platform independence. In theory, you could write a single
Java program and have it execute without modification on a PC, a Macintosh, a Sun
workstation, or any other computer platform supported by Java. This was a truly major
advance. How does Java’s platform independence work?
When you write a program, in C or Java or whatever, you use the English-like statements
and keywords of the specific language. A computer, however, cannot directly understand
your program. A computer’s central processing unit, or CPU, understands only the spe-
cific binary instructions it was designed to work with. The CPU, therefore, must translate
your program, from your programming language into the binary instructions that are
readable. When you compile a C program, this is exactly what you are doing—translat-
ing source code to binary code.
Unfortunately, different computers use different CPUs. Although the general principles
behind all CPUs are the same, they differ in the details. This means that the binary code
must be generated for a specific CPU. A Macintosh will not understand binary code cre-
ated for a PC, and vice versa.
Java’s solution to this problem is as follows. When a Java program is compiled, it is not
translated all the way to binary instructions but rather to bytecode. Bytecode can be
thought of as an intermediate step between source code and binary code. The important
factor is that bytecode has no CPU-specific elements in it. In other words, it is still
generic and platform independent.
Each different platform, or type of computer, has its own Java interpreter. This interpreter
is specifically designed to translate Java bytecode into the CPU-specific binary instruc-
tions required for this particular system. The interpreter is called the Java Virtual
Machine (JVM), and the process of translating the bytecode to binary instructions is
done as the program is executing. Hence, when you write a Java program, you can dis-
tribute the same compiled bytecode for use on any system that has a Java Virtual
Machine.

642 Bonus Day 1

36 448201x-Bonus1 8/13/02 11:18 AM Page 642

Free download pdf