Java vs C (and C++) yellow highlighted - not as good as the other language light blue highlighted - focus point Concept Java Language Type object-oriented C function-oriented; oo not supported C b t s c .h c s C C s Basic program organization class and its methods traditional include file (.h), source file (.c) with C functions File Naming Class.java fileName.c - source code fileName.h - include file Main Program public 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 } variable declaration location Declarations, primitive types, fundamental data structures as you need it globals at the top of the file; locals at the for (int i = 0; i < iLength; i++) beginning of a {} block { body } primitive types character strings int - 4 byte integer long - 8 byte integer float - 4 byte floating pt double - 8 byte floating pt boolean - true or false char - 16 bit Unicode String 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. a { int i; // automatic local variable for (i= 0; i < iLength; i++) { body } } int - usually 4 byte integer long - 4 byte integer float - 4 byte floating pt double - 8 byte floating pt int - where 0 means false and non-zero is true char - 8 bit ASCII (or EBCDIC) 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 byte char szMyStr[50] = "hello"; // the following two declarations s b s / d / s / / s String myStr = "my string"; // result in the same size and value char szLastName[] = {'S', 'a', 'n' , 'd', 'l', 'e', 'r', '\0'}; char szLastName[] = "Sandler"; type[] var = new type[n]; static type[] var = {initList}; global extern and statics -receive memory at program load. Declared at top of source file: public class HelloWorld { static int[] myIntM = {10, 20, 30}; … } automatics - receive memory on {} entry: Safety - out of bounds array.length (If it is declared larger than what was needed, it is like C.) An attempt to reference outside the bounds of an array or string will raise an exception String length string.length must have a separate variable containing the count or some type of special value marking the end. A reference outside the bounds will get unknown data. Assigning outside the bounds will overwrite memory outside the string/array. strlen(szString) Comparing equality of strings Structures instance.compareTo(string) == 0 strcmp(szString1, szString2) == 0 s le s does not support structures. Java language does not support record I/O. define structures: s arrays Occupied length of an array type var[ n ]; s o type var[ n ]; Examples: #include <stdio.h> // globals double dTemperatureM[24]; // ext basis int iCountTemperature = 0; double average() { int i; double sum = 0; for (i=0; i < iCount; i++) { sum += dTemperatureM[i]; } } 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. s k s c Object-Oriented does not support classes OO - class definition fully supported. Definition and source in Class.java file OO - inheritance fully supported, but only one inheritance hierarchy can overload methods; cannot overload operators does not support classes fu C C fu does not support classes c Stream Formatted Printing System.out.printf("average=%6.2f" , average); printf("average = %6.2f", average); Reading from stdin Standard Input is a class, Stdin. int ix = StdIn.readInt(); Use fgets and scanf. Safety - input Record I/O Not an issue Not supported. can overwrite memory fopen, fread, and fwrite provide ability to read and write binary data. OO - overloading I/O int ix; … scanf("%d", &ix); s c s s i c C s FILE *pfileEmployee; pfileEmployee - fopen("employee.dat" , "rb"); … iNumRecRead = fread (&employee , sizeof(Employee) , 1L , pfileEmployee); Invoking a built-in function Parameter Passing - primitives import java.lang.Math; … x = Math.sqrt(y); by value double calculateAvg(int iExam1, int iExam2, int iFinalExam) { return ((iExam1 + iExam2 + 2 * iFinalExam) / 4.0); } cannot pass by address/reference functions and parameter passing #include <math.h> … x = sqrt(y); by 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 s s , iFinalExam , &average); Parameter Passing - arrays passes reference to the array int [] 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. s 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 indirection int 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; } Parameter Passing - structures does not support structures Note: the * in declarations declares pointers. The * in accessing the value is a dereference. by default it passes by value (which makes no sense), but we can also pass by address; unfortunately, the syntax isn't elegant double 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. s Parameter Passing - objects Exceptions passes a reference to the object does not support objects; use structures instead Student::boolean register(Course course) { if (course.isFull) return false; return insert (course); } int register(Student *pStudent , Course *pCourse) { if (pCourse->availSeats <= 0) return (FALSE); return insert (pStudent, pCourse); } A full hierarchy of Exception classes with the ability to raise exceptions. Miscellaneous does not support exceptions. Must use function value. p A t if (token.tokenStr.compareTo(")") != 0) throw new ParseException("Expected ')'"); pointer chasing Memory management Integration with system capabilities Scientific Applications node.left.info Dynamically allocated are automatically freed via garbage collection. Improving Business Applications involving money User Interface Integration Portability of source code Scores (negative): s s Mathematical/scientific/statistical libraries are less available. Performance is not as good as C pnode->pleft->info Programmer responsible for dynamic memory management Unix/Linux system libraries written in C and integrate well with C. C is essential for CS3423 Systems Programming. Excellent availability of mathematical/ scientific/ statistical function libraries. Compiled C performs well. No native decimal numeric types No native decimal numeric types N Integrated with both workstation-based and web tools good Difficult to integrate with UI tools In a g 8 4 good 11 s s