COMPARACIÓN DE MICROSOFT'S C# Y JAVA

30 views
Skip to first unread message

juan Carlos

unread,
Mar 1, 2010, 11:21:27 AM3/1/10
to progravan2
3.
De las máquinas virtuales y el lenguaje Runtimes

Just like Java is typically compiled to Java byte code which
then runs in managed execution environment (the Java Virtual Machine
or JVM) so also is C# code compiled to an Intermediate Language (IL)
which then runs in the Common Language Runtime (CLR). Al igual que
Java es normalmente compilado a código de bytes de Java que se ejecuta
en un entorno de ejecución administrado (Java Virtual Machine o JVM),
así también es el código C # compilado a un lenguaje intermedio (IL),
que luego se ejecuta en el Common Language Runtime (CLR). Both
platforms support native compilation via Just In Time compilers .
Ambas plataformas de apoyo compilación nativa a través de Just In Time
compiladores.

NOTE: While the Java platform supports interpretation of byte
code or byte code being JITed then run natively, the .NET platform
only supports native execution of C# code because the IL code is
always natively compiled before running. NOTA: Aunque la plataforma
Java compatible con la interpretación del código byte o código byte
JITed se ejecute de forma nativa, la plataforma. NET sólo admite la
ejecución nativa de código C # ya que el código IL es siempre nativo
compilado antes de correr.
4.
Heap Based Classes and Garbage Collection Clases Heap base y
Recolección de Basura

In Java objects are created on the heap using the new keyword.
Most classes in C# are created on the heap by using the new keyword.
En los objetos de Java se crean en el montón con el palabra clave new
La mayoría de las clases en C # se crean en el heap mediante la
palabra clave new Also just as the JVM manages the destruction of
objects so also does the CLR via a Mark and Compact garbage collection
algorithm También al igual que la JVM gestiona la destrucción de los
objetos así también lo hace el CLR a través de una marca y la recogida
de basura Compact algoritmo

NOTE: C# also supports stack-based classes, called value types,
which are discussed further below. NOTA: C # también admite las clases
basado en la pila, llamados tipos de valor, que se discuten más
adelante.
5.
Arrays Can Be Jagged Las matrices pueden ser Jagged

In languages like C and C++, each subarray of a multidimensional
array must have the same dimensions. En lenguajes como C y C + +, cada
submatriz de una matriz multidimensional debe tener las mismas
dimensiones. In Java and C# arrays do not have to be uniform because
jagged arrays can be created as one-dimensional arrays of arrays. En
Java y C # las matrices no tienen que ser uniformes porque matrices
escalonadas se puede crear como arreglos unidimensionales de las
matrices. In a jagged array the contents of the array are arrays which
may hold instances of a type or references to other arrays. En una
matriz escalonada el contenido de la matriz son arreglos que pueden
tener los casos de un tipo o referencias a otras matrices. For this
reason the rows and columns in a jagged array need not have uniform
length as can be seen from the following code snippet: Por esta razón,
las filas y columnas en una matriz escalonada no necesita tener
longitud uniforme como puede verse en el siguiente fragmento de
código:

int [][]myArray = new int[2][]; myArray[0] = new int[3];
myArray[1] = new int[9];
int [][]myArray = new int[2][]; myArray[0] = new int[3];
myArray[1] = new int[9];

The above code snippet is valid for both C# and Java. El
fragmento de código anterior es válido tanto para C # y Java.

6.
No Global Methods No hay métodos de Global

Just like Java and unlike C++, methods in C# have to be part of
a class either as member or static methods. Al igual que a diferencia
de Java y C + +, los métodos en C # tienen que ser parte de una clase,
ya sea como miembro o métodos estáticos.
7.
Interfaces, Yes. Interfaces, sí. Multiple Inheritance, No
Herencia múltiple, no

C#, like Java, supports the concept of an interface which is
akin to a pure abstract class. C #, como Java, apoya la idea de una
interfaz que se asemeja a una clase abstracta pura. Similarly C# and
Java both allow only single inheritance of classes but multiple
inheritance (or implementation) of interfaces. Del mismo modo C # y
Java tanto sólo permiten herencia simple de clases, pero la herencia
múltiple (o aplicación) de las interfaces.
8.
Strings Are Immutable Las cadenas son inmutables

