Differences between C# and Java

I’ve just had convert some C# into Java and have noticed the following differences between these two languages (that are often thought to be so similar as to make no difference). In no particular order:

  • Java uses packages, C# uses namespaces
  • Java uses “import” to bring in classes, C# uses “using”
  • Java classes (public ones) must be in a .java file with the same name as the class, C# doesn’t care
  • Java Strings must be Strings, C# has strings as well
  • Java doesn’t have ‘out’ parameters
  • Java functions must declare if they throw exceptions, C# doesn’t care
  • Java doesn’t have unsigned integer types, C# does
  • Java system namespaces start with “java.*”, C#’s start with “System.*”
  • Java doesn’t have support for accessor/setter methods in the language, C# does
  • Java uses words like “implements” and “extends” for inheritance, C# uses the : operator
  • Java doesn’t have a .TryParse method, C# does
  • Java has final, C# has const and readonly
  • Java can’t use enum constants in switch statements, C# can
  • Java can’t use [] on a String to access chars, C# can.

     

Not a problem for the current exercise, but other differences are:

  • Java misses partial classes
  • Java misses lamda functions (although there are proposals to include Lamda functions in Java BGGA)
  • Java (out of the box) doesn’t have some of the functional features of C#

There are only a couple of things I would conclude from this

  • Don’t assume that C# is a superior language just because it has loads more bling features
  • Don’t underestimate the task of converting non-trivial C# classes to Java

Breaking the Java Compiler with ANTLR

I’ve been doing a bit of work with ANTLR and Java. The work was gathering momentum and I had developed a modest size set of ANTLR rules from which I was generating Java code. To be honest, I was feeling quite good about life at this point.

Then from out of nowhere came a Java compiler error…

[along the lines of] Java method size exceeds 64 KB.

Now I thought limits like this were banished from the world of computing well before the days of Java. But no, the Java class file formats stores method lengths in 2 bytes, and it would appear this is a showstopper.

Fortunately, ANTLR is clever enough to reduce the size of its code generated methods. Instead of many nested “if” statements, it can use a table of DFA states. To achieve this, you must use the following command line to generate the Java code (I couldn’t find a way to do this ANTLRWORKS)

C: java org.antlr.Tool –Xmaxinlinedfastates [a number less than 60] grammar.g

Social Responsibility for Geeks – Chapter One

Well, I attended a developer event yesterday and you won’t be surprised to hear that several people describe their projects and technology as “awesome”. I think this word is overused.

Something is only awesome if it contributes (in a significant and transparent way) to:

  • The end of disease
  • World peace
  • The end of prejudice and injustice
  • ….

Otherwise, please refrain from exaggerating, and stick with being mildly pleased with whatever you have achieved, and think about whether you have actually contributed to any of the above goals!

 

Higher Order Functions

I’ve been doing a bit C#,F# and C++ recently and have started to use higher order functions a lot. I think they are a great way of simplifying code, so you’ll spending more time writing domain specific code rather than having to keep writing while and for loops, and having to keep balancing brackets.
    

Why should you use higher order functions? Well, one reason is that your code can be optimised without having to make any large changes. For instance, the parallel version of some of the higher order functions has virtually identical syntax to the single threaded version.
    

One of the confusing things about the higher order functions is that they have different names across the different languages. This shouldn’t matter too much, but I’m still seeing the need to do a comparison across the three languages (stated above) just to get it clear in my head.
    

So, here goes…

Set Iteration F#  
let myArray = [| 1 ; 2 ; 3 |]
myArray |> Seq.iter (fun x -> printfn "%d" (x * 2))
C#  
int[] myArray = new int[] { 1, 2, 3 };
Array.ForEach(
myArray,
(i) => System.Console.WriteLine(i*2)
);
  
C++ STL  
int arrayVals[] = {1,2,3};
std::vector<int>myArray(arrayVals,&arrayVals[3]);
std::for_each (
myArray.begin(),
myArray.end(),
[&](int n){
std::cout << (n*2) << std::endl;
}
);
  
Set mapping F#  
let myArrayDoubled = myArray |> Seq.map (fun x -> x*2)
C#   

int[] doubledSet = myArray.Select( (n) => n*2

  

).ToArray(); 

 

  

