[java] code...

Started by
5 comments, last by elis-cool 22 years, 1 month ago
Could someone please post up some code in Java and then in C++ so I can see the differences... Also if I learn Java in uni and I already know C++ would it be difficult to learn one or to not forget the other with learning Java?
[email=esheppard@gmail.com]esheppard@gmail.com[/email]
Advertisement
The nice thing about basic going from C++ to Java is the basic syntax is identical. Most basic syntax (for, if, while, do... while, arithmetic operators, calling methods, and creating new objects with the new keyword) all basically the same.

Java has many differences though. For example, EVERYTHING in Java is contained within a class. Even in a simple "Hello World" program, you still need to include the code within a class:

HelloWorld.java

  import java.lang.*;publicclass HelloWorld{	static public void main ()	{		System.out.println("Hello World!");	}	}  


A few things about this program. First, all source code is saved with a *.java extension. After that, you compile it with the javac compiler witch smashes the source code into a compact form called Bytecode, which is relatively close to machine code. From there, you have to run the program with the command:
java HelloWorld
Which starts the Java Virtual Machine.

About the code itself, here are some main things you might like to know. It starts out with the line "import java.lang.*;" This is somewhat similar to the #include directives, in that you use them to add functionality to your code. Instead of libraries, Java uses a system of "packages". Java has a very convenient and large standard library of packages from which you can use. The main package is java.lang which contains such classes as java.lang.System, java.lang.String, and java.lang.Thread. All standard library documentation is given at:
http://java.sun.com/j2se/1.4/docs/api/index.html
Also, note that since java.lang is such a common package, it is AUTOMATICALLY imported for all your Java programs (thus importing it as I did is redundant).

