How to use Deelang conditionals with operators? - java

Am making a simple game (another one that will probably never be published) in libGdx and I want to evaluate 'events' for the game characters. Each event should have a 'condition' block and an 'execute' block, that executes if the 'condition' returns true. The language has to support order of operations as well as the following logical operators or their equivalents;
==
!=
<=
>=
||
&&
I also need to be able to pass instances of various objects to the script, so that I might access variables and call methods similar to this;
if(game.hasFlag("here_be_my_flag")) then
game.alertAllPlayers("Here be my flag!");
Where game is the instance of class Game of my game and hasFlag and alertAllPlayers are methods of game implemented in java.
The problem comes when I need two dozen scripts evaluating for each "character" (between 100 and 500) in the game. It was quite simple to set Mozilla's Rhinoscript Javascript interpreter up for this, but this slows my FPS down from 50 to the 25 to 30 range, an unacceptable loss of performance. This is because Rhino was designed to run on an actual JVM, something Android lacks. Android instead runs on a DVM which executes bytecode in a different format from JVM bytecode. Rhino can compile to Java bytecode, but not Dalvik.
This problem is present in many of the different languages. Most were designed to work on desktop computers. I stumbled upon Deelang, a small scripting language that compiles into Dalvik bytecode. Deelang has good performance relative to Rhino on Android devices.
Unfortunately, it seems that most languages with good documentation do not have this ability and are bound to be slower than those that do (there are probably exceptions). So, I looked at the two basic examples of Deelang code on Github and there is absolutely nothing on boolean comparisons. I learned of Deelang while reading a few questions on scripting languages in java. There is little to no documentation on the Github Wiki regarding this, so, does anyone with experience in this minilanguage know anything regarding the use of operators and conditionals?
Note that I have poked around in the code for comments that might possible give me an idea as to how to do this.

Related

C/C++ exposure of functions / methods vs Java

