Java for C++ Programmers - PowerPoint PPT Presentation

java for c programmers n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Java for C++ Programmers PowerPoint Presentation
Download Presentation
Java for C++ Programmers

play fullscreen
1 / 94
Java for C++ Programmers
189 Views
Download Presentation
brody-thornton
Download Presentation

Java for C++ Programmers

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Java for C++ Programmers First Night

  2. Overview • First Night • Basics • Classes and Objects • Second Night • Enumerations • Exceptions • Input/Output • Templates vs. Generics • STL vs. JavaSE API

  3. First Night Agenda • Basics – file structure, compilation & execution differences, standard out/err/in, primitive types, constants, functions, strings, reference types, arrays, passing variables, command line arguments, packages • Discussion • Lab exercises • Break • Classes & Objects – declaration, instantiation, access modifiers, members, methods, common methods, inheritance, interfaces, javadoc • Discussion • Lab exercises

  4. C++ File Structure • We typically have header files (*.h, *.H *.hpp) and a source file (*.c, *.C, *.cpp) • There is no coloration between the name of the file and the classes (if any) defined within

  5. C++ Example – factorial.H #ifndef _FACTORIAL_H_ #define _FACTORIAL_H_ intfactorial(int n); #endif

  6. C++ Example – factorial.C #include"factorial.H" intfactorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result; }

  7. C++ Example – example1.C #include<iostream> #include"factorial.H" usingnamespace std; intmain(int argc, char** argv) { int n = 4; cout << "factorial(" << n << "): " << factorial(n) << endl; exit(0); }

  8. Java File Structure • No separate header file – all code is in a *.java file • No duplication of method signature in declaration (*.H) and definition (*.C) to keep in sync • No guarding of files to prevent against multiple includes • A file must contain a class of the same name • By convention files/classes start with a capital letter • Enforced consistency • No code lives outside of any class

  9. Java Main Signature • Main signature is a bit different • No return value • Only 1 argument to main – a String array publicstaticvoid main(String[] args)

  10. Java Factorial Example publicclass Factorial { publicstaticvoid main(String[] args) { int n = 4; System.out.print("factorial("); System.out.print(n); System.out.print("): "); System.out.println(factorial(n)); } staticint factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result; } }

  11. Compilation in C++ is done by compiling each of the *.C files, to produce *.o files The object files are then linked to create an executable which can be run directly a.out example1.o factorial.o example1.C factorial.H factorial.C C++ Compilation To run: a.out g++ example1.o factorial.o g++ -c example1.C g++ -c factorial.C

  12. Java Compilation • In Java, *.java files are compiled into *.class files • These *.class files contain what is known as “bytecode” • Bytecode does not get run directly • Bytecode is not linked to produce an executable • Instead, this bytecode is interpreted and executed by another program known as the Java Virtual Machine (JVM) • Bytecode can be run on any platform having a JVM

  13. *.java files are compiled using the javac command The class files are then executed using the java command Note no .class specified when running Factorial.class Factorial.java Java Compilation & Execution To run: java Factorial javac Factorial.java

  14. Standard In/Out/Error • Like C++, Java automatically creates streams for stdout, stdin and stderr • cout is equivalent to System.out • cerr is equivalent to System.err • cin is equivalent to System.in • Unlike C++, no imports or includes need to be made to use these streams

  15. Standard Out/Error • Output is easily done using one of the print methods off of these objects • System.out.print(arg) – prints the arg • If you want a newline (what you would get by using endl), use the println variant of this function – System.out.println(arg) • A detailed list of methods available on System.out or System.err can be found at: • http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html#method_summary

  16. Standard In • Like C++, Java automatically creates a stream for stdin • cin is equivalent to System.in • Unfortunately, reading a given type off of System.in is not as easy as using cin in C++ • Typically another class is used in conjunction with System.in to more easily read values off of the stream

  17. Primitive Types • Like C++, Java has a built-in boolean type • C++ uses the keyword bool, whereas Java used the keyword boolean • Both use the values true and false • Unlike C++, you cannot assign non-boolean types into booleans • boolean x = 1 results in a compiler error

  18. Primitive Types • Like C++, Java defines a character type • Just like C++, Java uses the char keyword to declare this type • Character literals are defined using single quotes such as 'a'

  19. Primitive Types • Integer types are pretty much the same, both provide the following types • A C++ short int is a Java short • A C++ int is a Java int • A C++ long int is a Java long • There are no unsigned variants in Java • Unlike C++, if you want to assign a higher precision number into a lower precision container you must explicitly down cast… int i = 1234567; short s = (short)i;

  20. Primitive Types • Like C++, Java has both float and double types • The same down casting rules that applied with integer types applies to doubles and floats also • So if you want to assign a double into a float you must cast it to be a float • Additionally, Java assumes that floating point literals are doubles by default • If you want to create a literal you can tack on an “f” to the literal to declare it of a float type float f = 1234.5678f;

  21. Constants • Constants in C++ are typically done in one of two ways… • A #define • Or, a const declaration #define PI = 3.14159; constdouble PI = 3.14159;

  22. Constants • Java does not have a traditional pre-processor to do substitutions like C/C++ • Thus it uses an approach similar to the const declaration • Constants in Java are typically declared to be public static final • Declared inside a class, outside all methods publicstaticfinaldoublePI = 3.14159;

  23. Functions • C++ allows non-member functions • Java does not allow non-member functions • All functions in Java are actually methods • Methods may be made static, essentially making them equivalent to functions staticint factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result; }

  24. Strings • Java provides a String class much like the string class in the C++ STL • Similarities… • Can create by simply using a double quoted string • Concatenation is done using the + operator • Length obtained by calling .length() method • Some notable differences… • No overloaded [i] operator, use the .charAt(i) method instead • Strings in Java are immutable • For more documentation on Java strings see: • http://java.sun.com/javase/6/docs/api/java/lang/String.html

  25. Strings • Since Strings are immutable a new String is created on all operations • Need to be sure to assign result back into variable, otherwise result of operation is lost String s = "foo"; s = s + "bar" + "baz"; s = s.substring(3); System.out.println(s); s = s.replace("b", "B"); System.out.println(s);

  26. Reference Types • The way Java handles reference (non-primitive) types in Java is very different from that of C++ • A reference is kind of like a pointer in C++, but there are some notable differences • All objects are stored in variables are actually references to objects • No direct access to the underlying memory, including no pointer arithmetic • References are strongly typed unlike C++, cannot assign a Date reference into a String reference • Uninitialized references are set to null (lowercase)

  27. Reference Types • In C++ we can statically create an object like so… • Or, dynamically create an object like so (and need to remember to free it like so)… • In Java, we create an object like so… Foof(); Foo * fPtr = new Foo(); delete fPtr; Foo f = new Foo();

  28. Reference Types • If you’re using new, then it’s a reference • One of the biggest perks about Java’s approach to references deals with freeing objects • You don’t! No more delete statements. • Java uses a technique called “Garbage Collection” to automatically free memory which is no longer in use

  29. Arrays • Arrays are allocated using the new keyword • Primitives are initialized to zero • The boolean type is initialized to false • References are initialized to null • Unlike C++, arrays in Java are objects • The length of an array can be determined by looking at the array’s .length member (not a method!) • Like C++, indexing is supported via square brackets – array[i]

  30. Array Allocation // example declarations int[] intArray = newint[10]; boolean[] boolArray = newboolean[10]; // note [] may appear before of after, // before is the more popular Java convention String[] strArray1 = new String[10]; String strArray2[] = new String[10]; // may alternately use curly brace syntax String[] strArray3 = {"foo", "bar", "baz"};

  31. Enhanced For Loop • Java 5 introduced a number of new features to the language – one of those is an enhanced for loop • This style for loop is known as a “foreach” loop • Popular looping construct in many languages: PHP, JavaScript, Perl, Python, Ruby, shell, etc… • C++ does not have a built in equivalent • Typically a foreach loop is used in place of a traditional for loop when we do not care about the index as we are iterating over the collection

  32. Enhanced For Loop • The general format of this loop in Java is as follows… • An example… for(Type item : Collection) { // do something with item } for(int i = 0; i < array.length; i++) { System.out.println(array[i]); } // becomes... for(String s : array) { System.out.println(s); }

  33. Passing Variables • Everything in Java is passed by value • Yes, everything – no goofy & or * notation • Does this mean passing an array of 1,000,000 items creates another huge array? • No! In the case of an array or object, the variable represents a reference, so the reference is being passed by value • So, when dealing with objects, we are always passing references (but by value)

  34. Passing Variables publicclass Test { publicstaticvoid main(String[] args) { int[] array = newint[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? } staticvoid zeroArray(int[] array) { for(int i = 0; i < array.length; i++) { array[i] = 0; } } }

  35. Passing Variables publicclass Test { publicstaticvoid main(String[] args) { int[] array = newint[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? } staticvoid zeroArray(int[] array) { array = newint[array.length]; } }

  36. Command Line Arguments • Now that we know that how arrays are passed we can go back make use of command line arguments • Remember main takes a String array, so we can access that like any other array… publicstaticvoid main(String[] args) { for(String s : args) { System.out.println(s); } }

  37. Packages • Like C++, Java provides a mechanism to organize code • Packages are similar to namespaces in C++ but have different syntax and conventions • In Java classes need not be explicitly be under a package, in which case the default package will be used • Though, this practice is discouraged

  38. Namespaces in C++ namespace A { classFoo { // minimal class }; } intmain(int argc, char** argv){ A::FooaFoo(); return 0; }

  39. Packages in Java • To package a class… • The first line in the Java file should be a package declaration in the following format… • The class file should be placed in a directory structure matching the package name… • foo/bar/baz/Foo.java package foo.bar.baz;

  40. Packaging Conventions • Typically package names consist of lowercase letters and/or numbers • Multiple words are usually separated by periods • In the real world most projects use something called reverse domain name notation • edu.umbc.dhood2.proj1.ClassName • Use this as another method to group your code into logical chunks

  41. Using a Package • Using a file in a package is very similar to that of C++ • In C++ we might have something like… • In Java, the syntax is different – we use the import keyword, drop the angle brackets, and the file extension #include<sys/socket.h> import java.util.Date;

  42. Exercises Using Java, create, compile and run… • A simple “Hello World” program • A program which takes a single string as a command line argument prints out whether or not the string is a palindrome • Palindrome is a word that reads the same backwards as forwards • A program which creates an array of 20 integers, fills it with the Fibonacci sequence and prints it out • Fibonacci[0] = 1, Fibonacci[1] = 1 • Fibonacci[n] = Fibonacci[n-2] + Fibonacci[n-1]

  43. Break

  44. C++ Class Declaration #ifndef _DATE_H_ #define _DATE_H_ classDate { private: intm_month; intm_day; intm_year; public: Date(int month, int day, int year); intGetMonth() const; intGetDay() const; intGetYear() const; voidSetMonth(int month); voidSetDay(int day); voidSetYear(int year); }; #endif

  45. #include"Date.H" Date::Date(int month, int day, int year) { this->m_month = month; this->m_day = day; this->m_year = year; } intDate::GetMonth() const { returnthis->m_month; } intDate::GetDay() const { returnthis->m_day; } intDate::GetYear() const { returnthis->m_year; } voidDate::SetMonth(int month) { this->m_month = month; } voidDate::SetDay(int day) { this->m_month = day; } voidDate::SetYear(int year) { this->m_year = year; } C++ Class Definition

  46. Java Differences • Since Java doesn’t split the declaration and implementation, all code is inline • No semi-colon at the end of the class declaration • Access explicitly attached to each method • this is not a pointer, but a reference, so we use the this. instead of this-> notation

  47. Java Naming Conventions • Class name are in UpperCamelCase • Member names are lowerCamelCase • Method names are lowerCamelCase

  48. publicclass Date { privateintmonth; privateintday; privateintyear; public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; } publicint getMonth() { returnthis.month; } publicint getDay() { returnthis.day; } publicint getYear() { returnthis.year; } publicvoid setMonth(int month) { this.month = month; } publicvoid setDay(int day) { this.day = day; } publicvoid setYear(int year) { this.year = year; } } Java Class Declaration & Definition

  49. C++ Method/Member Access • Private: • Only accessible from within the class or by friends • Protected: • Accessible from within the class, and by derived classes • Public: • Accessible by any anyone

  50. Java Access Modifiers • Java member access is different from that of C++, some notable differences • No friend classes • Addition of 4th type, default (also known as package private)