Comparação Java (J2SE 5.0) e C# parte 2

Informática

28/10/2008

Java Loops C#

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2) 
  System.out.println(i);

do
  i++;
while (i < 10);

for (int i : numArray) 
  sum += i;

// for loop can be used to iterate through
// any Collection
import java.util.ArrayList;
ArrayList<Object> list = new ArrayList<Object>();
list.add(10);    // boxing converts to instance of Integer
list.add("Bisons");
list.add(2.3);    // boxing converts to instance of Double

for (Object o : list)
  System.out.println(o);

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2)
  Console.WriteLine(i);

do
  i++;
while (i < 10);

foreach (int i in numArray) 
  sum += i;

// foreach can be used to iterate through
// any collection
 
using System.Collections;
ArrayList list = new ArrayList();
list.Add(10);
list.Add("Bisons");
list.Add(2.3);

foreach (Object o in list)
  Console.WriteLine(o);

Java Arrays C#
int nums[] = {1, 2, 3};   or   int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
  System.out.println(nums[i]);

String names[] = new String[5];
names[0] = "David";

float twoD[][] = new float[rows][cols];
twoD[2][0] = 4.5;

int[][] jagged = new int[5][];
jagged[0] = new int[5];
jagged[1] = new int[2];
jagged[2] = new int[3];
jagged[0][4] = 5;

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
  Console.WriteLine(nums[i]);

string[] names = new string[5];
names[0] = "David";

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
    new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

Java Functions C#
// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   System.out.println(x + y);
}

PrintSum(2, 3);

// Primitive types and references are always passed by value
void TestFunc(int x, Point p) {
   x++;
   p.x++;       // Modifying property of the object
   p = null;    // Remove local reference to object
}

class Point {
   public int x, y;
}

Point p = new Point();
p.x = 2;
int a = 1;
TestFunc(a, p);
System.out.println(a + " " + p.x + " " + (p == null) );  // 1 3 false




// Accept variable number of arguments
int Sum(int ... nums) {
  int sum = 0;
  for (int i : nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10

// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   Console.WriteLine(x + y);
}

PrintSum(2, 3);

// Pass by value (default), in/out-reference (ref), and out-reference (out)
void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2) {
   x++;  y++;  z = 5;
   p1.x++;       // Modifying property of the object     
   p1 = null;    // Remove local reference to object
   p2 = null;   // Free the object
}

class Point {
   public int x, y;
}

Point p1 = new Point();
Point p2 = new Point();
p1.x = 2;
int a = 1, b = 1, c;   // Output param doesn't need initializing
TestFunc(a, ref b, out c, p1, ref p2);
Console.WriteLine("{0} {1} {2} {3} {4}",
   a, b, c, p1.x, p2 == null);   // 1 2 5 3 True

// Accept variable number of arguments
int Sum(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10

Java Strings C#

// String concatenation
String school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
String mascot = "Bisons";
if (mascot == "Bisons")    // Not the correct way to do string comparisons
if (mascot.equals("Bisons"))   // true
if (mascot.equalsIgnoreCase("BISONS"))   // true
if (mascot.compareTo("Bisons") == 0)   // true

System.out.println(mascot.substring(2, 5));   // Prints "son"

// My birthday: Oct 12, 1973
java.util.Calendar c = new java.util.GregorianCalendar(1973, 10, 12);
String s = String.format("My birthday: %1$tb %1$te, %1$tY", c);

// Mutable string
StringBuffer buffer = new StringBuffer("two ");
buffer.append("three ");
buffer.insert(0, "one ");
buffer.replace(4, 7, "TWO");
System.out.println(buffer);     // Prints "one TWO three"

// String concatenation
string school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons")    // true
if (mascot.Equals("Bisons"))   // true
if (mascot.ToUpper().Equals("BISONS"))   // true
if (mascot.CompareTo("Bisons") == 0)    // true

Console.WriteLine(mascot.Substring(2, 3));    // Prints "son"

// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");

// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer);     // Prints "one TWO three"

Java Exception Handling C#

// Must be in a method that is declared to throw this exception
Exception ex = new Exception("Something is really wrong.");
throw ex;  

try {
  y = 0;
  x = 10 / y;
} catch (Exception ex) {
  System.out.println(ex.getMessage()); 
} finally {
  // Code that always gets executed
}

Exception up = new Exception("Something is really wrong.");
throw up;  // ha ha


try
{
  y = 0;
  x = 10 / y;
} catch (Exception ex) {      // Variable "ex" is optional
  Console.WriteLine(ex.Message);
} finally {
  // Code that always gets executed
}

Java Namespaces C#

package harding.compsci.graphics;












import
harding.compsci.graphics.Rectangle;  // Import single class

import harding.compsci.graphics.*;   // Import all classes

namespace Harding.Compsci.Graphics {
  ...
}

or

namespace Harding {
  namespace Compsci {
    namespace Graphics {
      ...
    }
  }
}

// Import all class. Can't import single class.
using Harding.Compsci.Graphics;


Fonte: http://www.harding.edu/fmccown/java1_5_csharp_comparison.html

Esta apresentação reflete a opinião pessoal do autor sobre o tema, podendo não refletir a posição oficial do Portal Educação.


Colunista Portal - Educação

por Colunista Portal - Educação

O Portal Educação possui uma equipe focada no trabalho de curadoria de conteúdo. Artigos em diversas áreas do conhecimento são produzidos e disponibilizados para profissionais, acadêmicos e interessados em adquirir conhecimento qualificado. O departamento de Conteúdo e Comunicação leva ao leitor informações de alto nível, recebidas e publicadas de colunistas externos e internos.

Portal Educação

UOL CURSOS TECNOLOGIA EDUCACIONAL LTDA, com sede na cidade de São Paulo, SP, na Alameda Barão de Limeira, 425, 7º andar - Santa Cecília CEP 01202-001 CNPJ: 17.543.049/0001-93