Performance of Java 1.6 vs C++? - java

With Java 1.6 out can we say that performance of Java 1.6 is almost equivalent to C++ code or still there is lot to improve on performance front in Java compared to C++ ?
Thanks.

Debian likes to conduct benchmarks on this sort of thing. In their case, it appears that Java is about half as fast and consumes 2-18 times as much memory as C++.

A well-written Java program is never going to be as fast as a well-written C or C++ program. The virtual machine is an irreducible overhead. However, most code is not well written.
Java is a simpler language than C++, and offers a more forgiving environment for inexperienced programmers - so if your programmers are inexperienced (and cheap), then Java will probably perform 'better' than C++.
shared_ptrs offer a similarly forgiving environment in C++, so they are very tempting for inexperienced programmers, or those migrating from Java, But their performance overhead is as bad or worse than Java's garbage collection. I've seen large C++ programs where every variable is a shared_ptr, and they perform terribly.
My opinion
Personally, I think that large projects need to choose an 'easy' programming language for the bulk of their code, and a 'fast' one for sections that need optimising. Java may be a good choice for the 'easy' language, especially since there is currently a plentiful supply of Java programmers - in the future, I think even easier languages such as Python will begin to take over.
C++ is a reasonable choice for a 'fast' language if you already know it, but I think it's over-complexity will eventually see it fall by the wayside, while C will continue to fulfill this role.

I would expect that most of the time for most applications C++ will be faster than Java.
In some cases there will be some C++ which is slower than Java for a given task. This is pretty rare and always a result for poor implemntation or more commenly poor refactoring of an application.
In the majority of cases the performance difference more than offset by the fexibility, ease of use, availability of libraries, and, portability that Java provides.
In a very few cases performance is so critical that developing in Java would be a poor choice <opinion><flame off>in these cases plain C is usually a better choice than C++ </flame></opinion>.
Currently the sweetspot in performance/ease of use/ease of development tradeoffs is C#. Portability is a big issues here though.

I find that Java performs very well.
However, why has no one ever fixed my biggest complaint?
Java uses FIVE TIMES as much memory as a C++ program doing the same job. At least!
And once it's used, Java keeps it!
Please, please, why won't anyone write a garbage collector for Java that uses minimum amounts of RAM? It could compact the heap and returns the memory to the OS. Instead of ridiculous piles of -Xm* options, use the memory needed and then give it back!
Actually I am sure some of the embedded system JVMs do this, but none of the desktop or server systems do.
This memory piggishness makes Java applications all want to act as if they own the entire computer system, that no one ever wants to run more than one application and that RAM is free and infinitely upgradable.
Therefore, no matter how great the performance, I would never write anything like a utility program in Java. Only gigantic server apps need apply.

What program are you developing?
Comparing C++ to Java speed is like comparing a screwdriver and a hammer, pointless. In the world we live in, where both supercomputers and toasters need to be programmed, you need to focus on your particular requirements.
I use C++ for hard realtime software running on embedded systems. I wouldn't dream of using the awfully broken Java for realtime spec for at least another 5 years, when it will hopefully be mature. I would be equally loath to use C++ for a database, cloud accessing middleware app (actually I have no Idea what I just said, but I know Java is good for 'that sort of stuff')
Would you use a ferrari with no trunk space to move your belongings? Would you bring a minivan to a drag race?
People have to understand that just because they are programming languages, does not mean they are comparable in a meaningful way.

No. Unless you measure it, you may not say it.

Performance is usually "good enough" for most purposes. The question is what you want to compare exactly, and if you have applied a profiler to find and fix the hotspots in your code.
JVM's based on Sun's code still pay a hefty startup-tax (I still wonder why they cannot snapshot that and restart from there) but Suns approach has been correctness first, speed second, and it's taken them 10 years to get up to par.
So the answer is "It depends" :)

For most applications it is almost certainly possible to write a C++ program which performs considerably better than a program to achieve the same thing in java.
However if the program isn't optimised for speed then java will likely be just as fast or faster because the compiler / JIT is able to make optimisations that a C++ environment can't.
Basically if you are willing to spend considerable time understanding and coding for performance you can probably do a considerably better job in c++ eventually than you could in java but for the same amount of time and effort it is quite likely that java will "win".
As usual though, algorithmic improvements tend to make as much if not more difference than the language.

