Home | Department of Computer Science



Java vs C (and C++)yellow highlighted - not as good as the other languagelight blue highlighted - focus pointConceptJavaCC++Language Typeobject-orientedfunction-oriented; oo not supportedboth functions and ooBasic program organizationclass and its methodstraditional include file (.h),source file (.c) with C functionstraditional include file (.h),source file (.c) with C functions, class include file(.hpp although some use .h)class source file (.cpp)File NamingClass.javafileName.c - source codefileName.h - include filesame as C andClass.cpp - class source codeClass.h or Class.hpp - class definitionMain Programpublic class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); System.out.println("Command Args"); for (int i = 0; i < args.length ; i++) { System.out.println(args[i]); } System.exit(0); }}#include <stdio.h>int main (int argc, char *argv[]){ int i; // counter for loop printf("Hello World\n"); // print the arguments // argv[0] is the executable's name printf("Command Args\n"); for (i = 1; i < argc; i++) { printf("%s\n", argv[i]); } return 0; // normal return}same as CDeclarations, primitive types, fundamental data structuresvariable declaration locationas you need itfor (int i = 0; i < iLength; i++){ body}globals at the top of the file; locals at the beginning of a {} block{ int i; // automatic local variable for (i= 0; i < iLength; i++) { body }}as you need itprimitive typesint - 4 byte integerlong - 8 byte integerfloat - 4 byte floating ptdouble - 8 byte floating ptboolean - true or falsechar - 16 bit Unicodeint - usually 4 byte integerlong - 4 byte integerfloat - 4 byte floating ptdouble - 8 byte floating ptint - where 0 means false and non-zero is truechar - 8 bit ASCII (or EBCDIC)same as C;bool - true or false character stringsString class// This declares the variable, but// doesn't allocate space for the// actual value.String myStr;// This declares the variable and // assigns it a value.String myStr = "my string";char array with a zero byte('\0') marking the end// this declares a string which is a// max of 49 bytes plus 1 byte for// zero bytechar szMyStr[50] = "hello";// the following two declarations// result in the same size and valuechar szLastName[] = {'S', 'a', 'n' , 'd', 'l', 'e', 'r', '\0'};char szLastName[] = "Sandler";same as C and C++ string class// This declares the variable, but doesn't allocate // space for the actual string.string myString;// This declares the variable and // assigns it a value string myString = "hello";arraystype[] var = new type[n];static type[] var = {initList};public class HelloWorld { static int[] myIntM = {10, 20, 30}; …}global extern and statics -receive memory at program load. Declared at top of source file:type var[ n ];automatics - receive memory on {} entry:type var[ n ];Examples:#include <stdio.h>// globals double dTemperatureM[24]; // ext basisint iCountTemperature = 0;double average(){ int i; double sum = 0; for (i=0; i < iCount; i++) { sum += dTemperatureM[i]; }}same as C or can be allocated when object is dynamically createdOccupied length of an arrayarray.length(If it is declared larger than what was needed, it is like C.)must have a separate variable containing the count or some type of special value marking the end. same as C; C++ has special classes that know their length.Safety - out of boundsAn attempt to reference outside the bounds of an array or string will raise an exceptionA reference outside the bounds will get unknown data. Assigning outside the bounds will overwrite memory outside the string/array. same as C except there are some special classes that do bounds checksString lengthstring.lengthstrlen(szString)same as C; C++ string class provides paring equality of pareTo(string) == 0strcmp(szString1, szString2) == 0same as C; C++ string class provides Structuresdoes not support structures. Java language does not support record I/O. define structures: struct {char szSSN[10];double dHourlyRate;char szName[31]; } Employee employee;An attribute is referenced with dot notation: Employee.dHourlyRate;define structure types using typedef: typedef struct {char szSSN[10];double dHourlyRate;char szName[31]; } Employee;read and write structures using record I/O.same as CObject-OrientedOO - class definitionfully supported. Definition and source in Class.java filedoes not support classesfully supportedClass.cpp - class source codeClass.h or class.hpp - class definitionOO - inheritancefully supported, but only one inheritance hierarchydoes not support classesfully supportedOO - overloadingcan overload methods; cannot overload operatorsdoes not support classescan overload operators and methodsI/OStream Formatted PrintingSystem.out.printf("average=%6.2f" , average);printf("average = %6.2f", average);same as C and C++ only capability:cout << "average = " <<setprecision(2) << setw(6) << average;Reading from stdinStandard Input is a class, Stdin.int ix = StdIn.readInt();Use fgets and scanf.int ix;…scanf("%d", &ix);same as C and C++ only capability:int ix;cin >> ix;Safety - input Not an issuecan overwrite memoryC capabilities can overwrite memoryRecord I/ONot supported.fopen, fread, and fwrite provide ability to read and write binary data.FILE *pfileEmployee;pfileEmployee - fopen("employee.dat" , "rb");…iNumRecRead = fread (&employee , sizeof(Employee) , 1L , pfileEmployee);same as Cfunctions and parameter passingInvoking a built-in functionimport java.lang.Math;…x = Math.sqrt(y);#include <math.h>…x = sqrt(y);same as C and additional classesParameter Passing - primitivesby valuedouble calculateAvg(int iExam1, int iExam2, int iFinalExam){ return ((iExam1 + iExam2 + 2 * iFinalExam) / 4.0);}cannot pass by address/referenceby default it passes by value: double calculateAvg(int iExam1, int iExam2, int iFinalExam){ return (iExam1 + iExam2 + 2 * iFinalExam) / 4.0;}but we can also pass by address:void calculateAvgv2(int iExam1, int iExam2, int iFinalExam, double *pdAverage){ // count the final twice *pdAverage = (iExam1 + iExam2 + 2 * iFinalExam) / 4.0;}the caller:double average;int iExam1, iExam2, iFinalExam;…calculateAvgv2(iExam1, iExam2 , iFinalExam , &average);same as CParameter Passing - arrayspasses reference to the arrayint [] grades = {100, 80, 90};int sum = sumArray(grades);System.out.println("Sum is " + sum);private static int sumArray(int [] grades){ int sum=0; for (int iGrade : grades) { sum += iGrade; } return sum;}C passes arrays by address. The parameter can be declared as an array or a pointer. The caller isn't different for those two options.int grades[] = {100, 80, 90}int iNumGrades = 3;int sum;sum = sumArray(grades, iNumGrades);printf("Sum is %d\n", sum);by address as an array:int sumArray(int iGradeM[], int icount){ int i; int sum = 0; for (i = 0; i < icount; i++) { sum += iGradeM[i]; } return sum;}by address as a pointer; accessing it requires indirectionint sumArray(int *piGrade, int icount){ int i; int sum = 0; int *p; p = piGrade; for (i = 0; i < icount; i++, p++) { sum += *p; } return sum;}Note: the * in declarations declares pointers. The * in accessing the value is a dereference.same as CParameter Passing - structuresdoes not support structuresby default it passes by value (which makes no sense), but we can also pass by address; unfortunately, the syntax isn't elegantdouble calcWage(Employee *pEmployee , double dHours){ return pEmployee->dHourlyRate * dHours;}Note: the * in the declaration declares a pointer to a structure. The attributes in the structure are referenced using a pointer reference (->). Normal references (not via a pointer) to attributes within a structure use dot notation.same as CParameter Passing - objectspasses a reference to the objectStudent::boolean register(Course course){ if (course.isFull) return false; return insert (course);}does not support objects; use structures insteadint register(Student *pStudent , Course *pCourse){ if (pCourse->availSeats <= 0) return (FALSE); return insert (pStudent, pCourse);}pass by addressMiscellaneousExceptionsA full hierarchy of Exception classes with the ability to raise exceptions.if (token.pareTo(")") != 0) throw new ParseException("Expected ')'"); does not support exceptions. Must use function value.A full hierarchy of Exception classes with the ability to raise exceptions.pointer chasingnode.pnode->pleft->infosame as CMemory managementDynamically allocated are automatically freed via garbage collection.Programmer responsible for dynamic memory managementsame as CIntegration with system capabilitiesImprovingUnix/Linux system libraries written in C and integrate well with C.C is essential for CS3423 Systems Programming.same as CScientific ApplicationsMathematical/scientific/statistical libraries are less available.Performance is not as good as CExcellent availability of mathematical/ scientific/ statistical function piled C performs well.same as CBusiness Applications involving moneyNo native decimal numeric typesNo native decimal numeric typesNo native decimal numeric typesUser Interface IntegrationIntegrated with both workstation-based and web toolsDifficult to integrate with UI toolsIntegrated with both workstation-based and web toolsPortability of source codegoodgoodgoodScores (negative):8114 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download