C# has a System.String class which is analogous to the
java.lang.String class. C # tiene una clase System.String que es
análoga a la clase java.lang.String. Both classes are immutable
meaning that the values of the strings cannot be changed once the
strings have been created. Ambas clases son inmutables sentido de que
los valores de las cadenas no se puede cambiar una vez que las cadenas
se han creado. In both instances methods that appear to modify the
actual content of a string actually create a new string to return,
leaving the original string unchanged. En ambos casos, los métodos que
parecen modificar el contenido real de una cadena de realmente crear
una nueva cadena para regresar, dejando a la cadena original sin
cambios. Thus the following C# and Java code does not modify the
string in either case Así pues, el siguiente código de C # y Java no
modificar la cadena en cualquier caso,

C# Code String csString = "Apple Jack"; csString.ToLower(); /*
Does not modify string, instead returns lower case copy of string */
Java Code String jString = "Grapes"; jString.toLowerCase(); /* Does
not modify string, instead returns lower case copy of string */
C# Code String csString = "Apple Jack"; csString.ToLower(); /*
Does not modify string, instead returns lower case copy of string */
Java Code String jString = "Grapes"; jString.toLowerCase(); /* Does
not modify string, instead returns lower case copy of string */

To create a string-like object that allows modification in C# it
is advisable to use the System.Text.StringBuilder class whereas in
Java one would use the java.lang.StringBuffer class. Para crear una
cadena como objeto que permite la modificación en C # que es
recomendable utilizar el System.Text.StringBuilder clase, mientras que
en Java se podría utilizar la clase java.lang.StringBuffer.

NOTE: In C#, the string class can either be written as string or
String. NOTA: En C #, la clase de cadena puede ser escrito como string
o de cadena.

9.
Unextendable Classes Clases improrrogable

Both Java and C# provide mechanisms to specify that a class
should be the last one in an inheritance hierarchy and cannot be used
as a base class. Java y C # proporcionan mecanismos para especificar
que una clase debe ser el último en una jerarquía de herencia y no
puede ser usado como una clase base. In Java this is done by preceding
the class declaration with the final keyword while in C# this is done
by preceding the class declaration with the sealed keyword. En Java,
esto se hace antes de la declaración de la clase con la palabra clave
final mientras que en C # esto se hace antes de la declaración de la
clase con la palabra clave sealed Below are examples of classes that
cannot be extended in either language A continuación se presentan
ejemplos de las clases que no se puede ampliar en cualquier idioma

C# Code sealed class Student { string fname; string lname; int
uid; void attendClass() {} } Java Code final class Student { String
fname; String lname; int uid; void attendClass() {} }
C# Code sealed class Student { string fname; string lname; int
uid; void attendClass() {} } Java Code final class Student { String
fname; String lname; int uid; void attendClass() {} }

10.
Throwing and Catching Exceptions Lanzar y atrapar excepciones
Exceptions in C# and Java share a lot of similarities.
Excepciones en C # y Java comparten muchas similitudes. Both languages
support the use of the try block for indicating guarded regions, the
catch block for handling thrown exceptions and the finally block for
releasing resources before leaving the method. Ambos idiomas apoyar el
uso del bloque try para indicar las regiones vigilado, el bloque catch
para tratar las excepciones lanzadas y el bloque finally para liberar
recursos antes de abandonar el método. Both languages have an
inheritance hierarchy where all exceptions are derived from a single
Exception class. Exceptions can be caught and rethrown after some
error handling occurs in both languages. Ambos idiomas tienen una
jerarquía de herencia de todas las excepciones que se derivan de una
clase sola excepción. Excepciones pueden ser capturadas y vuelve a
iniciar después de alguna manipulación de error se produce en ambos
idiomas. Finally, both languages provide a mechanism for wrapping
exceptions in one another for cases where a different exception is
rethrown from the one that was caught. Por último, los dos idiomas de
proporcionar un mecanismo para el envasado de las excepciones en el
otro para los casos en que una excepción se vuelve a iniciar
diferentes de la que fue capturado. An example of using the exception
wrapping capability is a three tier application where a SQLException
is thrown during database access but is caught, examined, then an
application specific exception is thrown. Un ejemplo del uso de la
excepción es la capacidad de ajuste de tres aplicaciones de nivel
cuando un SQLException se produce durante el acceso a la base de datos
pero es atrapado, examinó, a continuación, una excepción de aplicación
específica se produce. In this scenario the application specific
exception can be initialized with the original SQLException so
handlers of the application specific exception can access the original
exception thrown if needed. En este escenario de la aplicación de las
excepciones concretas pueden ser iniciadas con la SQLException
original para controladores de la aplicación de las excepciones
concretas pueden acceder a la excepción original lanzado en caso
necesario. Below are two equivalent code samples that show the
similarities between exceptions in both languages. A continuación hay
dos ejemplos de código equivalente que muestran las similitudes entre
las excepciones en ambos idiomas.