Related

Is Java a good choice for a streaming server application?

I'm facing a project with audio streaming, as a client and a server. Would Java be a good choice for the server app?
I've read in other questions that because of performance C++ is the best choice for this kind of app.
If you are more comfortable with C++ or Java, I would use that. You can write a low pause server in either language.
A streaming server is mostly about passing lots of data from A to B i.e. the I/O matters. Unless you plan to compress the stream on the fly, the CPU performance is unlikely to be important.
Even if you are doing on the fly compression and Java isn't fast enough for that, you can call a library (preferably one already written/tested) to do this via JNI and still write most of the server in Java.
shrug It's not a bad choice. While audio streaming does have a performance component, the algorithms/optimizations you make are going to have a much larger effect than the language you choose.
Not to mention the famous Knuth quote "Premature optimization is the root of all evil". Write in whatever you are most comfortable with and check if it's a problem later.
The biggest issue with Java performance, I think, is garbage collection. Without careful consideration to what you're doing, it's easy in Java to write code that needs to pause every so often to clean up. C++ doesn't have that problem. On the other hand, without consideration of what you're doing, it's easy to write C++ code that leaks heap memory (when you forget to delete something from the heap). This is really bad for a long-running process like a server. It's possible to leak memory in Java, but it's related to keeping references around too long, not to anything built into the language.
Although C++ tends to be faster, with modern just-in-time compilers for Java, the performance difference tends to be overstated. Overall Java is probably just as fine as C++ for a streaming audio server. If you find that there's a bottleneck in some compute-intensive section, you can always drop down to C++ using Java Native Interface. But that should only be after identifying a problem with profiling.
If you did want to use java, here would be a great place to find some uses and files for using media in java...

Java, JIT and Garbage Collector efficiency