C++ STL
int doublen(int n){

  

return n*2; 

 

}  

…  

std::vector<int> doubledArray;  

std::transform(  

myArray.begin(),  

myArray.end(),  

std::back_inserter(doubledArray),  

&doublen  

);  

Set concatenation F#   

let myListOfArrays = [ [| 1;2;3 |] ;

  

[| 4;5;6 |] ; 

 

[| 7;8;9 |] ]  

let concatenatedList = Seq.concat myListOfArrays  

C#   

List<int[]> myListOfArrays = new List<int[]>();

  

myListOfArrays.Add( 

 

new int[] { 1, 2, 3 });  

myListOfArrays.Add(  

new int[] { 4, 5, 6 });  

myListOfArrays.Add(  

new int[] { 7, 8, 9 });  

int[] newArray = myListOfArrays.SelectMany(  

(n) => n).ToArray();  

C++ STL  I think you could do something here with “accumulate” and a functor object – but as far as I can see there is nothing “out of the box” to do this.
Fold (aggregation) F#   

let total = myArray |>

  

Seq.fold ( 

 

fun state item -> state + item)  

0 // initial value of state  

printfn "%d" total    

C# int total = myArray.Aggregate(0, (state, item) => state + item);
C++ STL  int total =   std::accumulate(       myArray.begin(),    

       myArray.end(),    

       0    

);    

Unfold (set initialisation) F#   let fibs = (1,1) |> Seq.unfold (fun (n0,n1) -> Some(n0,(n1,n0 + n1)))
C#  static IEnumerable<int> Fibonacci(int n0, int n1)
{
 int _n0 = n0;
        int _n1 = n1;
        yield return n0;
        yield return n1;
        while (true)
        {
            int temp = _n1;
            _n1 = _n0 + _n1;
            _n0 = temp;
            yield return _n1;
        }
} … 

var fib = Fibonacci(1, 1); 
int[] first5fib = fib.Take(5).ToArray(); 

  

  

 

  

C++ STL  std::vector<int> fibseq;
Fibonacci acc(1,1);
std::generate_n(
 back_inserter(fibseq),
 5,
 acc
); … class Fibonacci
{
 int _x0;
 int _x1;
 int _callcount;  public:
 Fibonacci(int x0,int x1)
  : _x0(x0),
   _x1(x1),
   _callcount(0)
 {
 }   

 int operator() ()
 {
  if (_callcount == 0)
  {
   ++_callcount;
   return _x0;
  }
  else if (_callcount++ == 1)
  {
   ++_callcount;
   return _x1;
  }
  else
  {
   int temp = _x1;
   _x1 = _x0 + _x1;
   _x0 = temp;
   return _x1;
  }
 }
};   

The trials of porting Visual C++ projects to gcc on Linux

Recently I have had the pleasurable experience of porting some C++ code developed on Visual Studio 2010 to work on GCC on Linux. You’d have thought with C++ being a defined standard it would just work (but then you stop dreaming). Here is a list of the problems I encountered:

  • #includes are case sensitive

#include "stdio.h" does not equal #include "Stdio.h"
This was easy to fix.

  • dependant types must be prefixed with the “typename” keyword

I had a templated class, in which I was using one of the STL’s template containers with the template class. An example explains this better…

// in Visual C++
template<class T>
class MyClass<T>
{
...
void MyMethod()
{
...
std::vector<T>::iterator it;
...
}
...
};

GCC requires std::vector::iterator to be prefixed with the typename keyword. At least GCC compiler errors pointed me in the right direction.

  • compiler warnings in Visual C++ are compiler errors on GCC

 GCC is much more fussy about the types you are allowed to implicitly cast between. Putting a few explicit casts into the code fixed this one.

  • default boolean return type is false on GCC, true on Visual C++

This was an odd one. I had a method with a boolean return type. Except I wasn’t returning anything..

bool method()
{
// no return statement
}
...
bMethodSuccess = method();
...

I would have thought that this shouldn’t compile – yet it did, and Visual C++ was not setting bMethodSuccess. However, Gcc will generate the code to return false, resulting in a program that behaves differently. Slapped wrist for not spotting this sooner.

I expect I might find other subtleties, so I may update this blog post in the future.