The next few lines read "public class HelloWorld". The "public" keyword here indicates it may be used by any other class. Class names should be written with the first letter capitolized for easy recognition. After that comes the code that makes up the class within delimiting brackets {...} Unlike in C++, classes do NOT end in a semicolon (

After that comes the main method (in Java the word method is used over function... doesn''t it sound a lot better?). Unlike the ANSI C++ "int main ()", Java uses a "static void main ()". The "static" keyword is functionally the same as the C++ "static" keyword and is required for your main method because the initial method in your program DOES NOT belong to an object (Applets, on the other hand, do, and are slightly different from applications). One last note on the main method... for querrying command line, you can add the argument "String[] args" (an array of String objects called "args"). "args" starts with the first word after the
java ClassName
line in the command console and delimits each String with a space. To find out the total number of elements in the array, you can say:
args.length
since Java arrays have a built-in "length" member which returns the number of elements in the array. Very useful.

Then we have the pride and joy of the HelloWorld program:
System.out.println("Hello World!");
Instead of "cout << ", Java uses a bit more difficult command. System.out.print and System.out.println are the two commands we have for basic console output (println also returns a new line after outputting the text). So the program just prints "Hello World" to the console, goes to the next line, and terminates. Unfortunately, Java has no easy to use "cin >>" equivalent. You either have to make your own function using the System.in method (but you have to know a little about the java.io package first) or you can use a Swing dialog box:

javax.swing.JOptionPane.showInputDialog(String promptMessageHere);
* Note: You can reffer to a class by either adding the package extension before the class name, or as I showed earlier, importing that class (import javax.swing.JOptionPane or the entire package (import javax.swing.*

Neither "cin >> " or the Swing dialog box are very good with their input though. "cin >>" cuts off after the first space and you have to be careful with the dialog box because it returns "null" if no string is entered (BTW, "null" is a predefined keyword in Java).

There are many other differences from C++ such as:

* All members of a class must be marked with "private", "public", or "protected". You cannot simply put "private:" like in C++.

* All member methods are defined directly beneith their prototype. You don''t have to worry about referencing a method or variable before it''s defined either, because the Java compiler automatically defines all the members of a class before instanciating them. (a major reason I can''t stand using C++)

* You can''t override operators.

* You can''t chose between passing parameters as value parameters and reference parameters; primative data types always pass by value and Objects always pass by reference.

* GUI programming with the AWT and SWING packages are a hella lot easier to learn that Microsoft''s confounded system with all it''s WORDs and Long pointers to pointers =-| With Java, you just create a JFrame, change the window name and size, slap on a panel, and then customize the panel as you wish.

* Inheritence is marked by adding:
extends SuperClass
after the class definition (where SuperClass is the name of the actual super class). I prefer to add this to the line right undernieth the class definition to make for easy readability.


* The "=" operator DOES NOT copy objects, but rather reassigns them as if they were pointers. To copy an object, you must make a class that implements the java.lang.Clonable interface and then use the clone() method of your objects to replicate themselves.

* You CANNOT use the "==" operator in conditional statements. No more stupid errors with confusing "=" and "==". Thank God =-)

* Static members of a class work the same as in C++, but instead of referencing them with "ClassName::staticVar", you simply use the "." operator: "ClassName.staticVar"

* Static methods are very useful in Java, unlike C++, since you can''t have any "outside" methods in Java that are defined outside of the class. Instead, you use static methods which you can invoke without first obtaining an Object of that class.

* There''s no multiple inheritence in Java. Instead, we have things called Interfaces, which are like abstract classes that can ONLY define abstract methods AND NO MORE.

* To conform to an interface, you add the line:
implements MyInterface
after the class definition in a similar way to inheriting from a class. You can also implement multiple interfaces by joining them with commas (,):
implements Interface1, Interface2, Interface3
In addition, your class must define all methods required by the interface to use it. Failing to define an interface-required function will result in a compile-time error.

* You write your own interface in a similar manner as you write your own classes:
public interface MyInterface {...}
However, all methods described in Interfaces are automatically "private" and do not require you to supply that keyword. You may also define constant variables (isn''t that an oximoron?). The "const" keyword is replaced by "final" but works in pretty much the same way. It is occasionally helpful to write an interface for the sole purpose of defining constants, since, unlike C++, a constant defined in a class is restricted to use only in that class.

* The question of why we need interfaces take some time to get used to. Remember, though, implementing an Interface, like inheritence, creates an "is-a" relationship. For example, if you have a class called "Bomb" that implements "Explosive", you can say:
Explosive myBomb = new Bomb();
and more importantly, since the Explosive interface forces all implementing classes to define a set of methods, you are guaranteed that any Explosive object can invoke those methods:
myBomb.explode();
This may not seem like much now, but it really helps in practice.

* All classes in Java automatically inherit the java.lang.Object class. Object is the super class of all classes. This is very useful since Java doesn''t support templated classes.

I could go on for ever, but my time is up. I hope I''ve been helpful =-) G''luck with your Java''ing
PS: If you want any more complicated example code, just tack on some C++ code and I could give you the closest equivilant I can.
Thanks man I can see you took along time writing that but it seams rather complicated to me(not overly though...) but more than C++ so I dont see why people say its easyier for beginers and I cant see how it would take a significantly less amount of time to write than C++...
anyway heres some code for u to convert:

  #include <fstream.h>#include <iostream.h>int main(){    char FileName[30];    char string[256];    ifstream File;    cout << "select file to open: ";    cin >> FileName;    File.open(FileName);    for(int i = 0; !(File == NULL); ++i)    {	File.getline(string, sizeof(string));			cout << string << endl;    }    File.close();    cout << ''\n'';    return 0;}  

Its just some basic file IO, I hope its not to difficult...
[email=esheppard@gmail.com]esheppard@gmail.com[/email]
Did the small conversion for ya, hope Tac-Tics don't feel cheated
This snippet of code is not really enough to judge a language by though. It would not surprise me if a language like Perl could do this in just a few lines.

      import java.io.*;public class FilePrint {    public static void main(String[] args) {	try {	    System.out.print("Select file to open: ");	    String fileName = (new BufferedReader(new InputStreamReader(System.in))).readLine();	    BufferedReader lineReader = new BufferedReader(new FileReader(fileName));	    String textLine;	    while((textLine = lineReader.readLine()) != null) {		System.out.println(textLine);	    }	    lineReader.close();	    System.out.print("\n");	} catch(IOException ioe) {}    }}      


[edited by - HenryAPe on March 18, 2002 11:53:08 AM]
The IO classes are a lot harder to use that in C++. That''s probably one of the only major downfalls of Java. However, once you master IO, networking becomes easy as pi, because Java networking works just like file input/output.
That looks one hell of alot harder than C++!!!!
[email=esheppard@gmail.com]esheppard@gmail.com[/email]

This topic is closed to new replies.

Advertisement