
By: Grant Palmer
Publisher: Prentice Hall
Pub. Date: April 21, 2003
Print ISBN-10: 0-13-101815-9
Print ISBN-13: 978-0-13-101815-0
Pages in Print Edition: 496
Subscriber Rating: 



[0 Ratings]
Java is an object-oriented programming language. C is not. The C language does not support objects. The closest C comes to defining an object is the struct or union programming constructs. As you probably know, a struct is a collection of named data members. The data members can be of different types. You can declare a struct variable that is a reference to a struct. The values of the struct data members can be accessed by typing the structvariable name, a period, and the data member name.
If you are familiar with using structs, it shouldn't be too great a leap to become familiar with the concept of a class. A Java class is basically just a named block of code that defines a collection of both fields and methods. A class is more self-contained than a struct in that a class can (and should) define all the methods required to manipulate its data members. Java classes can make use of the powerful object-oriented concepts of inheritance, polymorphism, and encapsulation. There are many different types of classes according to whether one or more modifying keywords are applied to them. You can have public and private classes, abstract and final classes. You can nest a class definition inside another class definition
You can create instances of a class. A class instance is also known as an object. You can declare variables that are references to class instances. A class can define a class instance as one of its fields.
Both C and Java define a variety of data types. The types each language supports are shown in [url=]Table 3.1[/url].
Some of the types supported by C are not supported by Java and vice versa. Java does not support signed or unsigned types. All Java integral types (including char) are signed. Java does not use the long double or void type. Java does not support pointers, so there are no pointer or function pointer types in Java. The same can be said of struct and union types.
Java does provide some useful data types that are not provided by C. The boolean type has a true or false value. Using a boolean variable is more convenient than using 0 for false and 1 for true as in C. Java provides the byte type that represents a single byte of data. Because Java is object oriented, you can declare variables that are references to class instances (objects).
When a C variable is declared outside of any function definition it is a global variable and is available anywhere inside a C program. Java does not support global variables. A Java class variable is one that is declared outside of any method definitions and is available anywhere inside the class in which it is declared. Both C and Java support local variables. A local variable is declared inside a method, a for statement, or other block of code and exists only inside the block in which it is defined.
A C program can make use of pointers to directly access locations in memory. Pointers can be used to change the value of a variable and are also routinely used to manipulate arrays. Pointers can be useful in certain situations but can also be dangerous in that pointers have the potential to do bad things such as corrupt memory.
Java does not support publicly accessible pointers. Java has been designed so that there is no reason to use pointers. A Java primitive type variable stores a single value. You can manipulate the value directly. A reference type variable holds the address where a class instance or array is stored. The reference type variable provides all the access you will need.
In C they are called functions. Java calls them methods. Both are named blocks of code that can be called from somewhere else in a program. Functions are the basic building blocks of a C program. Java methods, on the other hand, are always declared inside of a class. Java methods do not have to be prototyped.
A C function declaration includes the return type, function name, and input parameter list. The only modifying keywords that can be applied to a C function are extern, which means the function is defined outside of the current file, or static, which means the function cannot be referenced from other files. The body of the function is enclosed in braces.
Java method declarations contain the return type, name, and input parameter list of the method. The declaration may also include modifying keywords and a throws clause. Java methods are more powerful and versatile than their C counterparts. For one thing, Java methods can be given an access modifier. This keyword defines how and when the method can be accessed by other code. Java methods can be declared to be static, abstract, final, native, andsynchronized. As with C, the body of a Java method is enclosed in braces.
Input arguments are passed to a C function by value, meaning that a copy of the value of the variable is sent to the function. Any changes made to the variable inside the function will not be reflected in the original variable. To have a C function alter the value of the original variable, a pointer to the variable must be passed to the function.
Arguments to Java methods are also passed by value. For arguments representing primitive types, a copy of the argument value is sent to the method. Any changes made to the value inside the method will not be made to the original value. For arguments representing reference types (objects or arrays), a copy of the reference to the location in memory where the data for the object or array is stored is sent to the method. Any changes made to the object inside the method will also be made to the original object.
C functions are called by simply typing the function name and providing the appropriate arguments. The way that Java methods are called depends on where the method call occurs. Inside the class in which they are defined, Java methods can be called by typing the method name and providing the appropriate arguments. Outside of the class in which they are defined, Java methods are called relative to a class instance or the class name depending on whether it is an instance or static method.
While Java and C both start array indices from zero, there is a fundamental difference in the way the two languages treat arrays. With C, an array of a given data type is treated as a sequence of members of that type stored in contiguous locations in memory. The declaration syntax is the data type, the array name, and the size of the array enclosed in brackets.
int data[5];The members of a C array can be accessed using the array name and index or with a pointer to the array. C arrays can be given a fixed size when they are declared or you can create a dynamically allocated array using pointers and themalloc() function.
In Java, arrays are reference types just like class instances. Creating a Java array is a two-step process. You first declare an array variable by specifying its type and name followed by a pair of brackets—
int data[];Declaring an array variable does not allocate any memory for it. The second step in the array creation process is to allocate memory for the array variable using the new keyword followed by the type and size of the array.
data = new int[5];—The two steps can be combined to a single line
int data[] = new int[5];Elements of a C array can be accessed either through the array index or by using a pointer to the array. Because Java does not support pointers, Java array elements are accessed only through indexes. Both C and Java use a pair of brackets around the index of the element to be accessed. For example, to assign the value 45 to the third element of an array named data you would type—
data[2] = 45;When looking at the above syntax, keep in mind that Java array indices start at 0. The first element of the data array would be data[0].
With C, you can define the size of an array when the array is declared. Using pointers, you can also determine the size and dynamically allocate memory for an array at runtime. This can be useful if the required size for the array may vary from run to run in that you don't have to worry about declaring a really large array to cover all possibilities. The downside to dynamic memory allocation is that it is up to the programmer to properly allocate and deallocate the dynamic memory. If memory is not properly deallocated, you can create the dreaded memory leak.
Java does not support explicit dynamic memory allocation and deallocation because a sophisticated memory management system is part of the JVM that executes Java programs. As part of the memory management system, Java uses a mechanism known as the garbage collector that periodically monitors a Java program while it is running. Whenever a variable goes out of scope it is eligible to be garbage collected, meaning that memory assigned to the variable is deallocated and made available for use by some other part of the program. A Java programmer never has to worry about manually deallocating memory.
Exception handling allows you to recover from errors that might occur while your program is running. The C language has no built-in exception handling. If you want exception handling in a C program, you have to do it yourself. User-defined exception handling usually involves a potentially complicated series of if-then statements and user-defined error codes. The exception handling generally has to take place where the exception occurs. In a C program you cannot easily pass the exception handling off to another part of the code.
Exception handling is a part of the Java language. There are a series of classes and programming constructs that allow you to easily build exception handling capabilities into your Java program. You can define your own exception classes for any unique needs that your program might have. Blocks of code are used to catch and process exceptions. What's more, the exception handling can be passed on to another part of the program. The exception handling does not have to be performed where the exception occurs.
Both C and Java have built-in libraries that you can access when writing your programs. The C libraries are somewhat limited in scope and consist mostly of functions and constants. You can import C libraries into your program using#include statements placed at the top of your program.
One of the great strengths of the Java language is the enormous collection of code libraries that you can utilize when developing your programs. The Java libraries are more commonly referred to as the Java Application Programming Interfaces (APIs). The Java APIs cover everything from I/O to GUI development to security and anything in between. The APIs consist of a collection of classes and interfaces organized in groups called packages. You can import part or all of a package into your program by placing import declarations at the top of the program. As well as providing a lot of useful methods and constants, the Java APIs include the class declarations that constitute a rich and sophisticated source of reusable code for your Java applications.
A string is a sequence of characters. Strings are very important when it comes to displaying, naming, and describing data. The C and Java languages represent strings in very different ways. In C, a string is represented by an array of characters. The end of the string is designated as such by the null character '/0'. The C libraries provide functions to manipulate strings such as the strcpy(), strcat(), and strcmp() functions. When dealing with these functions and with C strings in general you often use pointers.
In Java, strings are represented by the String class and as such are treated as any other reference type. The String class defines a large number of methods for creating, manipulating, and modifying strings. Java strings are immutable. Once a String object is initialized it cannot be changed. If a method is used to modify a string, a new String object is created containing the modified string. Both Java and C support the concept of a string literal. Any text surrounded by double quotes is a string literal.
Both the Java and C libraries provide built-in functions to compute absolute value, power, square root, transcendental, trigonometric, rounding, and other mathematical functions. The built-in math capability of the two languages is quite similar, even some of the function/method names are identical. C has some built-in functions that Java does not—the hyperbolic trigonometric and base 10 logarithm functions, for example. Java has some math methods that C does not, the toRadians(), min(), and max() methods for instance. Java takes advantage of method overloading to streamline its math methods. While C has to define three absolute value methods, one for each of three data types, Java only has to define one absolute value method that can take integer or floating point arguments.
Basic printing in C is performed using the printf()and fprintf()functions. These functions print a string to either the console or to a file using format specifiers (%lf, %s, etc.) to convert variable values to strings. The basic print functions in Java are the print() and println() methods. Every Java object has a handy method called toString()that returns a string representation of it.
The I/O functionality in C is rudimentary at best. You spend a lot of time using nonintuitive functions such as scanf(), sscanf(), and gets(). Some of the functions will read a newline character at the end of a line and some will not. These functions also tend to be quite format-specific. You have to specify exactly what variable type is to be read and returned from these functions. It is easy to run into conversion problems between, say, a float and a double. Reading and parsing an input file can be an intricate and error-prone process.
Java has a much improved I/O functionality over that offered by C. Like C, Java uses a stream-based I/O system. A data stream is simply an abstraction that represents a data connection between a source and a destination. Java provides a wide array of specialized I/O stream classes in two general categories. Character streams are designed to read and write character data. The characters can be read in one at a time or an entire line of data can be read in as a String. Byte streams are intended to read and write binary data. The data can be read in one byte at a time or an entire buffer of byte data can be read.
The standard C libraries do not contain any GUI or web-based application capability. Java has entire libraries devoted to GUI development. You can also develop your own custom GUI components. With Java you can write a sophisticated GUI front-end for your scientific and engineering application without having to learn or use another programming language. A brief introduction to Java GUI development is provided in Chapter 26. Java also allows you to develop powerful web-based applications with an extraordinarily powerful set of facilities such as servlets, JavaServer Pages (JSP), and Enterprise JavaBeans (EJBs). An introduction to web-based applications can be found in Chapter 27.
扫码加好友,拉您进群



收藏
