Tuesday, August 29, 2023

C# vs Java programming comparison

 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!);
    }
}
```
a. 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 -
a. Use `extends` for inheriting from another class. This can be from one class only.
b. No virtual or override, instead methods of the same signatures are overridden.
c. Use `implements` to implement from an Interface and for multiple inheritance.
d. If not implementing an interface, mark it as abstract. Only abstract classes can have abstract fields.

3. Classes -
a. Avoid modifiers to it, at least when learning. If using public it has to be in its own file.

4. 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.

5. Compiling the source code.
`javac Pgm.java`

6. Running the program.
`java Pgm`

7. 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`

8. Statements -
a. All if, else, while and for loops are similar.
b. Switch cases can have multiple with comma separtions like `case SATURDAY, SUNDAY -> "week end";`

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

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

11. Generics seem similar


No comments:

Post a Comment

Browser background color or monitor brightness

Have you been in a situation where you are almost sitting the whole day in front of your browser and going through a document and find that ...