Vous êtes sur la page 1sur 9

How Java Differs from C and C++

This appendix contains a description of most of the major differences between C, C++, and the Java language. If you
are a programmer familiar with either C or C++, you may want to review this appendix to catch some of the
common mistakes and assumptions programmers make when using Java.
Pointers
Java does not have an explicit pointer type. Instead of pointers, all references to objects including variable
assignments, arguments passed into methods, and array elementsare accomplished by using implicit
references. References and pointers are essentially the same thing except that you cant do pointer arithmetic
on references (nor do you need to.
References also allo! structures such as lin"ed lists to be created easily in Java !ithout explicit pointers#
simply create a lin"ed list node !ith variables that point to the next and the previous node. $hen, to insert
items in the list, assign those variables to other node objects.
Arrays
%rrays in Java are first class objects, and references to arrays and their contents are accomplished through
implicit references rather than via point arithmetic. %rray boundaries are strictly enforced# attempting to read
past the end of an array is a compile or run&time error. %s !ith other objects, passing an array to a method
passes a reference to the original array, so changing the contents of that array reference changes the original
array object.
Arrays of objects are arrays of references that are not automatically initialized to contain actual objects. Using
the following Java code produces an array of type MyObject with ten elements, but that array initially
contains only nulls:
'y(bject arrayofobjs) * + ne! 'y(bject),-*#
.ou must no! add actual 'y(bject objects to that array/
for (int i+-# i 0 arrayofobjs.length# i11 2
arrayofobjs)i* + ne! 'y(bject(#
Java does not support multidimensional arrays as in 3 and 311. In Java, you must create arrays that contain
other arrays.
Strings
4trings in 3 and 311 are arrays of characters, terminated by a null character (5 6-. $o operate on and manage
strings, you treat them as you !ould any other array, !ith all the inherent difficulties of "eeping trac" of
pointer arithmetic and being careful not to stray off the end of the array.
Strings in Java are objects, and all methods that operate on strings can treat the string as a complete entity.
Strings are not terminated by a null, nor can you accidentally overstep the end of a string (like arrays, string
boundaries are strictly enforced).
1874e/Gao 1
Memory Management
All memory management in Java is automatic; memory is allocated automatically when an object is created,
and a run-time garbage collector (the gc) frees that memory when the object is no longer in use. Cs
malloc() and free() functions do not exist in Java.
To force an object to be freed, remove all references to that object (assign all variables and array elements
holding it to null). The next time the Java gc runs, that object is reclaimed.
Data Types
%s mentioned in the early part of this boo", all Java primitive data types ( char, int, long, and so on
have consistent si7es and behavior across platforms and operating systems. $here are no unsigned data types
as in 3 and 311 (except for char, !hich is a ,8&bit unsigned integer.
$he boolean primitive data type can have t!o values/ true or false. 9oolean is not an integer, nor can
it be treated as one, although you can cast - or , (integers to boolean types in Java.
3omposite data types are accomplished in Java exclusively through the use of class definitions. $he
struct, union, and typedef "ey!ords have all been removed in favor of classes.
3asting bet!een data types is much more controlled in Java# automatic casting occurs only !hen there !ill be
no loss of information. %ll other casts must be explicit. $he primitive data types (int. float, long,
char, boolean, and so on cannot be cast to objects or vice versa# there are methods and special
:!rapper; classes to convert values bet!een objects and primitive types.
Operators
(perator precedence and association behaves as it does in 3. <ote, ho!ever, that the ne! "ey!ord (for
creating a ne! object binds tighter than dot notation (., !hich is different behavior from 311. In particular,
note the follo!ing expression/
new foo().bar;
$his expression operates as if it !ere !ritten li"e this/
(new foo()).bar;
Operator overloading, as in C++, cannot be accomplished in Java. The, operator of C has been deleted.
$he === operator produces an unsigned logical right shift (remember, there are no unsigned integer data
types.
$he 1 operator can be used to concatenate strings.
1874e/Gao 2
Control Flow
%lthough the if, while, for, and do&while statements in Java are syntactically the same as they are
in 3 and 311, there is one significant difference. $he test expression for each control flo! construct must
return an actual boolean value (true or false. In 3 and 311, the expression can return an integer.
Arguments
Java does not support mechanisms for variable&length argument lists to functions as in 3 and 311. %ll method
definitions must have a specific number of arguments.
3ommand&line arguments in Java behave differently from those in 3 and 311. $he first element in the
argument vector (argv[0]) in 3 and 311 is the name of the program itself# in Java, that first argument is
the first of the additional arguments. In other !ords, in Java, argv[0] is argv[1] in 3 and 311# there is
no !ay to get hold of the actual name of the Java program.
Other Differences
$he follo!ing other minor differences from 3 and 311 exist in Java/
Java does not have a preprocessor, and as such, does not have #defines or macros. 3onstants can be
created by using the final modifier !hen declaring class and instance variables.
Java does not have template classes as in 311.
Java does not include 3s const "ey!ord or the ability to pass by const reference explicitly.
Java classes are singly inherited, !ith some multiple&inheritance features provided through interfaces.
%ll functions must be methods. $here are no functions that are not tied to classes.
$he goto "ey!ord does not exist in Java (its a reserved !ord, but currently unimplemented. .ou can,
ho!ever, use labeled breaks and continues to brea" out of and continue executing complex s!itch
or loop constructs.
1874e/Gao 3
So, Wheres the Java?
Now that youve learned a little HTML, youre ready to learn about Java itself. Later, when youve learned about
Java applets, youll see the HTML incantations necessary to add a Java applet to an HTML page.
WHO NEEDS JAVA, ANYWAY?
:'arvelous>; you thin" as you loo" do!n at the soft!are pac"age in your hands. Just !hat youve been loo"ing for
the program that !ill solve all your problems, dry all your tears, fulfill all your dreams. .es, life is truly good.
%nd then you notice the fine print/ :Runs on 'acintosh only;# but your computer runs ?indo!s. If your !orld does
not exactly turn blac" and your blood does not @uite run cold, at the very least you end up frustrated and annoyed.
:?hy cant every computer run the same programsA; you as". Java may !ell be the solution to this problem.
Java is a computer language designed for programming on the Internet. %t the moment, Java has the attention of the
media and the public because of its ability to add action to other!ise lifeless ?eb pages. 'ost people accessing the
?eb do so using a modem and a dial&up connection. ?hile full&motion images of the sort !eve all gro!n to expect
ta"e too long to deliver over a modem, Java allo!s motion by sending still images over the Internet and then
animating them locally, on the same computer that hosts the bro!ser. $his effectively overcomes the band!idth
bottlenec". Bo!ever, the ultimate potential significance of Java extends far beyond such entertaining tric"s.
Javas po!er comes from a ne! sort of portability "no!n as cross-platform binary portability. Crograms !ritten in
3 or Cascal on one type of computer can often be ported to run on a different type of computer. $he cost of doing
this can sometimes be much less than the cost of re!riting the program from scratch. <evertheless, such porting is
often time&consuming and difficult, and fre@uently the results are less than ideal. Dor batch&oriented programs such
as processing payroll or utility bills, such porting is often employed, but in these days of graphical user interfaces,
moving a program from ?indo!s to the 'acintosh or E<IF is often a Berculean tas". %nd, even if the program is
intentionally !ritten to be portable, !hat is actually portable is the source codethe high&level language
instructionsnot the actual executable code. ?hat if you could put that ?indo!s 95 program dis" in your F
?indo! E<IF machine (and vice versa and just have it !or"A
$his is the portability provided by Java. % Java executable !ritten for one computer can be run, !ithout
modification, on another computer supporting Java. $he other computer does not need the corresponding source
code to accomplish this feat# porting it automatic and virtually instantaneous. $his means that users o!ning entirely
different types of computers can do!nload a Java executable from a server and run that executable on their systems
and expect an identical result. Digure , sho!s this process. $he capability of do!nloading a program and executing
it on a variety of computers is expected to lead to entirely ne! "inds of application programs. $his is the true magic
of Java.
1874e/Gao 4
JAVA SOURCE CODE
public my%pplet extends %pplet 2
public void init( 2
label myGabel + ne! Gabel(:Bi;#
add (myGabel#
H
H
Javac
Cseudocode
3ompiler
Java
9ytecodes
?eb 4erver
'%3 I9'
E<IF
Figure 1 Downloa!ing an! E"e#uting a Java $rogra%
1874e/Gao 5
'acintosh
Java virtual
machine
E<IF F ?indo!
Java virtual
machine
?in IJ C3
Java virtual
machine
THE HISTORY OF JAVA
Java began life in ,KK, as a programming language for consumer electronics devices at 4un 'icrosystems, Inc. %t
the time, 4un !as see"ing to diversify its business beyond the very popular E<IF&based !or"stations for !hich the
company is still noted. 4un engineers see"ing to build an intelligent remote control for multihundred&channel cable
$L needed a simple programming language capable of hosting highly reliable soft!are, because nothing is
guaranteed to generate complaints li"e customers having their cable $L go do!n in the midst of a movie.
$he 4un fol"s loo"ed at several alternatives. 9uilding a compiler for an existing language such as 311 seemed to
re@uire too much effort, because the hard!are components of the system changed so fre@uently. Ese of assembly
language !as rejected because of the difficulty of producing reliable soft!are. In the end, the engineers decided to
create a ne! language called Oak, built specifically for their tas". (a" !as based on 311 but lac"ed certain 311
features "no!n to be a common source of programming errors. It also had additional features not found in 311.
Enfortunately for 4un, but fortunately for the rest of us, the anticipated mar"et for intelligent remote controls failed
to appear. $his loo"ed li"e the end of (a". 9ut the engineers !or"ing on the project too" a step bac" and as"ed
themselves, :?hat can !e possibly use this thing forA; 4ome of them loo"ed at the Internet and sa! a uni@ue fit. In
a short period of intense coding they crafted a ?eb bro!ser called HotJava, using (a", !hich they rechristened
Java. BotJava introduced the idea of an applet, a small program that could be do!nloaded from a ?eb server and
executed !ithin an environment provided by a bro!ser. $his early demonstration of the capability for animation of
?eb pages captured the attention of 4un executives, !ho decided to sponsor the Java project.
% preliminary (alpha version of Java and BotJava !as made !idely available over the Internet as part of a free Java
Mevelopers Nit (JMN. 4un reasoned that the only !ay to achieve !ide&scale acceptance of Java as a universal
standard !as to ma"e it available to everyone. $he experiences of users and developers !ho experimented !ith Java
!ere helpful to 4un engineers, !ho released a second (beta version of the JMN that incorporated suggested
improvements and corrections. In ,KK8, <etscape 3ommunications 3orp. announced that support for Java applets
!ould be included in version J.- of its <avigator bro!ser. Gater that year 'icrosoft follo!ed suit by announcing
Java support for its Internet Oxplorer version I.-. $he Java revolution !as on>
THE FEATURES OF JAVA
(ne of the first lessons children learn is to differentiate bet!een types of advertising. $oys that are advertised as
:ne!, exciting, fun, and thrilling; may pi@ue our interest, but the !ords dont actually tell us much. ?hen the box
!e carry home says, :9atteries not included,; :4ome assembly re@uired,; or :Illustration is Ix actual si7e,; !e
@uic"ly and painfully learn that these !ords convey real meaning. ?e normally call the former category
:bu77!ords; because of the emotional reaction they elicit despite their limited semantic content.
$he features of Java !ere described in an early paper !ritten by 4un engineers. P$he Java Ganguage/ % ?hite
Caper.; $his paper defined Java as :a simple, object&oriented, distributed, interpreted, robust, secure, architecture
neutral, portable, high&performance, multithreaded, and dynamic language.; %lthough this torrent of computer&
spea" jargon has often been labeled the :bu77!ord description; and !as doubtless intended !ith tongue in chee", it
nevertheless accurately identifies many of the features of Java that ma"e it so !ell&suited for programming Internet
applications. Gets briefly examine each of these !ords, !ith a vie! to better understanding !hat ma"es Java tic".
Simple
Gets face it, using a phone is simple, but programming a computer is not. 4o, !hen the designers of Java describe it
as a simple language, you really have to as", :3ompared !ith !hatA;
$oday, one of the most popular computer languages is 311 (pronounced :4ea&plus&plus;. $his language !as
developed by %$Q$s 9ell Gabs to bring object&oriented features to its popular 3 language. Mespite its success, 31
1 has been !idely critici7ed for being too complex.
Java, though adopting much of the loo" and feel of 311, is a much simpler language than 311. It has fe!er and
1874e/Gao 6
less&complex constructs, so it is easier to learn.
Object-Oriented
Like C++, Java is an object-oriented language. Object-oriented languages allow the programmer to organize a
program so that it closely models the real world in structure and in the interactions among its components. This is
particularly valuable in implementing applications using the graphical user interfaces popularized in the PC world
by the various versions of Microsoft Windows. Writing an application using a graphical user interface tends to be
much easier by use of an object-oriented language than otherwise.
Distributed
Java !as built !ith the Internet and ?eb in mind. %s do most other languages, Java includes prebuilt components or
libraries that provide important additional capabilities beyond the language itself. Bo!ever, Javas standard libraries
specifically include net!or"&a!are units that greatly facilitate !riting Internet applications. %dditionally, the
building bloc"s of a particular Java application do not have to reside locally, on your des"top machine, as they do
!ith traditional programming languages.
Interpreted
Remember the second generation of programming languagesA (ne of the first advances, after the invention of the
program itself, !as the invention of the program interpreter. Gi"e the early 4hort&3ode and 4peedcode systems, Java
is an interpreted language.
$his means that Javas executable files are composed of so&called bytecodes that are instructions and data relating to
a hypothetical computer called the Java virtual machine. Oach machine that runs a Java program uses a small
program, "no!n as the Java run-time system, to execute the Java bytecodes in your program. $his design is !hat
ma"es it possible to run the same program on a 'acintosh, a 4un, and a C3.
Robust
% robust program is one that does not fail (at least in a catastrophic !ay. If youve used a computer for any length
of time, youre obviously a!are that much modern soft!are lac"s this property. (ne cause of this is the complexity
of modern soft!are systems.
Java contains features that ma"e the tas" of !riting robust soft!are easier. $he designers did this by first omitting
features (found in other languages that are "no!n to cause errors. $hey then added features (such as strong typing
that allo! the developer to discover errors early, rather than after the product is in the customers hands.
Other features in this same vein include automatic memory allocation, garbage collection, and exception handling.
In Java programs, exceptions can be detected and handled according to instructions written by the programmer,
often allowing software to keep working in the face of unexpected problems.
Secure
(ne of the potential terrors of the Internet is the possibility of security breaches viruses that infect your computer,
or hac"ers !ho ta"e advantage of a soft!are glitch to invade your personal cyberspace and ma"e off !ith
confidential information. Java has a multitude of !ays for dealing !ith evildoers !ho !ould try to compromise your
system using a Java program.
Applets, which are Java programs automatically downloaded when a Web page is displayed, are subject to a number
of limitations that are designed to reduce the chance that simply viewing someones page might result in harm to
your system or data. No such system is absolutely reliable and none will ever be; but Java represents the state-of-
the-art in reducing the chances of a disaster.
1874e/Gao 7
Architecture Neutral
This means, of course, that your Java program will work identically whether you run it in a Quonset hut or in a
Georgetown townhouse. No, wait! Thats not what it means at all.
$he !ord architecture in this phrase does not refer to the building in !hich you live, but to the home in !hich your
computer program livesin other !ords, the computer system. Javas bytecodes are designed to be read and
interpretedin exactly the same manneron any computer hard!are or operating system that supports a Java run&
time. <o translation or conversion is necessary.
Portable
%n early form of portability involved carrying media, for example, floppy dis"s, from one system to another.
Cortability became a much larger problem once different sorts of computers !ere interconnected to form the
Internet.
Java programs contain no implementation-dependent aspects, so the result of executing a series of Java bytecodes
should always be the same no matter on what system they are executed. Moreover, the Java run-time system itself,
though it is written in C, is written in a way that simplifies porting the Java run-time to a new computer system.
High Performance
% typical problem !ith interpreted languages is that they are some!hat less efficient than compiled languages. %
program !ritten by use of an interpreted language may run J- to ,-- times slo!er than the same program !ritten by
use of a compiled language.
Java aims at overcoming this problem through the use of a techni@ue "no!n as just-in-time compilation. % just&in&
time compiler is an interpreter that remembers the machine code se@uences it executes corresponding to the input
bytecodes. Baving figured out the proper machine code se@uence once, it doesnt have to figure it out again if the
same code is reexecuted. Instead, it retrieves the memori7ed se@uences and executes them straight a!ay. 4tudies
have suggested that just&in&time compilation may ma"e interpretation of Java bytecodes almost as efficient as native
execution of machine&language code.
1874e/Gao 8
Multithreaded
'ost of us can !al" and che! gum at the same time. %ll of us do many other things simultaneously. 3omputers are
no different. If they are able to perform activities in parallel, the performance of the entire system can be improved.
$his technology is "no!n as multithreading. % multithreaded system can, for example, format a floppy dis" !hile a
user surfs the ?eb using a bro!ser. 'ultithreaded applications allo! you to complete more tas"s in a given time
and to use a systems resources more efficiently.
Bo!ever, developing multithreaded applications in 3 or 311 can be agony, because these languages lac" standard
support for operations necessary to create and control threads. Java includes support for multithreaded applications
as part of its basic library.
Dynamic
Javas program units, classes, are loaded dynamically (!hen needed by the Java run&time system. Goaded classes
are then dynamically lin"ed !ith existing classes to form an integrated unit. $he lengthy lin"&and&load step re@uired
by third&generation programming languages is eliminated.
Thus, when parts of an application you use are updated, you dont have to buy the latest copy. The dynamic nature
of Java allows you as a developer to always have the most up-to-date version of your software available to your
users.
1874e/Gao 9

Vous aimerez peut-être aussi