Home ...

C# vs Java programming comparison

Ragavendra B.N.
Ragavendra B.N.

This guide is for those who like to learn Java and are from the C# background or vice - versa or similar who are pretty much versed in it. I have documented the aspects which needs to be grasped and is different from C#.

  1. First line of code can be say a Pgm.java file like below.
class Pgm
{
    public static void main(String[] args)
    {
        System.out.println("Learning Java!);
    }
}
  1. The name of the file should be the same as the class inside. Main method is main here and string is String here.

  2. Inheritance -

  3. Use extends for inheriting from another class. This can be from one class only.

  4. No virtual or override, instead methods of the same signatures are overridden.

  5. Use implements to implement from an Interface and for multiple inheritance.

  6. If not implementing an interface, mark it as abstract. Only abstract classes can have abstract fields.

  7. Classes -

  8. Avoid modifiers to it, at least when learning. If using public it has to be in its own file.

  9. Lambda methods - Similar to C#, use -> instead, like Predicate<String> pred = s -> s.length() == 3; and do pred.test("111") which returns true if matching the predicate.

  10. Compiling the source code. javac Pgm.java

  11. Running the program. java Pgm

  12. Packages - Like namespaces, supposed to be the name of the folder but no compilation errors will be issued. Use like package abc.def.ghi; When compiling, one may have to do javac -d . Pgm.java and when running java abc.def.ghi.Pgm

  13. Statements -

  14. All if, else, while and for loops are similar.

  15. Switch cases can have multiple with comma separtions like case SATURDAY, SUNDAY -> "week end";

  16. Encapsulation - No properties here for classes. Create your own getter and setter individual methods.

  17. Concurrent List - To make a list concurrent or thread safe, you can do List newList = Collections.synchronizedList(eles);

  18. Generics seem similar