I want to know about the efficiency of Java and the advantages and disadvantages of Java Virtual Machine and Android.
Efficiency is the low use of memory, low use of the processor and fast execution.
Mobile devices are simpler than PC, then the apps need to be more efficient. Servers receive many connections and they need to be very efficient. Many mobile devices use Android and Java apps, and many servers use PHP.
Can Java and interpreted languages, such as Java Script, Python and PHP, be more efficient than C and C++?
JIT (just in time) advantages:
It can optimize better, because it knows the value of some variables and where it is used or changed.
It knows the processor and can optimize with processor specific instructions.
It is easier to transform functions into inline function.
It can remove known conditional tests and remove blocks that will not be run.
Java disadvantages:
When the app run for the first time, the app will be very slow, because the bytecodes will be interpreted and JIT compiler will do many analysis to find good optimizations. The apps cannot use the maximum of the hardware power. If an app is a game or a real-time app, if it be run for the first successfully and with no delay, but it uses the maximum of the hardware power, then the next time the app be run, it will not use the maximum of the hardware power due to optimizations. The problem is the app cannot be designed to use the maximum of the hardware power after the optimization, because it will be too slow on the first run, and will not continue to run.
Java checks if the array index is not out of bounds, and it checks if the pointers are not null. It will add several internal "if"s to generated code.
All objects use garbage collector, including objects that are very easy to manually delete.
All instances of objects are created with dynamic memory allocation, including objects that can easily use the stack. If a loop iteration begins creating an instance of a class and ends deleting the created object, dynamic memory allocation will be inefficient.
The garbage collector needs to stop the app while it cleans the memory and it is very undesired for games, GUI apps and real-time apps. Reference counting is slow and it cannot handle circular references. Multi-threaded garbage collector is slower and it needs more use of the CPU.
Can Java and interpreted languages, such as Java Script, Python and PHP, be more efficient than C and C++?
It's very difficult to get more efficient than the best C and C++ programs. There's a lot of C and C++ programs that are nowhere near as efficient as that though, and beating them with (modern) Java code is quite practical if you're any good.
I've also heard good things about the current best-of-breed Javascript engines, but I've never studied them in detail.
With Python and PHP (and many other languages besides) it's a bit different. Those languages are written in C, so it's obvious they cannot be more efficient than C (follows by construction). Yet it's much easier to write efficient code in them (i.e., that uses what is in-effect a very well-written C library) than it is to start from scratch. In particular, it reduces the number of defects per program. That's a very important metric in practice; anyone can produce fast code if it's allowed to be wrong.
In general, I advise not worrying about getting maximal efficiency. You run up against the law of diminishing returns. Instead, use sensible overall algorithms (or, as a friend of mine once said to me, “look after the big O()s and let the constant factors look after themselves”) and focus on the question of whether the program is good enough in practice. Once it is, stop fiddling around and ship it!
Let's pick apart your claimed disadvantages:
When the app run for the first time, the app will be very slow, because the bytecodes will be interpreted and JIT compiler will do many analysis to find good optimizations. The apps cannot use the maximum of the hardware power.
JIT compilation is an implementation issue. Not all platforms do it. Indeed, the Android platform could be modified to 1) do ahead of time compilation, or 2) cache the native code produced by the JIT to give faster startup next time you run the app.
It is interesting that various Java vendors have tried these strategies at various times, and yet the empirical evidence is that plain JIT is the best strategy.
Java checks if the array index is not out of bounds, and it checks if the pointers are not null. It will add several internal "if"s to generated code.
The JIT compiler can optimize away many of these tests. For the rest, the overheads tend to be relatively small; e.g. a few percent difference ... not a factor of 2.
Note that the alternative to checking is the risk that typical application bugs will crash the android platform. Certainly, garbage collection becomes problematic if applications can trash memory.
All objects use garbage collector, including objects that are very easy to manually delete.
The flip-side is that it is easy to forget to delete objects, delete objects twice, use them after they have been deleted and so on. These mistakes all lead to bugs that tend to be hard to track down.
All instances of objects are created with dynamic memory allocation, including objects that can easily use the stack. If a loop iteration begins creating an instance of a class and ends deleting the created object, dynamic memory allocation will be inefficient.
Java dynamic memory allocation and object creation is FAST. Faster than in C++ for example.
The garbage collector needs to stop the app while it cleans the memory and it is very undesired for games, GUI apps and real-time apps.
Use a concurrent / low-pause garbage collector then. Another approach is to implement your app to not generate lots of garbage ... and seldom trigger garbage collection.
Reference counting is slow and it cannot handle circular references.
No decent Java GC uses reference counting. (On the other hand, a lot of C / C++ manual memory management schemes do. For instance, so-called smart pointer schemes in C++.)
Multi-threaded garbage collector is slower and it needs more use of the CPU.
You actually mean concurrent collection I think. Yes it does, but that's the penalty you pay for the extra responsiveness that you demand for interactive games / realtime apps.
What you describe as 'efficient' I would describe as 'ideal'. An application that requires little memory, little CPU time and runs quickly, put another way, is one that is good, fast, and cheap all at the same time. Never mind if it does anything useful or interesting.
The only comparison I'd view as reasonable, if all three goals are required, is among applications that produce a common result. In that case, it is unlikely, given a competing group of evenly-capable programmers, that any one implementation would excel on all three counts over the others.
That said, your question leaves out a key criterion to the mobile market: rate of application development. Mobile applications also profit far more from positive user experience than back-end optimization. Without that constraint, the question of efficiency as you put it, seems to me more of an ponderous consideration than a practical one.
But to the actual question: can a language like Java produce more efficient code than one that compiles statically to the instruction set of the target machine? Probably not. Can it be as efficient, or efficient enough? Absolutely. If we considered an execution platform with fixed, severely constrained resources that changes infrequently, it would be a different matter.
In any language, the way to get fast execution is to do the job with as little execution as possible, and as little garbage collection as possible.
That sounds like a vacuous generality, but what it means in practice, regardless of language, is
For the data structure design, keep it as simple as possible. Stay away from the fancy collection classes full of bells and whistles. Especially stay away from notifications as a way of keeping data consistent. If your data is normalized, it can never be inconsistent. If you can't normalize it, it's better to tolerate temporary inconsistency, than to try to keep it tight with notifications.
Performance problems creep in, even into the best code. You should try not to make them, but you will still make them. Most important is knowing how to find them, once made, and remove them. Here's a blow-by-blow example. If in doing this, you find you need a better big-O algorithm, then put it in. Putting one in without being sure it's needed is a recipe for slowness.
No language can rescue a program from non-removed performance problems. The language and its compiler, JITter, etc. are like a race horse. It's fine to want a good horse, but it's a waste if the jockey isn't as slim as possible.
Your program is the jockey, and it's your job to take it on a weight-loss program.
I will paste an interesting answer given by the James Gosling himself in the Book Masterminds of Programming.
Well, I’ve heard it said that
effectively you have two compilers in
the Java world. You have the compiler
to Java bytecode, and then you have
your JIT, which basically recompiles
everything specifically again. All of
your scary optimizations are in the
JIT.
James: Exactly. These days we’re
beating the really good C and C++
compilers pretty much always. When you
go to the dynamic compiler, you get
two advantages when the compiler’s
running right at the last moment. One
is you know exactly what chipset
you’re running on. So many times when
people are compiling a piece of C
code, they have to compile it to run
on kind of the generic x86
architecture. Almost none of the
binaries you get are particularly well
tuned for any of them. You download
the latest copy of Mozilla,and it’ll
run on pretty much any Intel
architecture CPU. There’s pretty much
one Linux binary. It’s pretty generic,
and it’s compiled with GCC, which is
not a very good C compiler.
When HotSpot runs, it knows exactly
what chipset you’re running on. It
knows exactly how the cache works. It
knows exactly how the memory hierarchy
works. It knows exactly how all the
pipeline interlocks work in the CPU.
It knows what instruction set
extensions this chip has got. It
optimizes for precisely what machine
you’re on. Then the other half of it
is that it actually sees the
application as it’s running. It’s able
to have statistics that know which
things are important. It’s able to
inline things that a C compiler could
never do. The kind of stuff that gets
inlined in the Java world is pretty
amazing. Then you tack onto that the
way the storage management works with
the modern garbage collectors. With a
modern garbage collector, storage
allocation is extremely fast.

