没有合适的资源?快使用搜索试试~ 我知道了~
首页C语言与Java对比:关键特性和选择理由
C语言与Java对比:关键特性和选择理由
需积分: 10 2 下载量 27 浏览量
更新于2024-07-18
收藏 9.92MB PDF 举报
本资源主要聚焦于将C语言与Java这两种编程语言进行比较和介绍,特别关注于C语言对Java程序员可能有帮助的知识点。首先,"AHistoryLesson"部分可能会回顾C语言的历史,强调其在计算机科学发展中的地位,为理解两者的差异提供背景。"HighLevelDifferences"章节详细比较了C语言与Java在代码编译方式(编译 vs. 解释执行)、安全性和健壮性、多线程支持以及API设计的不同。 C++语言被提及,因为它是C语言的扩展,"TenReasonsToUseC++"列出了选择C++而非C的原因。包括C++的广泛使用、模板技术、操作符重载、标准模板库(STL)、资源自动回收、条件编译控制、访问器与修改器的区别、多重继承的实现方式、空间效率优化,以及私有继承的特点。这些特性展示了C++在性能、灵活性和面向对象编程上的优势。 "Chapter1BasicTypesandControlStructures"则涵盖了基础类型(如整数、浮点数、字符和布尔类型)的介绍,以及C语言和Java在语法结构上的不同,比如运算符和表达式、条件语句、循环结构以及C语言的定义明确赋值规则。此外,还介绍了额外的主题,如预处理器和`using`指令,以及如何在初学阶段编写简单的程序并输出结果。 通过深入解析这些章节,Java程序员可以更好地理解C语言的特性和用法,以便在需要时能够利用C语言的优势或者在两者之间做出明智的选择。同时,对于C语言开发者来说,了解Java的特性也有助于他们了解现代软件开发中的多样性,并根据项目需求灵活运用。
资源详情
资源推荐
A History Lesson 3
In parallel with the standardization of C was an effort by Bjarne Stroustrup to create a
more object-oriented approach to using C. Eventually C++ emerged, and then eventually C++
underwent a standardization process.
C++ should be viewed as a completely new language, based largely on C. It includes mod-
ern constructs to support object-oriented programming. Several design issues have greatly influ-
enced C++.
First and foremost, C++ was intended to be upward compatible with C, as much as possi-
ble. Thus legal C programs should be legal C++ programs, though this is not 100% true. (Obvi-
ous exceptions include C programs that use as identifiers any reserved word that was added to
C++, such as class.) As a result, numerous constructs from C that perhaps we could live with-
out are part of C++, as is the entire idea of using pointers to do arrays. Additionally, because
each new reserved word breaks existing code, the C++ community is reluctant to add new
reserved words, preferring instead to overuse existing words, such as const and static. So
whereas Java has throw and throws, in C++ we simply use throw both to throw an excep-
tion and to list exceptions.
The second crucial philosophy of C++ was in part political: C++ programs should be as
fast as C programs if they do the same thing. Otherwise, it was thought, nobody would want to
learn a more complicated language, just to write slower code. As part of this philosophy, in C++,
if you do not use a feature, you should not have to pay a cost a runtime. Among other things, this
still means, no runtime bounds checks, no dynamic dispatch by default, and no garbage collec-
tion.
The third thing to know about C++ is that it has continually evolved. The first widely-used
version of C++ supported classes and inheritance. Templates, discussed in Chapter 7, were
added later. Exceptions were added even later. At another time came namespaces. The templates
got fancier, with templates inside of templates. This has lead to compilers being perennially
behind the official specification, buggy with new features, and especially bug-prone when sev-
eral new features are used at the same time, much to the chagrin of programmers and textbook
authors. Fortunately, C++ has more or less stabilized and the latest compilers are quite good at
meeting (and in some cases doing more than required by) the language specification.
Java was developed by Sun Microsystems, and marketed as a modern alternative to C++.
Thus, cosmetically, there are many similarities. However, the designers of Java had (at least)
two main goals. First, they attempted to allow the programmer to write the same set of programs
that C++ allows, using simpler syntax. In cases where C++ has several ways to do the same
thing, Java attempts to pick the idiom most widely endorsed by the C++ community and support
it with a language feature. In cases where C++ features are abused, Java does not allow the fea-
ture. Thus some C++ features are not found in Java. Second, they have attempted to make it
harder for incorrect code to run, requiring the compiler to detect many sets of errors when it first
compiles the program, and then the Virtual Machine to throw an exception when bad things hap-
pen at runtime. By detecting most occurrences of bad behavior, not only are honest program-
c++book.mif Page 3 Saturday, July 12, 2003 10:53 AM
4 Chapter 0 • Introduction
ming errors avoided, system security against hacking is enhanced, since hacking generally
works by having the system do something it is not designed to do.
The Java designers have several advantages. First, in designing the language, they can
expect the compiler to work hard. We no longer use PDP-11s, and compiler research has
advanced greatly to the point that modern optimizing compilers can do a terrific job of creating
code, without requiring the programmer to resort to various tricks common in the good old days.
Second, Java designers specified most of the language (classes, inheritance, exceptions) at once,
adding only a second minor revision (inner classes), with most changes after Java 1.1 dealing
with the library. In doing so, they were able to have language features that don’t clash.
Although Java is the new kid on the block (unless C# becomes the next new kid), and has
lots of nice features, it is certainly not true that Java is better than C++, Nor would we say that
C++ is better than Java. Instead, a modern programmer should be able to use both languages, as
each language has applications that can make it the logical choice.
0.2 High Level Differences
As we just described, Java and C++ have different views of the world. C++’s main priority is
getting correct programs to run as fast as it can; incorrect programs are on their own. Java’s main
priority is not allowing incorrect programs to run; hopefully correct programs run reasonably
fast, and the language makes it easier to generate correct programs by restricting some bad pro-
gramming constructs.
0.2.1 Compiled vs. Interpreted Code
Java consists of both a compiler and a Virtual Machine. The compiler generates Java bytecode,
and the bytecode is then interpreted at runtime. As a result, not only is Java code portable, the
compiled bytecode is portable and in theory can be run on any platform.
On the other hand, a C++ compiler generates native code. The C++ language specification
provides no guidance on the specifics of what the native code looks like, so not only is the result
of the compilation not transferable to a different type of computer, parts of a single program that
are compiled on the same computer by different compilers are almost always not compatible
with each other.
Originally, the difference between compiled code and interpreted code meant that C++
was as much as 50 times faster than Java. Recent improvements in the Java compiler, and more
importantly, the Virtual Machine have dramatically closed the gap. In some cases, Java code
may actually be faster than C++, but generally speaking, one would expect that since C++ does
less runtime checks than Java, equally skilled compiler writers should be able to generate some-
what faster C++ code than Java code, assuming similar coding styles.
0.2.2 Security and Robustness
We have already seen that Java is very concerned with not allowing unsafe code to compile, and
with throwing exceptions at the first sign of trouble. C++ is unfortunately, somewhat lax in this
c++book.mif Page 4 Saturday, July 12, 2003 10:53 AM
High Level Differences 5
regard. C++ suffers several problems that can never occur in pure Java code. Four that stand out
are the following:
First, it is possible in C++ to have a pointer or reference to an object that has been returned
back to the memory heap, which is a sure disaster. This is because standard C++ does not do gar-
bage collection; instead the programmer must manage memory themselves, and programmers
are surprisingly bad at doing so. However, some C++ systems include garbage collection and
add runtime checks to avoid using stale pointers. These systems are quite close to the Java stan-
dard of avoiding memory problems.
Second, Standard C++ does not check array indexes, and a common hacker attack is to
find an input routine that reads a string, but doesn’t check that there is enough space for a very
very long string. By judiciously passing a huge string, the hacker can overflow the buffer, writ-
ing replacement values onto variables that are stored in memory adjacent to the buffer. Although
this could never happen in Java, since the C++ specification does not disallow bounds checks,
there is no reason that a safe C++ system couldn’t check array bounds. It would simply be
slower (but safer) than a competitor, and so it is not widely done by default.
Third, old C++ typecasts allow type confusion, in which a type is cast to an unrelated type.
This can never happen in Java, but is allowed in C++.
Fourth, in Java, all variables have a definite assigned value prior to use of their value. This
is because variables that are not local to a method by default are initialized to zero for primitives
and null for references. For local variables, an entire chapter of the Java Language Specifica-
tion is devoted to definite assignment, whereby the compiler is required to perform a flow analy-
sis and produce an error message if a local variable cannot be proven (under a long set of rules)
to have been definitely assigned to through all flows of the method. In C++, this behavior is not
required. Rather, a program that uses an uninitialized variable is said to be incorrect, but the
compiler is not required to take any particular action. Most C++ compilers will print warning
messages if uninitialized variables are detected. But the program will still compile. A similar
story occurs in the case of having a flow that fails to return a value in a non-void function.
0.2.3 Multithreading
C++ does not support multithreading as part of the language. Instead, one must use a set of
library routines that are native to the particular platform. Although Java supports multithreading,
the Java memory model and threading specification has recently been discovered to be inade-
quate and is undergoing revision.
0.2.4 API Differences
The Java API is huge. The core library includes, among other things, the Swing package
javax.swing for designing (mostly) portable GUIs, a networking package in java.net,
database connectivity in java.sql, built-in compression, serialization, and other I/O in
java.util.zip and java.io, reflection in java.lang.reflect, and even support for
remote methods, servlets, and XML.
c++book.mif Page 5 Saturday, July 12, 2003 10:53 AM
6 Chapter 0 • Introduction
Standard C++ has a very small API, containing little more than some I/O support, a com-
plex number package, and a Collections API, known as the Standard Template Library (STL).
Of course, compiler vendors augment Standard C++ with huge libraries, but each vendor has
different versions rather than implementing a single standard.
0.3 Ten Reasons To Use C++
The preceding section might leave one to conclude that C++ has little to offer. This is not true;
there are lots of reason why one would want to learn and use C++. In this section we list ten
advantages of using C++, including features found in C++ that are not found in Java. Figure 0-1
summarizes the differences described in both Section 0.2 and this section, as well as a few dif-
ferences that are described later in this text, but not otherwise mentioned in this chapter.
0.3.1 C++ Is Still Widely Used
Perhaps the most important reason to learn C++ is that it is still very-widely used, and since it is
a more complex and difficult language than C++, it is likely that there will always be a strong
market for knowledgeable C++ programmers.
0.3.2 Templates
Perhaps the most requested missing feature in Java is the equivalent of the C++ template. In
C++, templates allow the writing of generic, type-independent code, such as sorting algorithms
and generic data structures that work for any type. In Java, this is done by using inheritance, but
the downside is that many errors are not detected at compile time, but instead linger until run
time. Further, using templates in C++ seems to lead to faster code than the inheritance-based
alternative in Java. Generics are under consideration for Java 1.5. Template are discussed in
Chapter 7.
0.3.3 Operator Overloading
Java does not allow the user to defined operators for class types. C++ does, and this is known as
operator overloading. We discuss operator overloading in Chapter 5.
0.3.4 Standard Template Library
C++ provides a large library, known as the Standard Template Library (STL) for data structures
and generic algorithms. The STL has several advantages compared to the Java Collections API,
and we discuss these differences in Chapter 10.
0.3.5 Automatic Reclamation of Resources
Although Java provides garbage collection, which is a fantastic feature, it is hard to control the
management of other resources. For instance, in Java, the programmer must remember to close
files and database connections when they are no longer in use, dispose of graphics contexts, and
c++book.mif Page 6 Saturday, July 12, 2003 10:53 AM
Ten Reasons To Use C++ 7
so on. Although many (non-memory) resources are released by object finalization, relying on
object finalization in Java is a poor idea, since objects need not be reclaimed if the garbage col-
lector deems that memory is not low.
Figure 0-1 Differences between Java and C++
Feature Java C++
Compiler output Virtual machine bytecode native code
Portability Hi Moderate
Garbage collection Yes No
Checks array indices Yes No
Multithreading Yes Platform specific
API Huge Small
Security checks Yes No
Compiler checks Numerous Some
Operator overloading No Yes
Templates No Yes
Multiple Inheritance Interface only Yes
Standard GUI library Yes No
Data Structures Collections API STL
Exception Handling Yes Yes, but poorly integrated
Conditional Compilation No Yes
Global Functions No Yes
Class grouping Packages Namespaces
Pointer variables No Yes
Class documentation Javadoc Not in standard
Reflection Yes No
Space efficient Not really Yes
c++book.mif Page 7 Saturday, July 12, 2003 10:53 AM
剩余289页未读,继续阅读
兔老弟
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 多模态联合稀疏表示在视频目标跟踪中的应用
- Kubernetes资源管控与Gardener开源软件实践解析
- MPI集群监控与负载平衡策略
- 自动化PHP安全漏洞检测:静态代码分析与数据流方法
- 青苔数据CEO程永:技术生态与阿里云开放创新
- 制造业转型: HyperX引领企业上云策略
- 赵维五分享:航空工业电子采购上云实战与运维策略
- 单片机控制的LED点阵显示屏设计及其实现
- 驻云科技李俊涛:AI驱动的云上服务新趋势与挑战
- 6LoWPAN物联网边界路由器:设计与实现
- 猩便利工程师仲小玉:Terraform云资源管理最佳实践与团队协作
- 类差分度改进的互信息特征选择提升文本分类性能
- VERITAS与阿里云合作的混合云转型与数据保护方案
- 云制造中的生产线仿真模型设计与虚拟化研究
- 汪洋在PostgresChina2018分享:高可用 PostgreSQL 工具与架构设计
- 2018 PostgresChina大会:阿里云时空引擎Ganos在PostgreSQL中的创新应用与多模型存储
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功