NOTE: Although exceptions in both languages support methods for
getting a stack trace, only Java exceptions have methods that allow
one to alter the stack trace. NOTA: Si bien hay excepciones en ambos
idiomas de apoyo métodos para conseguir un seguimiento de la pila,
salvo excepciones de Java tienen métodos que permiten modificar la
traza de la pila.

C# Code using System; using System.IO; class MyException:
Exception{ public MyException(string message): base(message){ } public
MyException(string message, Exception innerException): base(message,
innerException){ } } public class ExceptionTest { static void DoStuff()
{ throw new FileNotFoundException(); } public static void
Main(string[] args){ try{ try{ DoStuff(); return; //won't get to
execute }catch(IOException ioe){ /* parent of FileNotFoundException */
throw new MyException("MyException occured", ioe); /* rethrow new
exception with inner exception specified */ } }
finally{ Console.WriteLine("***Finally block executes even though
MyException not caught***"); } }//Main(string[]) } // ExceptionTest
Java Code class MyException extends Exception{ public
MyException(String message){ super(message); } public
MyException(String message, Exception innerException){ super(message,
innerException); } } public class ExceptionTest { static void doStuff()
{ throw new ArithmeticException(); } public static void main(String[]
args) throws Exception{ try{ try{ doStuff(); return; //won't get to
execute }catch(RuntimeException re){ /* parent of ArithmeticException
*/ throw new MyException("MyException occured", re); /* rethrow new
exception with cause specified */ } }
finally{ System.out.println("***Finally block executes even though
MyException not caught***"); } }//main(string[]) } // ExceptionTest
C# Code using System; using System.IO; class MyException:
Exception{ public MyException(string message): base(message){ } public
MyException(string message, Exception innerException): base(message,
innerException){ } } public class ExceptionTest { static void DoStuff()
{ throw new FileNotFoundException(); } public static void
Main(string[] args){ try{ try{ DoStuff(); return; //won't get to
execute }catch(IOException ioe){ /* parent of FileNotFoundException */
throw new MyException("MyException occured", ioe); /* rethrow new
exception with inner exception specified */ } }
finally{ Console.WriteLine("***Finally block executes even though
MyException not caught***"); } }//Main(string[]) } // ExceptionTest
Java Code class MyException extends Exception{ public
MyException(String message){ super(message); } public
MyException(String message, Exception innerException){ super(message,
innerException); } } public class ExceptionTest { static void doStuff()
{ throw new ArithmeticException(); } public static void main(String[]
args) throws Exception{ try{ try{ doStuff(); return; //won't get to
execute }catch(RuntimeException re){ /* parent of ArithmeticException
*/ throw new MyException("MyException occured", re); /* rethrow new
exception with cause specified */ } }
finally{ System.out.println("***Finally block executes even though
MyException not caught***"); } }//main(string[]) } // ExceptionTest

11.
Member Initialization at Definition and Static Constructors
Miembros de inicialización en la definición de Constructores y Static

Instance and static variables can be initialized at their point
of definition in both C# and Java. Instancia y variables estáticas se
puede inicializar en su punto de definición en C # y Java. If the
member variable is an instance variable, then initialization occurs
just before the constructor is called. Static members are initialized
sometime before the first usage of the member and before the first
creation of an instance of the class. Si la variable de usuario es una
variable de instancia, luego de inicialización se produce justo antes
de que se llama el constructor. Los miembros estáticos se inicializan
en algún momento antes del primer uso del miembro y antes de la
primera creación de una instancia de la clase. It is also possible to
specify a block of code that should run before the class is used
either via creation of an instance variable or invocation of a static
method. También es posible especificar un bloque de código que debe
ejecutar antes de la clase se utiliza ya sea a través de la creación
de una variable de instancia o de la invocación de un método estático.
These code blocks are called are called static constructors in C# and
static initialization blocks in Java. Estos bloques de código se
llaman se llaman constructores estáticos en C # y bloques de
inicialización estática en Java. Static constructors are invoked
before the first invocation of a static method in the class and before
the first time an instance of the class is created. Constructores
estáticos se invocan antes de la primera invocación de un método
estático en la clase y antes de la primera vez que una instancia de la
clase es creado.

C# Code using System; class StaticInitTest{ string instMember =
InitInstance(); string staMember = InitStatic(); StaticInitTest()
{ Console.WriteLine("In instance constructor"); } static
StaticInitTest(){ Console.WriteLine("In static constructor"); } static
String InitInstance(){ Console.WriteLine("Initializing instance
variable"); return "instance"; } static String InitStatic()
{ Console.WriteLine("Initializing static variable"); return
"static"; } static void DoStuff(){ Console.WriteLine("Invoking static
DoStuff() method"); } public static void Main(string[] args)
{ Console.WriteLine("Beginning main()"); StaticInitTest.DoStuff();
StaticInitTest sti = new StaticInitTest();
Console.WriteLine("Completed main()"); } } Java Code class
StaticInitTest{ String instMember = initInstance(); String staMember =
initStatic(); StaticInitTest(){ System.out.println("In instance
constructor"); } static{ System.out.println("In static
constructor"); } static String initInstance()
{ System.out.println("Initializing instance variable"); return
"instance"; } static String initStatic()
{ System.out.println("Initializing static variable"); return
"static"; } static void doStuff(){ System.out.println("Invoking static
DoStuff() method"); } public static void main(String[] args)
{ System.out.println("Beginning main()"); StaticInitTest.doStuff();
StaticInitTest sti = new StaticInitTest();
System.out.println("Completed main()"); } } OUTPUT FROM BOTH EXAMPLES:
In static constructor Beginning main() Invoking static DoStuff()
method Initializing instance variable Initializing static variable In
instance constructor Completed main()
C# Code using System; class StaticInitTest{ string instMember =
InitInstance(); string staMember = InitStatic(); StaticInitTest()
{ Console.WriteLine("In instance constructor"); } static
StaticInitTest(){ Console.WriteLine("In static constructor"); } static
String InitInstance(){ Console.WriteLine("Initializing instance
variable"); return "instance"; } static String InitStatic()
{ Console.WriteLine("Initializing static variable"); return
"static"; } static void DoStuff(){ Console.WriteLine("Invoking static
DoStuff() method"); } public static void Main(string[] args)
{ Console.WriteLine("Beginning main()"); StaticInitTest.DoStuff();
StaticInitTest sti = new StaticInitTest();
Console.WriteLine("Completed main()"); } } Java Code class
StaticInitTest{ String instMember = initInstance(); String staMember =
initStatic(); StaticInitTest(){ System.out.println("In instance
constructor"); } static{ System.out.println("In static
constructor"); } static String initInstance()
{ System.out.println("Initializing instance variable"); return
"instance"; } static String initStatic()
{ System.out.println("Initializing static variable"); return
"static"; } static void doStuff(){ System.out.println("Invoking static
DoStuff() method"); } public static void main(String[] args)
{ System.out.println("Beginning main()"); StaticInitTest.doStuff();
StaticInitTest sti = new StaticInitTest();
System.out.println("Completed main()"); } } OUTPUT FROM BOTH EXAMPLES:
In static constructor Beginning main() Invoking static DoStuff()
method Initializing instance variable Initializing static variable In
instance constructor Completed main()

12.
Boxing Boxeo

In situations where value types need to be treated as objects,
the .NET and Java runtimes automatically converts value types to
objects by wrapping them within a heap-allocated reference type in a
process called boxing . En situaciones en que los tipos de valor deben
ser tratados como objetos,. NET y Java convierte automáticamente los
tiempos de ejecución de los tipos de valor a los objetos
envolviéndolos en un montón asignados tipo de referencia en un proceso
llamado de boxeo. The process of automatically convert an object to
its corresponding value type such as converting an instance of
java.lang.Integer to an int is known as unboxing . El proceso de
convertir automáticamente un objeto a su tipo de valor
correspondiente, tales como la conversión de una instancia de
java.lang.Integer a un int se conoce como unboxing. Below are examples
of various situations where boxing occurs in both runtimes. A
continuación se presentan ejemplos de diferentes situaciones en donde
el boxeo se produce tanto en tiempo de ejecución.

C# Code using System; using System.Collections; //stack
allocated structs also need to be boxed to be treated as objects
struct Point{ //member fields private int x; private int y; public
Point (int x, int y){ this.x = x; this.y = y; } public override string
ToString(){ return String.Format("({0}, {1})", x, y); } }//Point class
Test{ public static void PrintString(object o)
{ Console.WriteLine(o); } public static void Main(string[] args)
{ Point p = new Point(10, 15); ArrayList list = new ArrayList(); int z
= 100; PrintString(p); //p boxed to object when passed to PrintString
PrintString(z); //z boxed to object when passed to PrintString //
integers and float boxed when stored in collection // therefore no
need for Java-like wrapper classes list.Add(1); list.Add(13.12);
list.Add(z); for(int i =0; i < list.Count; i++)
PrintString(list[i]); } } Java Code import java.util.*; class
Test{ public static void PrintString(Object o)
{ System.out.println(o); } public static void PrintInt(int i)
{ System.out.println(i); } public static void main(String[] args)
{ Vector list = new Vector(); int z = 100; Integer x = new
Integer(300); PrintString(z); //z boxed to object when passed to
PrintString PrintInt(x); //x unboxed to int when passed to PrintInt //
integers and float boxed when stored in collection // therefore no
need for Java wrapper classes list.add(1); list.add(13.12);
list.add(z); for(int i =0; i < list.size(); i++)
PrintString(list.elementAt(i)); } }
C# Code using System; using System.Collections; //stack
allocated structs also need to be boxed to be treated as objects
struct Point{ //member fields private int x; private int y; public
Point (int x, int y){ this.x = x; this.y = y; } public override string
ToString(){ return String.Format("({0}, {1})", x, y); } }//Point class
Test{ public static void PrintString(object o)
{ Console.WriteLine(o); } public static void Main(string[] args)
{ Point p = new Point(10, 15); ArrayList list = new ArrayList(); int z
= 100; PrintString(p); //p boxed to object when passed to PrintString
PrintString(z); //z boxed to object when passed to PrintString //
integers and float boxed when stored in collection // therefore no
need for Java-like wrapper classes list.Add(1); list.Add(13.12);
list.Add(z); for(int i =0; i < list.Count; i++)
PrintString(list[i]); } } Java Code import java.util.*; class
Test{ public static void PrintString(Object o)
{ System.out.println(o); } public static void PrintInt(int i)
{ System.out.println(i); } public static void main(String[] args)
{ Vector list = new Vector(); int z = 100; Integer x = new
Integer(300); PrintString(z); //z boxed to object when passed to
PrintString PrintInt(x); //x unboxed to int when passed to PrintInt //
integers and float boxed when stored in collection // therefore no
need for Java wrapper classes list.add(1); list.add(13.12);
list.add(z); for(int i =0; i < list.size(); i++)
PrintString(list.elementAt(i)); } }

The Same But Different

Reply all
Reply to author
Forward
0 new messages