Aside from performance concerns, why is Java still chosen over Groovy/JRuby etc.?

[This is an empirical question about the state-of-the-art: I am NOT asking if Java is cooler or less cool than the dynamic languages that work in the JVM.]
Aside from cases where performance is a main decision factor, do companies/developers still willingly chose Java over Groovy, JRuby or Jython?
Edit: If the answer is "yes," why?
Personal Note: The reason I am asking is that, while I do some subset of my professional work in Ruby (not JRuby, for now), in my personal projects I use Java. While I have written non-trivial apps in Groovy, I prefer Java, but I wonder if I should just get over it and do everything in Groovy. I like Java because I feel that static typing saves me time and aids refactoring. (No, I am not familiar with Scala.) However, I feel that this very empirical, on-topic programming question may inform my decision.
non-statically typed languages don't "scale" well in the maintenance sense. Up to a few tens of thousands of lines of code they are maintainable. Past that they just take more effort to maintain, re-factor or update. This is true of any of the non-static typed languages, Perl, Python, Groovy, Ruby etc. The tools for working with half a million lines of Python code vs the same number of lines of code in C/C++/Java just aren't there. Now it is true that Python is about 1/3 to 1/5 the number of lines of code as an equivalent Java program. So this is never going to be apples and oranges, but there is a cut off point where the number of lines of code in a non-static language will have diminishing returns on maintenance. And everyone knows that maintenance is where the true cost of a software project has always been.
Static typing still is a big thing.
While it has been argued over and over again and proponents of the dynamic approach say that the problems that dynamic typing bring can be reduced (or even eliminated) with sufficient unit tests.
I don't want to argue whether or not this argument is correct, so I'll assume that it is, for this answer.
In that case there is still one problem, which is that many shops don't have the procedures/know-how/rules/management to produce a sufficient number of high-quality unit tests.
And if I have to choose between dynamically typed code without unit tests and statically typed code without unit tests, I'll choose the statically typed one every day.
A similar issue exists with double dispatch:
In Groovy method calls are dispatched based on the actual types of the arguments at runtime (which is almost required, because the static type is unknown and/or Object most of the time). This means that there is no reliable way to know which method is called at any given point at the code, when faced with extensible class hierarchies.
Any code that calls a method with the signature foo(String) most of the time may suddenly call foo(Integer) or foo(SomethingElseEntirely) depending only on the actual type of the argument at runtime. In the Java language that can never happen, because the exact signature of the method to be called is decided at compile time.
Much like other "dynamic" language features, double dispatch is occasionally a very useful tool and the lack of it can produce some ugly constructs in Java, but it has its cost in that it makes it even harder to read, understand and reason about code.
Yes, obviously.
Why are companies still "willingly" using Java?
Because companies are inherently conservative. They don't change technologies because they're cool, or even groovy. They change, reluctantly, when there's a prudent reason to do so. Early adopters pay very heavy penalties for being early adopters.
Edit: this is not "inertia" in the pejorative sense, as in "no reason to avoid change except resistance to change", but in the sense of prudence. It is right for companies to not abandon what's working, until there's something that's provably better.
And not in the "makes developers happy because it's cool" sense of better, but in terms of more quickly and reliably meeting whatever business requirements drive development in the organization.
Java offers:
Large base of trained, experienced developers. It's hard enough finding people who are able to do software development well, without picking a language which hasn't been around as long. And training people in a new language is expensive, in both time and money.
Brand-name recognition and an easily proven track record of successfully completed projects. This is nothing to scoff at: if I tell upper management I'm beginning a project in some groovy new language they've never heard of, I have to educate them on it, and they'll rate that as a risk. With any "established" language, I can skip that step.
Well-established, mature support tools, and third-party support.
These advantages accrue to any comparison between a long-established language and a new one, not just Java and your list. I expect that one day, Groovy, et al, will be the established language, and there'll be people asking the same question about some newer, shinier language. This is the cycle. It's how it's been for longer than I've been in the business.
Aside from cases where performance is
a main decision factor, do
companies/developers still willingly
chose Java over Groovy, JRuby or
JPython?
Yes, and I believe the main reason is inertia, either on the part of the developer or the company:
Company: existing investment in Java (in terms of staff skills and infrastructure), the risks of change are perceived to outweigh the benefits
Developer: there are plenty of Java jobs available, so why bother learning another language?
Lack of available resources is probably another reason, though this is something of a chicken-and-egg problem (or a Mexican standoff, or a self-fulfilling prophecy, or something else). I imagine there are a lot of companies watching Groovy, Jython, etc. but waiting for them to become more widely adopted before taking the plunge. Obviously, by postponing adoption themselves, they're exacerbating this lack of resources problem.
Personal Aside
I spent the last year working as a Groovy/Grails developer. I recently changed jobs and am now working as a Java 1.4 developer and (compared to Groovy programming) it's about as pleasant as gouging your eyes out with a rusty spoon.
Static typing is great in that it facilitates compile-time checking and code analysis tools like FindBugs, but no way does it compensate for the massive amounts of (boilerplate) code it takes to accomplish the simplest of tasks when writing Java (particularly if you're using a version earlier than 1.5).
I can tell you what is going on in my company. Our current application is done in java, but we have started a transition to grails/groovy and this will most probably be the platform for the next generation of our products.
Since you are asking an empirical question, and I assume looking for empirical answers:
Aside from cases where performance is a main decision factor, do companies/developers still willingly chose Java over Groovy, JRuby or JPython?
Yes.
I don't think there is anything else to say.

Alternative to Java

I need an alternative to Java, because I am working on a genetics-calculation project.
It takes a lot of memory and the most of the cpu time. And therefore it won´t work when I deploy it on a server, because many people use the program at the same time.
Does anybody know another language that is not running in a virtual machine and is similar to Java (object-oriented, using exceptions and type-safety)?
Best regards,
Jonathan
To answer the direct question: there are dozens of languages that fit your explicit requirements. AmmoQ listed a few; Wikipedia has many more.
And I think that you'll be disappointed with every one of them.
Despite what Java haters want you to think, Java's performance is not much different than any other compiled language. Just changing languages won't improve performance much.
You'll probably do better by getting a profiler, and looking at the algorithms that you used.
Good luck!
If your apps is consuming most of the CPU and memory on a single-user workstation, I'm skeptical that translating it into some non-VM language is going to help much. With Java, you're depending on the VM for things like memory management; you're going to have to re-implement their equivalents in your non-VM language. Also, Java's memory management is pretty good. Your application probably isn't real-time sensitive, so having it pause once in a while isn't a problem. Besides, you're going to be running this on a multi-user system anyway, right?
Memory usage will have more to do with your underlying data structures and algorithms rather than something magical about the language. Unless you've got a really great memory allocator library for your chosen language, you may find you uses just as much memory (if not more) due to bugs in your program.
Since your app is compute-intensive, some other language is unlikely to make it less so, unless you insert some strategic sleep() calls throughout the code to deliberately make it yield the CPU more often. This will slow it down, but will be nicer to the other users.
Try running your app with Java's -server option. That will engage a VM designed for long-running programs and includes a JIT that will compile your Java into native code. It may make your program run a bit faster, but it will still be CPU and memory bound.
If you don't like C++, you might consider D, ObjectiveC or the new Go language from google.
You may try C++, it satisfies all your requirements.
Use Python along with numpy, scipy and matplotlib packages. numpy is a Python package which has all the number crunching code implemented in C. Hence runtime performance (bcoz of Python Virtual Machine) won't be an issue.
If you want compiled, statically typed language only, have a look at Haskell.
Can your algorithms be parallelised?
No matter what language you use you may come up against limitations at some point if you use a single process. Using something like Hadoop will mean you can retain Java and ease of use but you can run in parallel across many machines.
On the same theme as #Barry Brown's answer:
If your application is compute / memory intensive in Java, it will probably be compute / memory intensive in C++ or any other "more efficient" language. You might get some extra leeway ... but you'll soon run into the same performance wall.
IMO, you need to do the following things:
You need profile your application, and look for any major performance bottlenecks. You might find some real surprises.
In the light of the previous step, review the design and algorithms, paying attention to space and time complexity issues. Do some research to see if someone has discovered better algorithms for doing the computations that are problematic from a performance perspective.
If the previous steps don't get you ahead of the curve, see if you can upgrade your platform; get a bigger machine with more processors, more memory, etc.
If you are still stuck, your only other option is a scale-out design. Assuming that individual user requests are processed in a single-threaded, re-architect your system so that you can run "workers" across multiple servers, with a load balancer on the front. If you have a persistent back-end, look into how you can replicate that. And so on.
Figure out if the key algorithms can be parallelized / distributed so that the resource intensive parts of a user request execute in parallel on multiple processors / multiple servers; e.g. using a "map-reduce" framework.
OK, so there is no easy answer. But simply changing programming languages is NOT a good answer.
Regardless of language your program will need to share with others when running in multiple instances on a single machine. That is simply the way computers work.
The best way to allow your current program to scale to use the available hardware resources is to chop your amount of work into small, independent pieces, and make them implement the Callable interface. These can then be executed by a suitable Executor which can then be chosen according to the available hardware. See the Executors class for many preconfigured versions. THis is what I would recommend you to do here.
If you want to switch language then Mac OS X 10.6 allows for programming in the way described above with C and ObjectiveC and if you do it properly OS X can distribute the code over all available computing resources (both CPU and GPU and what have we).
If none of the above is interesting to you, then consider one of the Grid frameworks. Terracotta may be a good place to start.
F# or ruby, or python, they are very good for calculations, and many other things
NASA uses python
Well.. I think you are looking for C#.
C# is Object Oriented and has excellent support for Generics. You can use it do write both WinForm and server-side applications.
You can read more about C# generics here: http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx
Edit:
My mistake, geneTIcs, not geneRIcs. It does not change the fact C# will do the job, and using generics will reduce load significantly.
You might find the computer language shootout here interesting.
For example, here's Java vs C++.
You might find Ocaml (from which F# is derived) worth a look; it meets your requirements for OO, exceptions, static types and it has a native compiler, however according to the shootout you may be trading less memory for lower speed.

Why Java programs?

I've had little exp. with java and since now i've worked with c++. what makes this one more special and preferred?
Moreover I would like to know about the use of System.in classes and parseInt classes.
Java is vastly easier to work with, especially when developing large programs.
Debugging: Java generates nice Stacktraces
Stability: You can catch every exception
Development Speed: you need no linker (which can take many minutes in C++); with a modern IDE (e.g. eclipse) you can edit code in-place while the program is running
Garbage Collection and run-time type safety eliminate whole classes of errors
really good free (as in beer) IDEs
In theory (and sometimes in reality) Java programs also run on multiple platforms, "write once - debug, er, run everywhere" type of thing. That makes it very useful for a variety of projects.
In my personal experience, while learning Java shortly after being introduced to C++, Java seemed simpler and easier to learn and understand, hence more productive, as was said before. While program structure and syntax is very similar, there is no need to worry about pointers and other potentially dangerous language features.
This is really very broad and I think these are really 2 or 3 different questions. I'll address the first one very briefly. Java utilizes garbage collection, or autmatic memory management. That is, arguably, the biggest difference between it from a language like C++. There are clearly some potential for increase in productivity in that you don't have to worry as much about memory, although in reality you do need to pay attention to your references. Perhaps you could refine your question a bit.
Java works in browsers! (Milpa for example). You can say Flash too, but with Java you can leverage the numerous classes coming with it (another advantage over C++, even if both languages has a good set of free libraries on the Net) and your knowledge of the language.
As said, Java is supported on many platforms with minimal adjustments, with a fast, efficient VM, from big servers to mobile phones.
OO support is arguably better designed, avoiding mistakes done in C++. Somehow, C# is to Java what Java is to C++ ^_^ (I won't argue on this, I don't know C# enough actually, it is just an historical point).
In the same spirit, Java is slightly more abstract, avoiding pointers, manual memory management and some other low level stuff.
That doesn't mean than one is better than the other, STL helps C++ for some of the issues above, etc.
I am not sure how to answer the last sentence, these are object and method respectively, not classes.
I never used System.in yet, I suppose it is usable if you feed the Java program with < or | on the command line. And parseInt is a static method of Integer class.
The language features have already been mentioned (GC, reflection etc.). But there is another major difference: Libraries. I know there is the STL and Boost and all kinds of libraries out there, but they are not all of a piece, they all feel different. Often you are forced to use all kinds of C-APIs (e.g. threading or sockets, just to mention two things). All the C++ evangelists will now jump in and tell about some kind of cool OO-socket or OO-threading library, but they are not part of the STL. They should be. Its almost 2009 and everything is networked and multithreaded. This ought to be part of the standard library.
Why is it bad to use those C-APIs? Because it is hard to use them in an object oriented programm. Try using Win32's CreateThread() with the listener-pattern (C#-users: read "delegates").
For a "rich client application", where performance is not a big deal, I would always use Java or C#. If I need raw speed (think signal processing or embedded applications), I would rather use C instead of C++.
BTW: I have used all four languages (C, C++, Java, C#) for a long time.
If you like to program really the object oriented way, then you need to go from C++ to Java. One of the problems with C++ is that most programmers actually use it as C and don't exploit all its OO features. Java is here stricter.
With C++ you're programming "on the metal", whereas with Java you're programming towards a virtual machine. The Java software stack all the way down to the VM is constructed to give a highly abstracted programming experience. This is most clearly apparent in the use of datatypes "that just are" (i.e. the programmers need no understanding of how they translate into memory areas), garbage collection "that just works" (the programmers don't have to deal with allocation and deallocation issues) and the ubiquity of exceptions for error handling and propagation. Pointers are not part of Java, the system takes care of where and how things are allocated.
From this, you might see that the design philosophy of Java is very different from C++: Java tries to enforce that the programmer should stick to certain ways of working which are considered to be safe and to make programming easier. Some people hate this aspect of Java, other people love it.
It really depends on what you're trying to do.
For a lot of higher level functionality where optimal performance may not matter, Java is easier and more reliable to use. For example, garbage collection, array checking, etc. It's also sandboxed, of course.
For me, another major benefit of Java is the use of reflection and of run time class loading. I write a lot of plugins within pluggable architectures, and can ensure I can add more new classes to a running program on any platform. Last time I tried to do that in C++, I had to mess with DLLs and COM.

Categories