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!
== Types == {| class="wikitable" |- ! [[#Data types|Data types]]!! Java !! C# |- | [[#Advanced numeric types|Arbitrary-size decimals]] || {{yes|Reference type; no operators}}<ref>{{cite web |url=http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html |title=BigDecimal (Java 2 Platform SE 5.0) |publisher=Docs.oracle.com |access-date=24 February 2015}}</ref> || {{no|Third-party library|style=background: #8CF;}}<ref>{{cite web |url=https://wezeku.github.io/Mpir.NET/ |title=Mpir.NET |access-date=17 July 2015}}</ref> |- | [[#Advanced numeric types|Arbitrary-size integers]] || {{yes|Reference type; no operators}} || {{yes}}<ref name="microsoft1">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-7.0 |title=BigInteger Struct (System.Numerics) |publisher=learn.microsoft.com |access-date=14 April 2023}}</ref> |- | [[#Arrays and collections|Arrays]] || {{yes}}<ref>{{cite web |url=http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html |title=Collection (Java 2 Platform SE 5.0) |publisher=Docs.oracle.com |access-date=20 May 2015}}</ref> || {{yes}} |- | [[Boolean type]] || {{yes}} || {{yes}} |- | [[Primitive data type#Characters and strings|Character]] || {{yes}}<ref>{{cite web |url=http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html |title=String (Java 2 Platform SE 5.0) |publisher=Docs.oracle.com |access-date=20 May 2015}}</ref> || {{yes}} |- | [[#Advanced numeric types|Complex numbers]] || {{no|Third-party library|style=background: #8CF;}}<ref>{{cite web |url=https://commons.apache.org/proper/commons-math/userguide/complex.html |title=Math – The Commons Math User Guide – Complex Numbers |access-date=17 July 2015}}</ref> || {{yes}} |- | Date/time || {{yes}}; reference type<ref>{{cite web |url=http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html |title=Date (Java 2 Platform SE 5.0) |publisher=Docs.oracle.com |access-date=20 May 2015}}</ref> || {{yes}}; value type |- | [[#Enumerations|Enumerated types]] || {{yes}}; reference type || {{yes}}; scalar |- | High-precision decimal number || {{no|style=background: #8CF;}}; but see 'Arbitrary-size decimals' above || {{yes|[[128-bit computing|128-bit]] (28 digits) decimal type<ref>{{cite web |title=decimal (C# Reference) |url=https://msdn.microsoft.com/en-us/library/364x0z75.aspx |publisher=Microsoft |access-date=30 November 2015}}</ref>}} |- | IEEE 754 [[binary32]] floating point number || {{yes}} || {{yes}} |- | IEEE 754 [[binary64]] floating point number || {{yes}} || {{yes}} |- | [[#Lifted (nullable) types|Lifted (nullable) types]] || {{no|style=background: #8CF;}}; but wrapper types || {{yes}} |- | [[#Pointers|Pointers]] || {{no|style=background: #8CF;}};<ref name="oracle.com">{{cite web |url=http://www.oracle.com/technetwork/java/simple-142616.html#4107 |title=The Java Language Environment |publisher=Oracle.com |access-date=18 August 2013}}</ref> only method references<ref name="oracle1">{{cite web |url=http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html |title=Method References (The Java Tutorials > Learning the Java Language > Classes and Objects) |publisher=Docs.oracle.com |date=28 February 2012 |access-date=24 February 2015}}</ref> || {{yes}}<ref>Only available in ''unsafe mode'' or through ''IntPtr'' managed type</ref> |- | [[#Reference types|Reference types]] || {{yes}} || {{yes}} |- | [[Signedness|Signed integers]] || {{yes}}; [[8-bit computing|8]], [[16-bit computing|16]], [[32-bit computing|32]], [[64-bit computing|64 bits]] || {{yes}}; 8, 16, 32, 64 bits |- | [[Primitive data type#Characters and strings|Strings]] || {{yes|Immutable reference type, [[Unicode]]}} || {{yes|Immutable reference type, [[Unicode]]}} |- | Type annotations || {{yes}} || {{yes}} |- | [[Type system#Unified type system|Single-root (unified) type system]] || {{no|style=background: #8CF;}}; but wrapper types || {{yes}}<ref>The type system is unified by default, unless the compiler is switched into ''unsafe mode'' where raw pointers are available as a datatype. Pointers are not derived from object nor does it have implicit conversions to/from the object data type</ref> |- | [[Tuples]] || {{no|style=background: #8CF;}}; limited third-party available<ref>{{cite web |url=http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html |title=org.apache.commons.lang3.tuple (Apache Commons Lang 3.4-SNAPSHOT API) |publisher=Commons.apache.org |date=15 January 2014 |access-date=24 February 2015}}</ref> || {{yes}}<ref name="C# Tuple class">{{cite web |title=Tuple Class (System) |url=https://learn.microsoft.com/en-us/dotnet/api/system.tuple |website=learn.microsoft.com |publisher=Microsoft Corporation |access-date=20 April 2023}}</ref><ref name="C# value tuples">{{Cite web |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples |title=Tuple types (C# reference) |website=learn.microsoft.com |publisher=Microsoft Corporation |access-date=20 April 2023}}</ref> |- | [[Unsigned integers]] || {{no|style=background: #8CF;}}; but some method support<ref>{{cite web |url=https://blogs.oracle.com/darcy/entry/unsigned_api |title=Unsigned Integer Arithmetic API now in JDK 8 (Joseph D. Darcy's Oracle Weblog) |publisher=Blogs.oracle.com |access-date=24 February 2015 |archive-date=25 February 2017 |archive-url=https://web.archive.org/web/20170225213350/https://blogs.oracle.com/darcy/entry/unsigned_api |url-status=dead}}</ref> || {{yes}}; 8, 16, 32, 64 bits |- | [[#User-defined value type (struct)|Value types]] || {{no|style=background: #8CF;}}; only primitive types || {{yes}} |} === Unified type system === Both languages are statically typed with class-based object orientation. In Java the [[primitive types]] are special in that they are not [[object-oriented]] and they could not have been defined using the language itself. They also do not share a common ancestor with reference types. The Java [[reference type]]s all derive from a common root type. C# has a unified [[type system]] in which all types (besides unsafe pointers<ref name="unsafe pointers">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code#pointer-types |title=Unsafe code, pointer types, and function pointers |publisher=learn.microsoft.com |date=29 May 2022 |access-date=14 April 2023}}</ref>) ultimately derive from a common root type. Consequently, all types implement the methods of this root type, and extension methods defined for the {{mono|object}} type apply to all types, even primitive {{mono|int}} literals and [[Delegate (CLI)|delegates]]. This allows C#, unlike Java, to support objects with encapsulation that are not reference types. In Java, compound types are synonymous with reference types; methods cannot be defined for a type unless it is also a ''class'' reference type. In C# the concepts of encapsulation and methods have been decoupled from the reference requirement so that a type can support methods and encapsulation without being a reference type. Only reference types support [[virtual method]]s and specialization, however. Both languages support many [[built-in type]]s that are copied and passed by value rather than by reference. Java calls these types [[primitive type]]s, while they are called ''simple types'' in C#. The primitive/simple types typically have native support from the underlying processor architecture. The C# simple types implement several [[Interface (object-oriented programming)|interfaces]] and consequently offer many methods directly on instances of the types, even on the literals. The C# type names are also merely ''aliases'' for [[Common Language Runtime]] (CLR) types. The C# {{code|System.Int64}} type is exactly the same type as the {{mono|long}} type; the only difference is that the former is the canonical [[.NET]] name, while the latter is a C# alias for it. Java does not offer methods directly on primitive types. Instead, methods that operate on primitive values are offered through companion [[primitive wrapper class]]es. A fixed set of such wrapper classes exist, each of which wraps one of the fixed set of primitive types. As an example, the Java {{mono|Long}} type is a [[reference type]] that wraps the primitive {{mono|long}} type. They are ''not'' the same type, however. === Data types === ==== Numeric types ==== ===== Signed integers ===== Both Java and C# support [[signedness|signed]] integers with bit widths of 8, 16, 32 and 64 bits. They use the same name/aliases for the types, except for the 8-bit integer that is called a {{mono|byte}} in Java and a {{mono|sbyte}} (signed byte) in C#. ===== Unsigned integers ===== C# supports [[signedness|unsigned]] in addition to the [[signedness|signed]] integer types. The unsigned types are {{mono|byte}}, {{mono|ushort}}, {{mono|uint}} and {{mono|ulong}} for 8, 16, 32 and 64 bit widths, respectively. Unsigned arithmetic operating on the types are supported as well. For example, adding two unsigned integers ({{mono|uint}}s) still yields a {{mono|uint}} as a result; not a long or signed integer. Java does not feature unsigned integer types. In particular, Java lacks a primitive type for an unsigned [[byte]]. Instead, Java's {{mono|byte}} type is [[sign extension|sign extended]], which is a common source of bugs and confusion.<ref>{{cite book |title=Java puzzlers : traps, pitfalls, and corner cases|year=2005 |publisher=Addison-Wesley|location=Upper Saddle River, NJ [u.a.]|isbn=978-0-321-33678-1|author=Joshua Bloch; Neal Gafter|edition=5. print.|page=36|quote=The lesson for language designers is that sign extension of byte values is a common source of bugs and confusion. The masking that is required to suppress sign extension clutters programs, making them less readable. Therefore, the byte type should be unsigned.}}<!-- |access-date=6 October 2012--></ref> Unsigned integers were left out of Java deliberately because [[James Gosling]] believed that programmers would not understand how unsigned arithmetic works.<blockquote>In programming language design, one of the standard problems is that the language grows so complex that nobody can understand it. One of the little experiments I tried was asking people about the rules for unsigned arithmetic in C. It turns out nobody understands how unsigned arithmetic in C works. There are a few obvious things that people understand, but many people don't understand it.<ref name="oracle.com"/><ref>{{cite web |url=http://www.artima.com/intv/gosling3P.html |title=James Gosling on Java, May 2001 |publisher=Artima.com |date=10 May 2001 |access-date=24 February 2015}}</ref></blockquote> Java versions 8 and 9 added some limited built-in unsigned integer operations, but they are only exposed as static methods on the primitive wrapper classes; they operate on signed primitive integer types, treating them as if they were unsigned.<ref>{{cite web |url=https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html |title=Integer (Java Platform SE 8) |publisher=Docs.oracle.com |access-date=20 Apr 2023}}</ref> ===== High-precision decimal numbers ===== C# has a type and literal notation for high-precision (28 decimal digits) decimal arithmetic that is appropriate for financial and monetary calculations.<ref>{{cite web |title=decimal |url=http://msdn.microsoft.com/en-us/library/364x0z75(v=vs.110).aspx | work=C# Reference |date=19 August 2012 |publisher=Microsoft}}</ref><ref name="thedecimaltype"/><ref>{{cite book | last=Mok | first=Heng Ngee |title=From Java to C? : a developer's guide |year=2003 |publisher=Addison-Wesley|location=Harlow, England | isbn=978-0-321-13622-0 | chapter=9.5. The decimal type}}</ref> Contrary to the {{mono|float}} and {{mono|double}} data types, decimal fractional numbers such as 0.1 can be represented exactly in the decimal representation. In the float and double representations, such numbers often have non-terminating binary expansions, making those representations more prone to round-off errors.<ref name=thedecimaltype>{{cite book | last=Sestoft | first=Jon Jagger, Nigel Perry, Peter |title=C? annotated standard |year=2007 |publisher=Elsevier/Morgan Kaufmann Publishers | location=Amsterdam | isbn=978-0-12-372511-0 | chapter=11.1.7 The decimal type}}</ref> While Java lacks such a built-in type, the Java library does feature an ''arbitrary precision'' decimal type. This is not considered a language type and it does not support the usual arithmetic operators; rather it is a reference type that must be manipulated using the type methods. See more about arbitrary-size/precision numbers [[#Advanced numeric types|below]]. ==== Advanced numeric types ==== Both languages offer library-defined [[arbitrary-precision arithmetic]] types for arbitrary-size integers and decimal point calculations. Only Java has a data type for arbitrary precision decimal point calculations. Only C# has a type for working with [[complex number]]s. In both languages, the number of operations that can be performed on the advanced numeric types is limited compared to the built-in [[IEEE 754]] floating point types. For instance, none of the arbitrary-size types support [[square root]] or [[logarithm]]s. C# allows library-defined types to be integrated with existing types and operators by using custom implicit/explicit conversions and operator overloading. See example in section ''[[#Integration of library-defined types|Integration of library-defined types]]'' ==== Characters ==== Both languages feature a native {{mono|char}} (character) datatype as a simple type. Although the {{mono|char}} type can be used with bit-wise operators, this is performed by promoting the {{mono|char}} value to an integer value before the operation. Thus, the result of a bitwise operation is a numeric type, not a character, in both languages. ==== Built-in compound data types ==== Both languages treat [[String (computer science)|strings]] as ([[immutable object|immutable]]) objects of reference type. In both languages, the type contains several methods to manipulate strings, parse, format, etc. In both languages [[regular expression]]s are considered an external feature and are implemented in separate classes. Both languages' libraries define classes for working with dates, times, [[time zone]]s, and [[calendar]]s in different cultures. Java provides {{code|java.util.Date}}, a mutable reference type with millisecond precision, and (since Java 8) the {{code|java.time}} package (including classes such as {{mono|LocalDate}}, {{mono|LocalTime}}, and {{mono|LocalDateTime}} for date-only, time-only, and date-and-time values), a set of immutable reference types with [[nanosecond]] precision.<ref>{{cite web |url=https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html |title=Package java.time (Java Platform SE 8) |publisher=docs.oracle.com |access-date=20 April 2023}}</ref> In contrast, the C# {{code|System.DateTime}} is an immutable struct value type for date-and-time information with 100-nanosecond precision; the .NET 6 API also added {{code|System.DateOnly}} and {{code|System.TimeOnly}}, similar structures for date-only or time-only operations.<ref>{{cite web |url=https://learn.microsoft.com/en-us/dotnet/standard/datetime/how-to-use-dateonly-timeonly |title=How to use the DateOnly and TimeOnly structures |date=12 January 2023 |publisher=learn.microsoft.com |access-date=20 April 2023}}</ref> C# additionally defines a {{code|System.TimeSpan}} type for working with time periods; Java 8 provides the {{code|java.time.Duration}} class for the same purpose. Both languages support date and time arithmetic according to different cultures and time zones. === User-defined value type (struct) === C# allows the programmer to create user-defined [[value type]]s, using the {{mono|struct}} keyword. Unlike classes and like the standard primitives, such value types are passed and assigned by value rather than by reference. They can also be part of an object (either as a field or [[Boxed type|boxed]]), or stored in an array without the memory indirection that normally exists for class types. Because value types have no notion of a {{mono|null}} value and can be used in arrays without initialization, they always come with an implicit [[default constructor]] that essentially fills the struct memory space with zeroes. The programmer can only define additional constructors with one or more arguments. Value types do not have [[virtual method table]]s, and because of that (and the fixed [[memory footprint]]), they are implicitly sealed. However, value types ''can'' (and frequently do) implement [[Interface (object-oriented programming)|interfaces]]. For example, the built-in integer types implement several [[Interface (object-oriented programming)|interfaces]]. Apart from the built-in primitive types, Java does not include the concept of value types. === {{anchor|Enumerated types}}Enumerations === Both languages define enumerations, but they are implemented in fundamentally different ways. As such, enumerations are one area where tools designed to automatically translate code between the two languages (such as Java to C# converters) fail. C# has implemented enumerations in a manner similar to C, that is as wrappers around the bit-flags implemented in primitive integral types (int, byte, short, etc.). This has performance benefits and improves interaction with C/C++ compiled code, but provides fewer features and can lead to bugs if low-level value types are directly cast to an enumeration type, as is allowed in the C# language. Therefore, it is seen as [[syntactic sugar]].<ref>{{cite web |url=https://www.dotnetperls.com/enum |title=Enum. |publisher=.NET Perls |location=Internet |language=en |access-date=14 November 2016 |quote='''Performance.''' Enums are fast. They are almost never a performance concern. They are just syntactic sugar on a type like int, which is also fast. […] '''Type.''' An enum has an underlying type. Each time we use the enum, we are using the underlying type. The enum has syntactic sugar on top.}}</ref> In contrast, Java implements enumerations as full featured collection of instances, requiring more memory and not aiding interaction with C/C++ code, but providing additional features in [[Reflective programming|reflection]] and intrinsic behavior. The implementation in each language is described in the table below. {| class=wikitable ! ! Java ! C# |- | Definition | In Java, the enumeration type is a [[Class (computer programming)|class]], and its values are [[Object (computer science)|objects]] (instances) of that class. The only valid values are the ones listed in the enumeration. The enumeration type may declare [[Member variable|fields]], allowing each individual enumerated value to reference additional data associated uniquely with that specific value. The enumeration type may also declare or override [[Method (computer programming)|methods]], or implement [[Protocol (object-oriented programming)|interfaces]].<ref name="enum">{{cite web |url=http://www.25hoursaday.com/CsharpVsJava.html#switch |title=A Comparison of Microsoft's C# Programming Language to Sun Microsystems' Java Programming Language |author=Dare Obasanjo |year=2007 |publisher=Dare Obasanjo | quote = In Java, enumerated types are a full-fledged class that means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe. |access-date=6 September 2012 |url-status=live |df=dmy-all |archive-url=https://web.archive.org/web/20011217071122/http://www.25hoursaday.com:80/CsharpVsJava.html |archive-date=17 December 2001}}</ref> | [[Enumeration]]s in C# are implicitly derived from the {{mono|Enum}} type that again is a value type derivative. The value set of a C# enumeration is defined by the ''underlying type'' that can be a signed or unsigned integer type of 8, 16, 32 or 64 bits. The enumeration definition defines names for the selected integer values.<ref name="enum"/><ref>{{cite web |url=http://www.cstruter.com/ |title=Java 5: Taming the Tiger: Syntactic Sugar | last1 = Prof. Dr. Gruntz | first1 = Dominik |date=8 April 2005 | language = de |publisher=Fachhochschule Aargau, Nordwestschweiz |archive-url=https://web.archive.org/web/20120708065042/http://cstruter.com/ |archive-date=8 July 2012 |quote=Enumerationen sind die heimlichen Sieger von Java 1.5. Nach vielen Beteuerungen durch Sun, Enums seien in Java überflüssig und können einfach nachgebildet werden, wurden sie nun doch eingeführt. Die einfachste Möglichkeit einer Enumeration der Jahreszeiten sieht wie folgt aus … Das Schlüsselwort enum steht für eine spezielle Art von Klasse, die eine Enumeration definiert. … ''Im Gegensatz zu anderen Programmiersprachen wie C/C++ und C# kann man ihnen per Gleichheitszeichen keine ganzen Zahlen zuordnen.'' |access-date=10 September 2012 |url-status=dead |df=dmy-all}}</ref> By default the first name is assigned the value 0 (zero) and the following names are assigned in increments of 1. Any value of the underlying primitive type is a valid value of the enumeration type, though an explicit cast may be needed to assign it. |- | Combining | Java enumeration set and map collections provide functionality to combine multiple enumeration values to a combined value. These special collections allow compiler optimization to minimize the overhead incurred by using collections as the combination mechanism. | C# supports bit-mapped enumerations where an actual value may be a combination of enumerated values bitwise or'ed together. The formatting and parsing methods implicitly defined by the type will attempt to use these values. |} In both C# and Java, programmers can use enumerations in a [[switch statement]] without conversion to a string or primitive integer type. However, C# disallows implicit fall-through unless the case statement does not contain any code, as it is a common cause of hard-to-find bugs.<ref>{{cite web |url=http://www.25hoursaday.com/ |title=A Comparison of Microsoft's C# Programming Language to Sun Microsystems' Java Programming Language: C. An Ever So Slight Feeling of Dèjà Vu: 4. Switch Statement |author=Dare Obasanjo |year=2007 |publisher=Dare Obasanjo |archive-url=https://web.archive.org/web/20120919093308/http://25hoursaday.com/ |archive-date=19 September 2012 |access-date=10 September 2012 |url-status=dead |df=dmy-all}}</ref> Fall-through must be explicitly declared using a [[goto]] statement.<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/13940fs2%28v=vs.110%29.aspx |title=goto (C#) |publisher=Msdn.microsoft.com |access-date=18 August 2013}}</ref> === Delegates, method references === C# implements object-oriented method pointers in the form of [[Delegate (CLI)|delegates]]. A delegate is a special type that can capture a reference to a method. This reference can then be stored in a delegate-type variable or passed to a method through a delegate parameter for later invocation. C# delegates support [[Covariance and contravariance (computer science)|covariance and contravariance]], and can hold a reference to any signature-compatible static method, instance method, anonymous method or [[Anonymous function|lambda expression]]. Delegates should not be confused with closures and inline functions. The concepts are related because a reference to a closure/inline function must be captured in a delegate reference to be useful at all. But a delegate does not always reference an inline function; it can also reference existing static or instance methods. Delegates form the basis of C# [[#Event|events]], but should not be confused with those either. Delegates were deliberately left out of Java because they were considered unnecessary and detrimental to the language, and because of potential performance issues.<ref name="JavaDelegates">{{cite web|url=http://java.sun.com/docs/white/delegates.html |title=Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle |publisher=Java.sun.com |access-date=24 February 2015 |url-status=dead |archive-url=https://web.archive.org/web/20120627043929/http://java.sun.com/docs/white/delegates.html |archive-date=27 June 2012 }}</ref> Instead, alternative mechanisms are used. The [[wrapper pattern]], which resembles the delegates of C# in that it allows the client to access one or more client-defined methods through a known [[Interface (object-oriented programming)|interface]], is one such mechanism.{{citation needed |date=March 2012}} Another is the use of [[Adapter pattern|adapter]] objects using inner classes, which the designers of Java argued are a better solution than bound method references.<ref name="JavaDelegates"/> See also example [[#C# delegates and equivalent Java constructs|C# delegates and equivalent Java constructs]]. === {{anchor|Nullable types}}Lifted (nullable) types === C# allows value/primitive/simple types to be "lifted" to allow the special {{mono|null}} value in addition to the type's native values. A type is lifted by adding a {{code|?}} suffix to the type name; this is equivalent to using the {{code|Nullable<T>}} [[Generic programming|generic]] type, where {{mono|T}} is the type to be lifted. Conversions are implicitly defined to convert between values of the base and the lifted type. The lifted type can be compared against {{mono|null}} or it can be tested for {{mono|HasValue}}. Also, lifted operators are implicitly and automatically defined based on their non-lifted base, where – with the exception of some Boolean operators – a null argument will propagate to the result. Java does not support type lifting as a concept, but all of the built-in primitive types have corresponding wrapper types, which do support the {{mono|null}} value by virtue of being reference types (classes). According to the Java spec, any attempt to dereference the {{mono|null}} reference must result in an exception being thrown at run-time, specifically a {{mono|NullPointerException}}. (It would not make sense to dereference it otherwise, because, by definition, it points to no object in memory.) This also applies when attempting to [[Auto-unboxing|unbox]] a variable of a wrapper type, which evaluates to {{mono|null}}: the program will throw an exception, because there is no object to be unboxed – and thus no boxed value to take part in the subsequent computation. The following example illustrates the different behavior. In C#, the lifted*operator propagates the {{mono|null}} value of the operand; in Java, unboxing the null reference throws an exception. Not all C# lifted operators have been defined to propagate {{mono|null}} unconditionally, if one of the operands is {{mono|null}}. Specifically, the [[Boolean operator (computer programming)|Boolean operator]]s have been lifted to support [[ternary logic]] thus keeping impedance with [[SQL]]. The Java Boolean operators do not support ternary logic, nor is it implemented in the base class library. === Late-bound (dynamic) type === C# features a [[Name binding|late bound]] dynamic type that supports no-reflection dynamic invocation, interoperability with dynamic languages, and ad-hoc binding to (for example) document object models. The {{mono|dynamic}} type resolves member access dynamically at runtime as opposed to statically/virtual at compile time. The member lookup mechanism is extensible with traditional [[Reflective programming|reflection]] as a fall-back mechanism. There are several use cases for the {{mono|dynamic}} type in C#: * Less verbose use of reflection: By casting an instance to the {{mono|dynamic}} type, members such as properties, methods, events etc. can be directly invoked on the instance without using the reflection API directly. * Interoperability with dynamic languages: The dynamic type comes with a [[hub-and-spoke]] support for implementing dynamically typed objects and common runtime infrastructure for efficient member lookup. * Creating dynamic abstractions on the fly: For instance, a dynamic object could provide simpler access to document object models such as [[XML]] or [[XHTML]] documents. Java does not support a late-bound type. The use cases for C# dynamic type have different corresponding constructs in Java: * For dynamic late-bound ''by-name'' invocation of preexisting types, reflection should be used. * For interoperability with dynamic languages, some form of interoperability API specific to that language must be used. The [[Java virtual machine]] platform does have multiple dynamic languages implemented on it, but there is no common standard for how to pass objects between languages. Usually this involves some form of reflection or reflection-like API. As an example of how to use JavaFX objects from Java.<ref>[http://blogs.sun.com/javafx/entry/how_to_use_javafx_in How to Use JavaFX in Your Swing Application] {{webarchive|url=https://web.archive.org/web/20090304204652/http://blogs.sun.com/javafx/entry/how_to_use_javafx_in|date=4 March 2009}}</ref> * For creating and interacting with objects entirely at runtime, e.g., interaction with a document object model abstraction, a specific abstraction API must be used. See also example [[#Interoperability with dynamic languages]]. === Pointers === Java precludes pointers and pointer-arithmetic within the Java runtime environment. The Java language designers reasoned that pointers are one of the main features that enable programmers to put bugs in their code and chose not to support them.<ref name="oracle.com"/> Java does not allow for directly passing and receiving objects/structures to/from the underlying operating system and thus does not need to model objects/structures to such a specific memory layout, layouts that frequently would involve pointers. Java's communication with the underlying operating system is instead based upon [[Java Native Interface]] (JNI) where communication with/adaptation to an underlying operating system is handled through an external ''glue'' layer. While C# does allow use of [[Pointer (computer programming)|pointers]] and corresponding pointer arithmetic, the C# language designers had the same concerns that pointers could potentially be used to bypass the strict rules for object access. Thus, C# by default also precludes pointers.<ref>{{cite web |title=Unsafe Code and Pointers (C# Programming Guide) |url=http://msdn.microsoft.com/en-us/library/t2yzs44b(v=vs.80).aspx |publisher=Microsoft |access-date=11 March 2013}}</ref> However, because pointers are needed when calling many native functions, pointers are allowed in an explicit ''unsafe'' mode. Code blocks or methods that use the pointers must be marked with the {{mono|unsafe}} keyword to be able to use pointers, and the compiler requires the {{code|/unsafe}} switch to allow compiling such code. Assemblies that are compiled using the {{code|/unsafe}} switch are marked as such and may only execute if explicitly trusted. This allows using pointers and pointer arithmetic to directly pass and receive objects to/from the operating system or other native APIs using the native memory layout for those objects while also isolating such potentially unsafe code in specifically trusted assemblies. === Reference types === In both languages [[Reference (computer science)|references]] are a central concept. All instances of classes are ''by reference''. While not directly evident in the language [[Syntax (programming languages)|syntax]] ''per se'', both languages support the concept of [[weak reference|''weak'' references]]. An instance that is only referenced by weak references is eligible for garbage collection just as if there were no references at all. In both languages this feature is exposed through the associated libraries, even though it is really a core runtime feature. Along with weak references, Java has ''[[soft reference]]s''. They are much like weak references, but the [[Java virtual machine]] (JVM) will not deallocate softly-referenced objects until the memory is needed. {| class="wikitable" style="width:80%;" |- ! style="width:40%;"| Reference types !! style="width:30%;"|Java !! style="width:30%;"|C# |- | [[Garbage collection (computer science)|Garbage collection]] || {{yes}} || {{yes}} |- | [[Weak reference]]s || {{yes}} || {{yes}} |- | Reference queue (interaction with garbage collection) || {{yes}} || {{yes}} |- | [[Soft reference]]s || {{yes}} || {{no}} |- | [[Phantom reference]]s || {{yes}} || {{no}} |- | [[Proxy pattern|Proxy support]] || {{yes}}; proxy generation || {{yes}}; object contexts |} === Arrays and collections === [[Array data structure|Arrays]] and [[Collection (abstract data type)|collections]] are concepts featured by both languages. {| class="wikitable" style="width:80%;" |- ! style="width:40%;"| [[Array data type|Arrays]] and [[Collection (abstract data type)|Collections]] !! style="width:30%;"|Java !! style="width:30%;"|C# |- | [[Abstract data type]]s || {{yes}} || {{yes}} |- | One-dimensional, zero-based index arrays || {{yes}} || {{yes}} |- | Multidimensional arrays, rectangular (single array)|| {{no}} || {{yes}} |- | Multidimensional arrays, jagged (arrays of arrays)|| {{yes}} || {{yes}} |- | Non-zero based arrays || {{no}} || {{some}} |- | Unified arrays and collections || {{no}} || {{yes}} |- | [[Associative array|Maps/dictionaries]] || {{yes}} || {{yes}} |- |Sorted dictionaries || {{yes}} || {{yes}}<ref>{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2 |title=SortedDictionary<TKey,TValue> Class (System.Collections.Generic) |publisher=learn.microsoft.com |access-date=20 April 2023}}</ref> |- |Sets || {{yes}} || {{yes}} |- |Sorted sets || {{yes}} || {{yes}}<ref>{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1 |title=SortedSet<T> Class (System.Collections.Generic) |publisher=learn.microsoft.com |access-date=20 April 2023}}</ref> |- |Lists/vectors || {{yes}} || {{yes}} |- | [[Queue (data structure)|Queues/stacks]] || {{yes}} || {{yes}} |- | [[Priority queue]] || {{yes}} || {{yes}}<ref>{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.priorityqueue-2?view=net-8.0 |title=PriorityQueue<TElement,TPriority> Class (System.Collections.Generic) |publisher= learn.microsoft.com |access-date=20 April 2023}}</ref> |- |Bags/multisets || {{no|Third-party library|style=background: #8CF;}} || {{yes}} |- |Concurrency optimized collections || {{yes}} || {{yes}}<ref>{{cite web |title=System.Collections.Concurrent Namespace |url=https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent |publisher=learn.microsoft.com |access-date=20 April 2023}}</ref> |} The syntax used to declare and access arrays is identical, except that C# has added syntax for declaring and manipulating multidimensional arrays. {| class="wikitable" style="width:90%;" |- ! style="width:50%;"| Java !! style="width:50%;"| C# |- | Arrays are implicitly direct specializations of {{mono|Object}}. They are not unified with collection types. | Arrays in C# are implicit specializations of the {{code|System.Array}} class that implements several collection [[Interface (object-oriented programming)|interfaces]]. |- | Arrays and collections are completely separate with no unification. Arrays cannot be passed where sequences or collections are expected (though they can be wrapped using {{code|Arrays.asList}}). | Arrays can be passed where sequences ({{mono|IEnumerable}}s) or collections/list [[Interface (object-oriented programming)|interfaces]] are expected. However, the collection operations that alter the number of elements (insert/add/remove) will throw exceptions as these operations are unsupported by arrays. |- | The {{mono|for}} statement accepts either arrays or {{mono|Iterable}}s. All collections implement {{mono|Iterable}}. This means that the same short syntax can be used in for-loops. | The {{mono|foreach}} statement iterates through a sequence using a specific implementation of the {{mono|GetEnumerator}} method, usually implemented through the {{mono|IEnumerable}} or {{code|IEnumerable<T>}} [[Interface (object-oriented programming)|interface]].<ref>{{cite web |url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in |title=foreach, in (C# reference) |year=2018 |publisher=Microsoft |archive-url=https://web.archive.org/web/20190112220056/https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in |archive-date=12 January 2019 |quote=The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the {{mono|System.Collections.IEnumerable}} or {{mono|System.Collections.Generic.IEnumerable<T>}} interface. |access-date=26 January 2019 |url-status=live}}</ref> Because arrays always implicitly implement these [[Interface (object-oriented programming)|interfaces]], the loop will iterate through arrays also. |- |colspan=2|In both languages arrays of reference types are covariant. This means that a {{code|String[]}} array is assignable to variables of {{code|Object[]}}, as {{mono|String}} is a specialization of (assignable to) {{mono|Object}}. In both languages, the arrays will perform a type check when inserting new values, because type safety would otherwise be compromised. This is in contrast to how generic collections have been implemented in both languages. |- | No [[Two-dimensional array|multidimensional arrays]] (rectangular arrays), but arrays of references to arrays ([[jagged array]]s). | [[Two-dimensional array|Multidimensional arrays]] (rectangular arrays), and arrays of references to arrays ([[jagged array]]s). |- | Arrays cannot be resized (though use of the {{code|System.arraycopy()}} method can allow for multi-step array resizing) | Arrays can be resized while preserving existing values using the {{code|Array.Resize()}} static array method (but this may return a new array). |- | Implemented as a [[retrofit]] for the {{code|java.util}} library having extra features, like data structures like sets and linked sets, and has several algorithms to manipulate elements of a collection, like finding the largest element based on some {{code|Comparator<T>}} object, finding the smallest element, finding sublists within a list, reverse the contents of a list, shuffle the contents of a list, create immutable versions of a collection, performs sorts, and make binary searches.<ref>{{cite web |url=http://www.25hoursaday.com/ |title=A Comparison of Microsoft's C# Programming Language to Sun Microsystems' Java Programming Language: C. An Ever So Slight Feeling of Dèjà Vu: 6. Collections |author=Dare Obasanjo |year=2007 |publisher=Dare Obasanjo |archive-url=https://web.archive.org/web/20120919093308/http://25hoursaday.com/ |archive-date=19 September 2012 |quote=The Java collections framework not only has methods that enable one to access unsafe collections in a thread safe manner, but contains thread-safe versions of most of the data structures as well. The Java collections framework has a number of algorithms for manipulating the elements within the data structures including algorithms that can do the following; find the largest element based on some Comparator, find the smallest element, find sublists within a list, reverse the contents of a list, shuffle the contents of a list, creates immutable versions of a collection, performs sorts, and binary searches. |access-date=10 September 2012 |url-status=dead |df=dmy-all}}</ref> | The C# collections framework consists of classes from the {{code|System.Collections}} and the {{code|System.Collections.Generic}} namespaces with several useful [[Interface (object-oriented programming)|interfaces]], abstract classes, and data structures.<ref>{{cite web |url=http://www.25hoursaday.com/CsharpVsJava.html |title=A Comparison of Microsoft's C# Programming Language to Sun Microsystems' Java Programming Language: C. An Ever So Slight Feeling of Dèjà Vu: 6. Collections |author=Dare Obasanjo |publisher=Dare Obasanjo |archive-url=https://archive.today/20130102015335/http://www.25hoursaday.com/CsharpVsJava.html |archive-date=2 January 2013 |date=March 2007 |quote=The C# collections framework consists of the classes in the System. Collections and the System.Collections.Generic namespaces. The {{mono|Systems.Collections}} namespace contains [[Interface (object-oriented programming)|interfaces]] and abstract classes that represent abstract data types such as {{mono|IList, IEnumerable, IDictionary, ICollection}}, and {{mono|CollectionBase}} that enable developers to manipulate data structures independently of how they are actually implemented as long as the data structures inherit from the abstract data types. The System.Collections namespace also contains some concrete implementations of data structures such as {{mono|ArrayList, Stack, Queue, HashTable}} and {{mono|SortedList}}. All four of the concrete data structure implementations enable one to obtain synchronized wrappers to the collection that allows for access in a thread-safe manner. The {{mono|System.Collections.Generic}} namespace has generic implementations of the key data structures in the System.Collections namespace including generic {{mono|List<T>}}, {{mono|Stack<T>}}, {{mono|Queue<T>}}, {{mono|Dictionary<K,T>}} and {{mono|SortedDictionary<K,T>}} classes. |access-date=10 September 2012 |url-status=dead }}</ref> NET 3.5 added {{code|System.Linq}} namespace that contains various extension methods for querying collections, such as {{mono|Aggregate}}, {{mono|All}}, {{mono|Average}}, {{mono|Distinct}}, {{mono|Join}}, {{mono|Union}} and many others. Queries using these methods are called [[Language Integrated Query]] (LINQ). |} Multidimensional arrays can in some cases increase performance because of increased [[Memory locality|locality]] (as there is one pointer dereference instead of one for every dimension of the array, as it is the case for jagged arrays). However, since all array element access in a multidimensional array requires multiplication/shift between the two or more dimensions, this is an advantage only in very random access scenarios. Another difference is that the entire multidimensional array can be allocated with a single application of operator {{mono|new}}, while jagged arrays require loops and allocations for every dimension. However, Java provides a syntactic construct for allocating a jagged array with regular lengths; the loops and multiple allocations are then performed by the virtual machine and need not be explicit at the source level. Both languages feature an extensive set of collection types that includes various ordered and unordered types of lists, maps/dictionaries, sets, etc. === Tuples === C# provides two different methods for creating [[tuple]] types (also known as [[product type]]s). The first is via the {{code|System.Tuple}} classes, which are immutable reference types provided by the framework API (starting with .NET Framework 4.0) for creating generic tuple types.<ref name="C# Tuple class"/> This first method has since been effectively superseded by the second, the {{code|System.ValueTuple}} structs, which are mutable value types provided by the framework API (starting with .NET Framework 4.7).<ref name="C# value tuples"/> While the two methods seem superficially similar, they have multiple notable differences. The {{mono|ValueTuple}} types are value types, so they have a more compact memory footprint; also, the {{mono|ValueTuple}} types expose their contents as mutable fields, compared to the immutable properties of the {{mono|Tuple}} classes. Finally, since C# version 7.0, the language has native syntactical support for the construction, deconstruction, and manipulation of tuples as {{mono|ValueTuple}} instances; this also provides for the arbitrary renaming of the tuples' constituent fields (as opposed to {{mono|Tuple}}, where the fields are always named {{mono|Item1}}, {{mono|Item2}}, etc.). Java does not provide tuple types as part of its language or standard API; numerous third-party libraries exist which can provide tuple types,<ref>{{Cite web |url=https://www.javatuples.org/ |title=javatuples |access-date=20 April 2023}}</ref> but they all are necessarily similar to the C# {{code|System.Tuple}} classes. In comparison to C# {{mono|ValueTuple}} types and their associated syntax, they are more unwieldy to use (requiring the explicit use of constructors or static factory methods for creating them, requiring individual member access to deconstruct them, and having fixed names for their elements).
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)