The world of Minecraft Modding has made me curious about differences in mechanisms between Java and C/C++ libraries to allow methods / functions in the libraries to be invoked externally.
My understanding is that Minecraft Modding came about due to the ability to decompile / reflect over Java in order to reverse engineer classes and methods that can be invoked from the library. I believe that the Java class specification includes quite a lot of metadata about the structure of classes allowing code to be used in ways other than intended.
There are some obfuscation tools around that try to make it harder to reverse engineer Java but overall it seems to be quite difficult to prevent.
I don't have the depth of knowledge in C/C++ to know to what degree the same can be done there.
For C/C++ code is compiled natively ahead of time. The end result is an assembly of machine code specific for that platform. C/C++ has the notion of externalising functions so that they can be exposed from outside the library or executable. Some libraries also have an entry point.
Typically when connecting to external functions there is a header file to list what functions are available to code against from the library.
I would assume there would need to be a mechanism to map an exposed function to the address within the library / executable machine code assembly so the function calls get made in the right place.
Typically connecting the function calls together with the address is the job of the linker. The linker still needs to somehow know where to find these functions.
This makes me wonder if it is fundamentally possible to invoke non exported functions. If so would this require the ability to locate their address and understand their parameter format?
function calls in C/C++ as I understand it is typically done by assigning the parameters to registers for simple functions or to an argument array for more complex functions.
I don't know if the practice of invoking non-public API's in native code is common
or if the inherent difficulty in doing so makes native code pretty safe from this kind of use.
First of all, there are tools (of varying quality and capabilities) to reverse engineer compiled machine-code back to the original language [or another language, for that matter]. The biggest problem when doing this is that languages such as C and C++, the names of members in a structure don't have names, and often become "flat", so what is originally:
struct user
{
std::string name;
int age;
int score;
};
will become:
struct s0
{
char *f0;
char *f1;
int f2;
int f3;
};
[Note of course that std::string may be implemented in a dozen different ways, and the "two pointers" is just one plausible variant]
Of course, if there is a header file describing how the library works, you can use the data structures in that to get better type information. Likewise, if there is debug information in the file, it can be used to form data structures and variable names in a much better way. But someone who wants to keep these things private will (most often) not ship the code with debug symbols, and only publish the actual necessary parts to call the public functionality.
But if you understand how these are used [or read some code that for example displayed a "user", you can figure out what is the name, the age and what is the score.
Understanding what is an array and what is separate fields can also be difficult. Which is it:
struct
{
int x, y, z;
};
or
int arr[3];
Several years ago, I started on a patience card game (Similar to "Solitaire"). To do that, I needed a way to display cards on the screen. So I thought "well, there's one for the existing Solitaire on Windows, I bet I can figure out how to use that", and indeed, I did. I could draw the Queen of Clubs or Two of Spades, as I wished. I never finished the actual game-play part, but I certainly managed to load the card-drawing functionality from a non-public shared library. Not rocket science by any means (there are people who do this for commercial games with thousands of functions and really complex data structures - this had two or three functions that you needed to call), but I didn't spend much time on it either, a couple of hours if I remember right, from coming up with the idea to having something that "works".
But for the second part of your question, plugin-interfaces (such as filter plugins to Photoshop, or transitions in video editors), are very often implemented as "shared libraries" (aka "dynamic link libraries", DLLs).
There are functions in the OS to load a shared library into memory, and to query for functions by their name. The interface of these functions is (typically) pre-defined, so a function pointer prototype in a header-file can be used to form the actual call.
As long as the compiler for the shared library and the application code are using the the same ABI (application binary interface), all should work out when it comes to how arguments are passed from the caller to the function - it's not like the compiler just randomly uses whatever register it fancies, the parameters are passed in a well-defined order and which register is used for what is defined by the ABI specification for a given processor architecture. [It gets further more complicated if you have to know the contents of data structures, and there are different versions of such structures - say for example someone has a std::string that contains two pointers (start and end), and for whatever reason, the design is changed to be one pointer and a length - both the application code and the shared library need to be compiled with the same version of std::string, or bad things will happen!]
Non-public API functions CAN be called, but they wouldn't be discoverable by calling the query for finding a function by name - you'd have to figure out some other way - for example by knowing that "this function is 132 bytes on from the function XYZ", and of course, you wouldn't have the function prototype either.
There is of course the added complication where Java Bytecode is portable for many different processor architectures, machine code only works on a defined set of processors - code for x86 works on Intel and AMD processors (and maybe a few others), code for ARM processors work in chips developed with the ARM instruction set, and so on. You have to compile the C or C++ code for the given process.

How does Java compute the sine and cosine functions?

How does Java find sine and cosine? I’m working on trying to make a game that is a simple platformer something like super Mario or Castlevania. I attempted to make a method that would rotate an image for me and then resize the JLabel to fit that image. I found an algorithm that worked and was able to accomplish my goal. However all I did was copy and past the algorithm any one can do that I want to understand the math behind it. So far I have figured everything out except one part. The methods sin and cos in the math class. They work and I can use them but I have no idea how Java get its numbers.
It would seem there is more then one way to solve this problem. For now I’m interested in how Java does it. I looked into the Taylor series but I’m not sure that is how java does it. But if Java does use the Taylor series I would like to know how that algorithm is right all the time (I am aware that it is an approximation). I’ve also heard of the CORDIC algorithm but I don’t know much about it as I do with the Taylor series which I have programmed into Java even though I don’t understand it. If CORDIC is how it's done, I would like to know how that algorithm is always right. It would seem it is also possible that the Java methods are system dependent meaning that the algorithm or code used would differ from system to system. If the methods are system dependent then I would like to know how Windows gets sine and cosine. However if it is the CPU itself that gets the answer I would like to know what algorithm it is using (I run an AMD Turion II Dual-Core Mobile M520 2.29GHz).
I have looked at the score code of the Math class and it points to the StrictMath class. However the StrictMath class only has a comment inside it no code. I have noticed though that the method does use the keyword native. A quick Google search suggest that this keyword enables java to work with other languages and systems supporting the idea that the methods are system dependent. I have looked at the java api for the StrictMath class (http://docs.oracle.com/javase/7/docs/api/java/lang/StrictMath.html) and it mentions something called fdlimb. The link is broken but I was able to Google it (http://www.netlib.org/fdlibm/).
It seems to be some sort of package written in C. while I know Java I have never learned C so I have been having trouble deciphering it. I started looking up some info about the C language in the hopes of getting to bottom of this but it a slow process. Of cores even if did know C I still don’t know what C file Java is using. There seems to be different version of the c methods for different systems and I can’t tell which one is being used. The API suggest it is the "IEEE 754 core function" version (residing in a file whose name begins with the letter e). But I see no sin method in the e files. I have found one that starts with a k which I think is sort for kernel and another that starts with an s which I think is sort for standard. The only e files I found that look similar to sin are e_sinh.c and e_asin.c which I think are different math functions. And that’s the story of my quest to fiend the Java algorithms for sine and cosine.
Somewhere at some point in the line an algorithm is being called upon to get these numbers and I want to know what it is and why it works(there is no way java just gets these numbers out of thin air).
The JDK is not obligated to compute sine and cosine on its own, only to provide you with an interface to some implementation via Math. So the simple answer to your question is: It doesn't; it asks something else to do it, and that something else is platform/JDK/JVM dependent.
All JDKs that I know of pass the burden off to some native code. In your case, you came across a reference to fdlibm, and you'll just have to suck it up and learn to read that code if you want to see the actual implementation there.
Some JVMs can optimize this. I believe HotSpot has the ability to spot Math.cos(), etc. calls and throw in a hardware instruction on systems where it is available, but do not quote me on that.
From the documentation for Math:
By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math.
The documentation for StrictMath actually mentions fdlibm (it places the constraint on StrictMath that all functions must produce the same results that fdlibm produces):
To help ensure portability of Java programs, the definitions of some of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic.
Note, however, that Math is not required to defer to StrictMath. Use StrictMath explicitly in your code if you want to guarantee consistent results across all platforms. Note also that this implies that code generators (e.g. HotSpot) are not given the freedom to optimize StrictMath calls to hardware calls unless the hardware would produce exactly the same results as fdlibm.
In any case, again, Java doesn't have to implement these on its own (it usually doesn't), and this question doesn't have a definitive answer. It depends on the platform, the JDK, and in some cases, the JVM.
As for general computational techniques, there are many; here is a potentially good starting point. C implementations are generally easy to come by. You'll have to search through hardware datasheets and documentation if you want to find out more about the hardware options available on a specific platform (if Java is even using them on that platform).

PHP to Java (using PtoJ)

I would like to transition our codebase from poorly written PHP code to poorly written Java, since I believe Java code is easier to tidy up. What are the pros and cons, and for those who have done it yourselves, would you recommend PtoJ for a project of about 300k ugly lines of code? Tips and tricks are most welcome; thanks!
Poorly written PHP is likely to be very hard to convert because a lot of the bad stuff in PHP just doesn't exist in Java (the same is true vice versa though, so don't take that as me saying Java is better - I'm going to keep well clear of that flame-war).
If you're talking about a legacy PHP app, then its highly likely that your code contains a lot of procedural code and inline HTML, neither of which are going to convert well to Java.
If you're really unlucky, you'll have things like eval() statements, dynamic variable names (using $$ syntax), looped include() statements, reliance on the 'register_globals' flag, and worse. That kind of stuff will completely thwart any conversion attempt.
Your other major problem is that debugging the result after the conversion is going to be hell, even if you have beautiful code to start with. If you want to avoid regressions, you will basically need to go through the entire code base on both sides with a fine comb.
The only time you're going to get a satisfactory result from an automated conversion of this type is if you start with a reasonably tide code base, written at least mainly in up-to-date OOP code.
In my opinion, you'd be better off doing the refacting excersise before the conversion. But of course, given your question, that would rather defeat the point. Therefore my recommendation is to stick it in PHP. PHP code can be very good, and even bad PHP can be polished up with a bit of refactoring.
[EDIT]
In answer to #Jonas's question in the comments, 'what is the best way to refactor horrible PHP code?'
It really depends on the nature of the code. A large monolithic block of code (which describes a lot of the bad PHP I've seen) can be very hard (if not imposible) to implementunit tests for. You may find that functional tests are the only kind of tests you can write on the old code base. These would use Selenium or similar tools to run the code through the browser as if it were a user. If you can get a set of reliable functional tests written, it is good for helping you remain confident that you aren't introducing regressions.
The good news is that it can be very easy - and satisfying - to rip apart bad code and rebuild it.
The way I've approached it in the past is to take a two-stage approach.
Stage one rewrites the monolithic code into decent quality procedural code. This is relatively easy, and the new code can be dropped into place as you go. This is where the bulk of the work happens, but you'll still end up with procedural code. Just better procedural code.
Stage two: once you've got a critical mass of reasonable quality procedural code, you can then refactor it again into an OOP model. This has to wait until later, because it is typically quite hard to convert old bad quality PHP straight into a set of objects. It also has to be done in fairly large chunks because you'll be moving large amounts of code into objects all at once. But if you did a good job in stage one, then stage two should be fairly straightforward.
When you've got it into objects, then you can start seriously thinking about unit tests.
I would say that automatic conversion from PHP to Java have the following:
pros:
quick and dirty, possibly making happy some project manager concerned with short-time delivery (assuming that you're lucky and the automatically generated code works without too much debugging, which I doubt)
cons:
ugly code: I doubt that automatic conversion from ugly PHP will generate anything but ugly Java
unmaintainable code: the automatically generate code is likely to be unmaintainable, or, at least, very difficult to maintain
bad approach: I assume you have a PHP Web application; in this case, I think that the automatic translation is unlikely to use Java best practices for Web application, or available frameworks
In summary
I would avoid automatic translation from PHP to Java, and I woudl at least consider rewriting the application from the ground up using Java. Especially if you have a Web application, choose a good Java framework for webapps, do a careful design, and proceed with an incremental implementation (one feature of your original PHP webapp at a time). With this approach, you'll end up with cleaner code that is easier to maintain and evolve ... and you may find out that the required time is not that bigger that what you'd need to clean/debug automatically generated code :)
P2J appears to be offline now, but I've written a proof-of-concept that converts a subset of PHP into Java. It uses the transpiler library for SWI-Prolog:
:- use_module(library(transpiler)).
:- set_prolog_flag(double_quotes,chars).
:- initialization(main).
main :-
Input = "function add($a,$b){ print $a.$b; return $a.$b;} function squared($a){ return $a*$a; } function add_exclamation_point($parameter){return $parameter.\"!\";}",
translate(Input,'php','java',X),
atom_chars(Y,X),
writeln(Y).
This is the program's output:
public static String add(String a,String b){
System.out.println(a+b);
return a+b;
}
public static int squared(int a){
return a*a;
}
public static String add_exclamation_point(String parameter){
return parameter+"!";
}
In contrast to other answers here, I would agree with your strategy to convert "PHP code to poorly written Java, since I believe Java code is easier to tidy up", but you need to make sure the tool that you are using doesn't introduce more bugs than you can handle.
An optimum stategy would be:
1) Do automated conversion
2) Get an MVP running with some basic tests
3) Start using the amazing Eclipse/IntelliJ refractoring tool to make the code more readable.
A modern Java IDE can refactor code with zero bugs when done properly. It can also tell you which functions are never called and a lot of other inspections.
I don't know how "PtoJ" was, since their website has vanished, but you ideally want something that doesn't just translate the syntax, but the logic. I used php2java.com recently and it worked very well. I've also used various "syntax" converters (not just for PHP to Java, but also ObjC -> Swift, Java -> Swift), and even they work just fine if you put in the time to make things work after.
Also, found this interesting blog entry about what might have happened to numiton PtoJ (http://www.runtimeconverter.com/single-post/2017/11/14/What-happened-to-numition).
http://www.numiton.com/products/ntile-ptoj/translation-samples/web-and-db-access/mysql.html
Would you rather not use Hibernate ?

C for Java Programmer? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Should I learn C before learning C++?
As a professional (Java) programmer and heavy Linux user I feel it's my responsibility to learn some C (even though I may never use it professionally), just to make me a better coder.
Two questions :
Should I try C or C++ first - I realise they are different languages with some common ground. Is it useful to learn a bit of both, or just try one? I hear C++ is a bit of a nightmare behemoth of a language.
What are the best resources (books, tutorials, practice programs, reference code) for a Java developer like myself.
Thanks
C is simple to learn, difficult to master. as a Java programmer the barrier will be memory and structure .. and undoing the damage Java may have done to the algorithm producing portions of your brain ;)
I would recommend getting familiar with the GCC toolchain on your Linux box, through tutorials on the Internet. Then read The C Programming Language, and a copy of Linux Application Development doesn't hurt. Also, on Linux glib will save you from reinventing the wheel ... but at least try to create your own linked-list, hashmap, graph and other API to learn. Pointer arithmetic, arrays and learning that elements such as structs are just named-offsets in a binary chunk are all important. Spend time with malloc and free and memcheck. With C, your tools and toolchain are very important and the IDE isn't necessarily your friend when learning.
I would pick C over C++ as C is a good foundation to get used to the memory management and pointer usage of C.
The best thing you can do is apply what you learn to a real project. But be prepared to bash your head against the wall allot in Valgrind and GDB. I have been programming C for years, and I am still no C monk.
I do agree that C is a great language, it shows up a bad programmer. But remember:
Any sufficiently complicated C program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
The moral of which is learn other languages too, rather than just C-derived ones! Consider some Lisp dialect, Erlang (which is cool at the moment), Haskell, etc. They will expand your horizons from the 2x2 cell of Java. Consider looking at SICP too.
Coming from ASM, C, then C++, and finally landing (forced) into the Java territory, I thought I may provide an opinion about the subject.
First, with all due respect to the Java community, the business experience shows that while C/C++ programmers can get used to the Java principles and programming (it may not be that easy), the opposite happens more rarely. In other terms, a C++ programmer will have to learn and cope with tons of Java rules (Frameworks...) but she will eventually (and usually) be able to produce a long term working code by injecting a lot of her system experience into the process. A Java programmer going to C, used to more theoretical principles, and strict structure rules may
feel insecure as she has to decide many things, like program organization and structure
feel surprised with the pointers, and memory management: allocation and freeing, which has to be thought carefully - discovering the world of memory leaks
feel discouraged, as the bugs won't appear black on white in a console dictated by the JVM through 200 lines of stack trace, but may happen at a deeper / system level, maybe caught thanks to an IDE in front of which the Java programmer will contemplate some assembly code for the 1st time in her life
feel perplex as to what algorithm and how to implement it, the one that was integrated into Java that she never had to worry about...
So, now, my task is to help you to feel secure, confident, and motivated before learning C/C++!
My advice is to start with C, because
C by itself owns all the very concepts you never had to face with Java
as a Java programmer you already have a classes 'approach', and starting with C++, you may be tempted to stick to the Java OO principles
C principles are limited to a few. C looks like the very last human thing before entering the dark world of assembly language.
What I would emphasize during the C study is, for instance
Pointers Java uses pointers of course, but hides its access while actually passing classes to methods as pointers. In C, you will have to learn the difference between by value and by reference. Also, the more subtle difference between char x[3] and char *x = "ab". And how convenient pointers are to go through an array etc..., you know *++x or *x++. A lot has been said about pointers, my advice would be
always keep control, i.e. don't put too many indirections when not necessary
don't typedef pointers, like typedef int *pointerToInt ; it seems easier at first (pointerToInt pi instead of int *pi) after a few levels, I prefer to count the stars than the 'pointerTo' [some big cies do that]. Except maybe the pointers to functions, unreadable anyway.
Memory When you need memory, you allocate it, and when you don't need it anymore, you free it. Easy. The thing is to allocate the right amount, and not to free it twice... Have to get used to that. And get used to the heap, the stack... And When your program runs and address NULL (0) you may have a visible exception. Maybe not.
Data structure So you want to use a convenient HashMap? Sure, after you developed it. Or there are some libraries you can link that do that kind of thing, just chose the right one. To be fair, when programming in C, you [have to] think different, and may find a more appropriate algorithm than a map for a given problem.
All in all, you will feel disoriented at first, but eventually (unless you have nightmares) you will find before you a lot of room for fun and pleasure. C allows a person to program with complete freedom: C goes according to your ideas, not the opposite.
If the goal is to make you a better coder, aim for languages that actually try to be different. Java, C++ and C are all closely related.
True, one is primarily a procedural language, one tries really hard to pretend to be OOP, and one is a mix of at least 4 different paradigms, but they're all imperative languages, they all share a lot of syntax, and basically, they're all part of the same family of languages.
Learning C isn't going to teach you anything dramatically new. It might teach you a bit about memory layout and such, but you can learn that in many other ways, and it's just not very relevant to a Java programmer.
On the other hand, the language is relatively easy to pick up, and widely used for a lot of Linux software, so if you want to contribute to any of those, learning C is a good idea. It just won't make you a much better Java programmer.
As for C++, calling it a "nightmare behemoth of a language" probably isn't far from the truth. It is big and complex and full of wierd pitfalls and traps for the unwary beginner.
but it also has some redeeming qualities. For one thing, it is one of the only languages to support the generic programming paradigm, and that allows you to express many advanced concepts very concisely, and with a high degree of flexibility and code reuse.
It's a language that'll probably both make you hate C++ for being such an overengineered mess, and all other languages for missing C++ features that'd have made your code so much simpler.
Again, learning C++ won't make a huge difference to you as a Java programmer, except that it'll reveal a number of shortcomings in Java that you weren't aware of until now.
Learning either language is good, but what's better is learning something different.
Learn SML or Scheme or Haskell. Or Ruby, Python or Smalltalk. How about Erlang or Occam? Or Prolog.
Learn something that isn't either Java's sibling or ancestor, something that is designed from scratch to have nothing in common with Java. Learn a functional language like SML, or a dynamically typed one like Python, or one that radically changes how you deal with concurrency, like Erlang.
It depends on what you want to learn. I think it's probably best to sit back and consider why you really want to do this at all. If Java does what you want, and you're just doing this out of some misplaced sense of duty, I think there are probably better ways to spend your time. The reputation of C++ as a "nightmare behemoth" is spread mostly by insecure Java programmers trying to justify what, in their hearts, they know to have been a second-rate choice1.
There are a couple of books specifically written for Java programmers learning C and/or C++. Though it's not specifically for Java programmers, if you do decide on C++ rather than C, I'd consider Acclerated C++.
1I'm at least sort of joking, of course, but there are an almost amazing number of Java programmers who seem to have a chip on their shoulder. If you tell somebody who uses Python or Ruby (for just a couple of examples) that it's slow, the typical reaction is them looking a little puzzled and saying something like: "If you say so -- it seems fast enough to me." Suggesting the same about Java is practically guaranteed to produce claims that you're obviously ignorant and expressing nothing but blind hatred.
Edit: As far as choosing between C and C++ goes, for somebody accustomed to Java, C will simply be an exercise in frustration. The difference in language would require considerable adjustment anyway, but moving from a library the size of Java's to one the size of C's will simply result destroying his productivity for quite a while, and is more likely to just prejudice him again all languages with "C" in the name than help him actually learn anything.
Moving directly from Java to C is like taking somebody whose idea of a sporty car is when he drives the Lincoln Town Car instead of being chauffeured in the limousine, and when he decides racing is cool, you dump him directly in the seat of an Outlaw sprint car. Give him a chance in (not only much safer, but actually faster) street-legal sports car first...
Regarding (1), I'd probably say C. It's a lot more foreign. Since your goal is to be multilingual for its own sake, moving towards a language that is much different than Java will probably be more useful than learning C++, which will probably make you angry. C++ gets a lot of crap from people, and it's not necessarily awful, but the primary reason is that it is trying to force a new paradigm into the structure of C, which doesn't work as well as a language that starts with that paradigm in the first place.
For (2), I would highly, highly recommend K&R. It assumes some programming familiarity, is brief, to the point, but also is deep enough to explain concepts. It doesn't include exercises, however, which you'll have to find elsewhere. I learned C on the job, I'm afraid (and still paying for it!) so I can't give you educated help there.
Since you're doing this for self-fulfillment and learning, I say go for broke and give C++ a try.
A small preface before I elaborate: I used to work primarily with C++ and have never worked with C code of any significant size. Now I work with C# for the most part, only using C++ on rare occasions.
I think C++ is a better option because:
It's a partial super-set of C: C programs will generally not compile as C++ programs, but the overlap between the two languages is substantial enough that it shouldn't be difficult for you to re-target your skills to work with C code if you need to.
C++ will introduce you to more concepts: You'll get all the fun of memory management and bit twiddling that you can do in C. But you'll also get to see generics like you've never seen them before, how algorithms can be written independently from containers, how to do compile-time polymorphism, how multiple inheritance can be actually useful sometimes, etc.
You'll learn to appreciate the design of the Java language a lot more: C++ is a complicated languages with many gotchas and edge cases (see the FAQ and the FQA for some examples). By experiencing them for yourself, you'll be able to better understand many of the design decisions that went into making both Java and C#.
It boils down to this: The more you learn the more that you'll be able to learn. And C++ forces a lot of learning on you, definitely more than C. And that's a good thing.
C++ will probably feel more familiar to you than C, and will probably be easier to get productive with off the bat. However, C is a much smaller language and should be reasonably straightforward to learn (although beware; by learning C you risk permanent brain damage). My personal reference is "C: A Reference Manual" by Harbison & Steele (currently 5th edition). For C++, I just use the O'Reilly nutshell book.
As a C programmer with some C++ experience and currently making the transition to Java, I can tell you the things about C that are probably going to trip you up almost immediately:
C has very little in the way of abstractions; pointers and byte streams are pretty much it. There are no standard container types (lists, maps, etc.). You want anything more sophisticated than a fixed-length array, you will have to roll your own (or use a library developed by someone else).
There is no such thing as garbage collection in C. Every byte you allocate dynamically (via malloc() or calloc()) you are on the hook for deallocating (via free()).
Arrays in C do not behave like arrays in Java; there are some funky rules regarding array types that at first blush do not make sense (and won't until sufficient brain damage has set in). There is no bounds checking on arrays, and some standard library functions (notably gets() and scanf()) make buffer overrun exploits a real risk.
C declaration syntax can get pretty twisted. While you probably won't see anything quite so ugly, declarations like int *(*(*(*f)())[10])(); are possible (f is a pointer to a function returning a pointer to a 10-element array of pointers to functions returning pointer to int`.
C implementation limits can vary from platform to platform; for example, the language standard only mandates minimum ranges for types like short, int, and long, but they may be wider than the minimum requirements. If you're expecting an int to always be the same size regardless of platform, you're in for some surprises.
Text processing in C is a pain in the ass. Seriously. C does not have a string type as such.

Closures in Java 7 [duplicate]

This question already has answers here:
What’s the current state of closures in Java?
(6 answers)
Closed 9 years ago.
So is Java 7 finally going to get the closures? What's the latest news?
Yes, closures were include to release plan of java 7 (and it was the most significant reason to delay release from winter to autumn (expected in September 2010)).
The latest news could be found at Project Lambda. You may also be interested in reading latest specification draft.
There is no official statement on the state of closures at the moment.
Here are some readable examples of how it could work and look like.
If you want to get some insight into what's going on I refer you to the OpenJDK mailing list.
Overview
Basically there is some hope, because code together with some tests were already committed to some source code branch and there are at least some halfway working infrastructure to test it.
The change message from Maurizio Cimadamore reads:
initial lambda push; the current prototype suuports the following features:
function types syntax (optionally enabled with -XDallowFunctionTypes)
function types subtyping
full support for lambda expression of type 1 and 2
inference of thrown types/return type in a lambda
lambda conversion using rules specified in v0.1.5 draft
support references to 'this' (both explicit and implicit)
translation using method handles
The modified script build of the
langtools repository now generates an
additional jarfile called javacrt.jar
which contains an helper class to be
used during SAM conversion; after the
build, the generated scripts
javac/java will take care of
automatically setting up the required
dependencies so that code containing
lambda expressions can be compiled and
executed.
But this is ongoing work and quite buggy at the moment.
For instance the compiler sometimes crashes on valid expressions, doesn't compile correct closure syntax code or generates illegal byte code.
On the negative side there are some statements from Neal Gafter:
It's been nearly three months since the 0.15 draft, and it is now less
than two weeks before the TL (Tools and Languages) final integration
preceding openjdk7 feature complete. If you've made progress on the
specification and implementation, we would very much appreciate it being
shared with us. If not, perhaps we can help. If Oracle has decided that
this feature is no longer important for JDK7, that would be good to know
too. Whatever is happening, silence sends the wrong message.
A discussion between Neal Gafter and Jonathan Gibbons:
Great to see this, Maurizio! Unfortunately it arrives a week too late, and
in the wrong repository, to be included in jdk7.
I notice that none of the tests show a variable of function type being
converted to a SAM type. What are the plans there?
Jonathan Gibbons' response:
Since the published feature list for jdk7 and the published schedule for
jdk7 would appear to be at odds, why do you always assume the schedule
is correct?
Neal Gafter's answer:
Because I recall repeated discussion to the effect that the feature set
would be adjusted based on their completion status with respect to the
schedule.
Some people even question if the whole thing makes sense anymore and suggest moving to another language:
One starts to wonder, why not just move to Scala -- there's much more
that needs to be added to Java in order to build a coherent combination
of features around lambdas. And now these delays, which affect not just
users of ParallelArray but everyone who wants to build neatly refactored,
testable software in Java.
Seems like nobody's proposing to add declaration-site variance in Java
=> means FunctionN<T, ...> interfaces will not subtype the way they should.
Nor is there specialization for primitives. (Scala's #specialized is
broken for all but toy classes, but at least it's moving in the right
direction)
No JVM-level recognition that an object is a closure, and can hence be
eliminated, as it can be with Scala's closure elimination (if the HOF can
also be inlined.) The JVM seems to add something like an unavoidable machine
word access to every polymorphic call site, even if they are supposedly
inline-cached and not megamorphic, even inside a loop. Result that I've
seen is approximately a 2x slowdown on toy microbenchmarks like "sum an array
of integers" if implemented with any form of closures other than something
that can be #inline'd in Scala. (And even in Scala, most HOF's are virtual
hence can't be inlined.) I for one would like to see usable inlining in a
language that /encourages/ the use of closures in every for loop.
Conclusion
This is just a quick look at the whole problem going on and the quotes and statements are not exhaustive at all. At the moment people are still in the state of "Can closures really be done in Java and if yes, how should it be done and how might it look like?".
There is no simple "OK, we just add closures to Java over the weekend".
Due to the interaction of some design mistakes like varargs as arrays, type erasure ... there are cases which just can't work. Finding all these small problems and deciding if they are fixable is quite hard.
In the end, there might be some surprises.
I'm not sure what that surprise will be, but I guess it will be either:
Closures won't get into Java 7 or
Closures in Java 7 will be what Generics were in Java 5 (Buggy, complex stuff, which looks like it might work, but breaks apart as soon as you push things a bit further)
Personal opinion
I switched to Scala a long time ago. As long as Oracle doesn't do stupid things to the JVM, I don't care anymore. In the evolutionary process of the Java language mistakes were made, partly due to backward compatibility. This created an additional burden with every new change people tried to make.
Basically: Java works, but there will be no evolution of the language anymore. Every change people make increases the cost of making the next change, making changes in the future more and more unlikely.
I don't believe that there will be any changes to the Java language after Java 7 apart from some small syntax improvements like project Coin.
http://java.dzone.com/news/closures-coming-java-7
The latest news is AFAIK still as of late Nov 2009 that closures will be in Java 7 in some form. Since this was given as the main reason for a significant delay in the release, it seems pretty unlikely that they'll drop it again.
There's been a whole lot of syntax and transparency related debating (particularly focusing on how hard to read a currying function with a particular syntax is, it seems like) going on on the lambda-dev mailing list, and there have been a couple draft proposal iterations from Sun, but I haven't seen much from them on that list in a while.
I'm at a release conference now and the speaker is saying closures are coming to Java 8.

Categories