Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Examples == === Input/output === Example illustrating how to copy text one line at a time from one file to another, using both languages. {| class="wikitable" |- ! Java ! C# |- |valign=top|<syntaxhighlight lang="Java" style="font-size:90%"> import java.nio.file.*; class FileIOTest { public static void main(String[] args) throws Exception { var lines = Files.readAllLines(Paths.get("input.txt")); Files.write(Paths.get("output.txt"), lines); } } </syntaxhighlight> |valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> using System.IO; class FileIOTest { public static void Main(string[] args) { var lines = File.ReadLines("input.txt"); File.WriteAllLines("output.txt", lines); } } </syntaxhighlight> |- |valign=top|Notes on the Java implementation: * {{code|Files.readAllLines}} method returns a List of String, with the content of the text file, Files has also the method {{mono|readAllBytes}}, returns an array of {{mono|Strings}}. * {{code|Files.write}} method writes byte array or into an output file, indicated by a Path object. * {{code|Files.write}} method also takes care of buffering and closing the output stream. |valign=top|Notes on the C# implementation: * The {{mono|ReadLines}} method returns an enumerable object that upon enumeration will read the file one line at a time. * The {{mono|WriteAllLines}} method takes an enumerable and retrieves a line at a time and writes it until the enumeration ends. * The underlying reader will automatically allocate a buffer, thus there is no need to explicitly introduce a buffered stream. * {{mono|WriteAllLines}} automatically closes the output stream, also in the case of an abnormal termination. |} === Integration of library-defined types === C# allows library-defined types to be integrated with existing types and operators by using custom implicit/explicit conversions and operator overloading as illustrated by the following example: {| style="width:100%;" class="wikitable" |- ! style="width:50%;"|Java !! style="width:50%;"| C# |- | <syntaxhighlight lang=Java style="font-size:90%"> var bigNumber = new BigInteger("123456789012345678901234567890"); var answer = bigNumber.multiply(BigInteger.valueOf(42)); var square = bigNumber.sqrt(); var sum = bigNumber.add(bigNumber); </syntaxhighlight> | <syntaxhighlight lang="csharp" style="font-size:90%"> var bigNumber = BigInteger.Parse("123456789012345678901234567890"); var answer = bigNumber * 42; var square = bigNumber * bigNumber; var sum = bigNumber + bigNumber; </syntaxhighlight> |} === C# delegates and equivalent Java constructs === {| style="width:100%;" class="wikitable" |- ! style="width:50%;"| Java !! style="width:50%;"| C# |- valign="top" | <syntaxhighlight lang=Java style="font-size:90%"> // a target class class Target { public boolean targetMethod(String arg) { // do something return true; } } // usage void doSomething() { // construct a target with the target method var target = new Target(); // capture the method reference Function<String, Boolean> ivk = target::targetMethod; // invokes the referenced method var result = ivk.apply("argumentstring"); } </syntaxhighlight> |<!-- This is Visual Studio Default Style. C# is generally GNU not Ritchie --> <syntaxhighlight lang="csharp" style="font-size:90%"> // a target class class Target { public bool TargetMethod(string arg) { // do something return true; } } // usage void DoSomething() { // construct a target with the target method var target = new Target(); // capture the delegate for later invocation Func<string, bool> dlg = target.TargetMethod; // invoke the delegate bool result = dlg("argumentstring"); } </syntaxhighlight> |} === Type lifting === {| style="width:100%;" class="wikitable" |- ! style="width:50%;"| Java !! style="width:50%;"| C# |- valign="top" | Java doesn't have this feature, although a similar effect is possible with the {{mono|Optional}} class <syntaxhighlight lang="java"> var a = Optional.of(42); var b = Optional.<Integer>empty(); var c = a.flatMap(aa -> b.map(bb -> aa * bb)); </syntaxhighlight> |<!-- This is Visual Studio Default Style. C# is generally GNU not Ritchie --> <syntaxhighlight lang="csharp"> int? a = 42; int? b = null; // c will receive the null value // because*is lifted and one of the operands are null int? c = a * b; </syntaxhighlight> |} ===Interoperability with dynamic languages=== This example illustrates how Java and C# can be used to create and invoke an instance of class that is implemented in another programming language. The "Deepthought" class is implemented using the [[Ruby (programming language)|Ruby programming language]] and represents a simple calculator that will multiply two input values ({{mono|a}} and {{mono|b}}) when the {{mono|Calculate}} method is invoked. In addition to the conventional way, Java has [[GraalVM]], a virtual machine capable to run any implemented programming language. {| style="width:100%; border:none;" class="wikitable" |- !width=50%|Java !width=50%|C# |- |valign=top| ====Using GraalVM==== <syntaxhighlight lang=Java style="font-size:90%"> Context polyglot = Context.newBuilder().allowAllAccess(true).build(); //Ruby Value rubyArray = polyglot.eval("ruby", "[1,2,42,4]"); int rubyResult = rubyArray.getArrayElement(2).asInt(); //Python Value pythonArray = polyglot.eval("python", "[1,2,42,4]"); int pythonResult = pythonArray.getArrayElement(2).asInt(); //JavaScript Value jsArray = polyglot.eval("js", "[1,2,42,4]"); int jsResult = jsArray.getArrayElement(2).asInt(); //R Value rArray = polyglot.eval("R", "c(1,2,42,4)"); int rResult = rArray.getArrayElement(2).asInt(); //LLVM (in this case C, but could be C++, Go, Basic, etc...) Source source = Source.newBuilder("llvm", new File("C_Program.bc")).build(); Value cpart = polyglot.eval(source); cpart.getMember("main").execute(); </syntaxhighlight> ====Traditional way==== <syntaxhighlight lang="java" style="font-size:90%"> // Initialize the engine var invocable = new ScriptEngineManager().getEngineByName("jruby"); var rubyFile = new FileReader("Deepthought.rb"); engine.eval(fr); </syntaxhighlight> <syntaxhighlight lang="java" style="font-size:90%"> // create a new instance of "Deepthought" calculator var calcClass = engine.eval("Deepthought"); var calc = invocable.invokeMethod(calcClass, "new"); // set calculator input values invocable.invokeMethod(calc, "a=", 6); invocable.invokeMethod(calc, "b=", 7); // calculate the result var answer = invocable.invokeMethod(calc, "Calculate"); </syntaxhighlight> |valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> // Initialize the engine var runtime = ScriptRuntime.CreateFromConfiguration(); dynamic globals = runtime.Globals; runtime.ExecuteFile("Deepthought.rb"); </syntaxhighlight> <syntaxhighlight lang="csharp" style="font-size:90%"> // create a new instance of "Deepthought" calculator var calc = globals.Deepthought.@new(); // set calculator input values calc.a = 6; calc.b = 7; // calculate the result var answer = calc.Calculate(); </syntaxhighlight> |- valign=top | Notes for the Java implementation: * Ruby accessors names are generated from the attribute name with a {{code|{{=}}}} suffix. When assigning values, Java developers must use the Ruby accessor method name. * Dynamic objects from a foreign language are not first-class objects in that they must be manipulated through an API. | Notes for the C# implementation: * Objects returned from properties or methods of {{mono|dynamic}} objects are themselves of {{mono|dynamic}} type. When type inference (the {{mono|var}} keyword) is used, the variables calc and answer are inferred dynamic/late-bound. * Dynamic, late-bounds objects are first-class citizens that can be manipulated using C# syntax even though they have been created by an external language. *{{mono|new}} is a reserved word. The {{code|@}} prefix allows keywords to be used as identifiers. |} === Fibonacci sequence === This example illustrates how the [[Fibonacci sequence]] can be implemented using the two languages. The C# version takes advantage of C# [[#Generator methods|generator methods]]. The Java version takes the advantage of {{mono|Stream}} interface and method references. Both the Java and the C# examples use [[K&R style]] for code formatting of classes, methods and statements. {| style="width:100%; border:none;" class="wikitable" |- !Java !C# |- |width=50%|<syntaxhighlight lang=Java style="font-size:90%"> // The Fibonacci sequence Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }).limit(10).forEach(System.out::println); </syntaxhighlight> |width=50% valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> // The Fibonacci sequence public IEnumerable<int> Fibonacci() { int a = 0; int b = 1; while (true) { yield return a; (a, b) = (b, a + b); } } </syntaxhighlight> |- |width=50%| |width=50% valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> // print the 10 first Fibonacci numbers foreach (var it in Fibonacci().Take(10)) { Console.WriteLine(it); } </syntaxhighlight> |- valign="top" |Notes for the Java version: * The Java 8 Stream interface is a sequence of elements supporting sequential and parallel aggregate operations. * The generate method returns an infinite sequential unordered stream where each element is generated by the provided Supplier. * The limit method returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. * The forEach method performs an action for each element of this stream, this action could be a lambda or a method reference. ====Using a foreach==== The same example above, but using a method returning an Iterable to maintain greater similarity with the C# example. Anything that implements the iterable interface can be iterated in a foreach. <syntaxhighlight lang="java" style="font-size:90%"> Iterable<Integer> fibonacci(int limit) { return Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }).limit(limit)::iterator; } </syntaxhighlight> <syntaxhighlight lang="java" style="font-size:90%"> // print the 10 first Fibonacci numbers for(int it: fibonacci(10)) { System.out.println(it); } </syntaxhighlight> The most common way to do the example above would be to use Streams, not Iterables. This could be returned from a method like the C# example, but it's unnecessary and could be used directly by just collecting the Stream. Below is an example using Streams and the collecting the Stream calling {{mono|toList}} in the foreach block. <syntaxhighlight lang="java" style="font-size:90%"> var fibonacci = Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }); </syntaxhighlight> <syntaxhighlight lang="java" style="font-size:90%"> // print the 10 first Fibonacci numbers for(int it: fibonacci.limit(10).toList()) { System.out.println(it); } </syntaxhighlight> In addition to the toList collector in the foreach block, It's important to highlight that there are more collectors for every type of collection. Also, custom collectors could be created by implementing the {{mono|Collector}} interface or describing the implementation as a lambda expression, both cases passing it as arguments to the collect method of the {{mono|Stream}} object. In this example would be just calling the {{mono|collect}} method instead {{mono|toList}} if would have some complex type of object per item for the collection. Both examples could also be done with {{mono|IntStream}} and {{mono|IntSupplier}} and avoid the {{mono|Integer}} generic in the {{mono|Supplier}} interface implementation, but the generic is used to preserve greater similarity with the C# example. ====Functional Style==== The above algorithm can be written even more consistently, using {{code|Stream.iterate}}. The iterate method receives a seed parameter, and a function that specifies what to do for each iteration. In this case, the seed can be a record class with the 2 initial values of the algorithm, and its respective transformation in each iteration. In short, the iterate method makes unnecessary the implementation of a Supplier. <syntaxhighlight lang="java" style="font-size:90%"> record Pair(int a, int b) {}; Stream .iterate(new Pair(0, 1), p -> new Pair(p.b, p.a + p.b)) .limit(10) .map(p -> p.a) .forEach(System.out::println); </syntaxhighlight> |Notes for the C# version: * The method is defined as returning instances of the interface {{csharp|IEnumerable<int>}}, which allows client code to repeatedly request the next number of a sequence. * The {{csharp|yield}} keyword converts the method into a generator method. * The {{csharp|yield return}} statement returns the next number of the sequence and creates a continuation so that subsequent invocations of the {{csharp|IEnumerable}} interface's {{csharp|MoveNext}} method will continue execution from the following statement with all local variables intact. * Tuple-assignment avoids the need to create and use a temporary variable when updating the values of the variables {{mono|a}} and {{mono|b}}. |}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)