.NET

15 mar, 2017

.NET – Comparação dos principais recursos entre C# e Java

Publicidade

Neste artigo, vou apresentar uma comparação dos principais recursos das linguagens C# e Java.

A comparação refere-se aos principais recursos, sem levar em conta os novos recursos da linguagem C# (versões C# 6.0 e C# 7.0), que simplificaram a sintaxe em muitos casos.

Estrutura do programa

C#
using System;
namespace Ola {
   public class OlaMundo {
      public static void Main(string[] args) {
         string nome = "C#";
         // ve se um argumento foi passado da linha de comando
         if (args.Length == 1)
            name = args[0];
         Console.WriteLine("olá, " + nome + "!");
      }
   }
}
Java
package Ola;
public class OlaMundo {
   public static void main(String[] args) {
      String nome = "Java";
      // ve se um argumento foi passado da linha de comando
      if (args.length == 1)
         name = args[0];
      System.out.println("Ola, " + nome + "!");
    }
}

Comentários

C#
// Linha simples
/* Multiplas
    linhas  */
/// XML comentários em uma linha simples
/** XML comentário em múltiplas linhas */
Java
// Linha Simples

/* Multiplas
    linhas  */
/** comentário de documentação Javadoc */

Tipos de dados

C#
Tipos por valor
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double, decimal
structures, enumerations
Tipos por referência
object    (superclasse todas as outras classes)
string
arrays, classes, interfaces, delegates

Conversões

// int para string 
int x = 123; 
String y = x.ToString();  // y é "123"

// string para int
y = "456"; 
x = int.Parse(y);   ou  x = Convert.ToInt32(y);

// double para int
double z = 3.5; 
x = (int) z;   // x é 3  (trunca os decimais)
Java
Tipos primitivos
boolean
byte
char
short, int, long
float, double

Tipos por referência
Object   (superclasse todas as outras classes)
String
arrays, classes, interfaces

Conversões

// int para String 
int x = 123; 
String y = Integer.toString(x);    // y é "123"

// String para int
y = "456"; 
x = Integer.parseInt(y);   // x é 456

// double para int
double z = 3.5; 
x = (int) z;      // x é 3  (trunca os decimais)

Constantes

C#
const double PI = 3.14;
// Pode ser definido para uma constante ou variável. 
// Pode ser inicializada em um construtor
readonly int PESO_MAXIMO = 9;
Java
// Pode ser inicializada em um construtor 
final double PI = 3.14;

Enumerações

C#
enum Action  { Start, Stop, Rewind, Forward };
enum Status { Flunk = 50, Pass = 70, Excel = 90 };

 


Sem Equivalente



 



Action a = Action.Stop;
if (a != Action.Start)
      Console.WriteLine(a);           // Imprime "Stop"

Status s = Status.Pass;
Console.WriteLine((int) s);         // Imprime "70"
Java
enum Action {Start, Stop, Rewind, Forward};
// Tipo especial de classe 
enum Status 
{
   Flunk(50), Pass(70), Excel(90);
   private final int value;
    Status(int value) 
    { 
        this.value = value; 
     }
     public int value() 
     {   
        return value; 
     } 
};

Action a = Action.Stop;
if (a != Action.Start)
     System.out.println(a);               // Imprime "Stop"

Status s = Status.Pass;
System.out.println(s.value());      // Imprime "70"

Operadores

C#
Comparação
==  <  >  <=  >=  !=
Aritméticos
+  -  *  /  %  (mod) 
/  (divisão inteira se ambos os operandos são inteiros)  Math.Pow(x, y)

Atribuição
=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --

Bitwise
&  |  ^   ~  <<  >>

Logicos
&&  ||  &  |   ^   !

Nota: && e ||  realização avaliação lógica de curto-circuito

Concatenação de strings
+
Java
Comparação
==  <  >  <=  >=  !=
Aritméticos
+  -  *  /  %  (mod) 
/  (divisão inteira se ambos os operandos são inteiros) Math.Pow(x, y)

Atribuição
=  +=  -=  *=  /=   %=   &=  |=  ^=  <<=  >>=  >>>=  ++  --

Bitwise
&  |  ^   ~  <<  >>  >>>

Logicos
&&  ||  &  |   ^   !

Nota: && e || realizam avaliações lógica de curto-circuito

Concatenação de strings
+

Estrutura de decisão

C#
saudacao = idade < 20 ? "O que há de novo ?" : "Ola";
if (x < y)  
  Console.WriteLine("maior");

if (x != 100) {    
  x *= 5; 
  y *= 2; 
} 
else 
  z *= 6;

string color = "azul";
switch (color) {                        // Pode ser qualquer tipo predefinido
  case "azul":    r++;    break;        // break é obrigatório;  não sai
  case "preta":   b++;   break; 
  case "verda": g++;   break; 
  default: other++;     break;       // break deve ser usado
Java
saudacao = idade < 20 ? "O que há de novo ?" : "Ola";
if (x < y) 
  System.out.println("maior");

if (x != 100) {    
  x *= 5; 
  y *= 2; 
} 
else 
  z *= 6;

int selecao = 2;
switch (selecao) {         // Deve ser byte, short, int, char, ou enum
  case 1: x++;            //  Sai para o próximo next , se não houver um break
  case 2: y++;   break; 
  case 3: z++;   break; 
  default: other++;
}

Laços (Loop)

C#
while (i < 10) 
  i++;

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

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

// foreach pode ser usado para iterar sobre qualquer coleção 
using System.Collections;
ArrayList list = new ArrayList();
list.Add(10);
list.Add("Cavalo");
list.Add(2.3);

foreach (Object o in list)
  Console.WriteLine(o);
Java
while (i < 10) 
  i++;

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

for (int i : numArray)  // foreach   
  soma += i;

// for - pode ser usado para iterar sobre qualquer coleção
import java.util.ArrayList;
ArrayList<Object> list = new ArrayList<Object>();
list.add(10);           // boxing converte para uma instância de Integer
list.add("Cavalo");
list.add(2.3);           // boxing converte para uma instancia de Double

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

Arrays

C#
int[] numeros = {1, 2, 3};

for (int i = 0; i < numeros.Length; i++)
  Console.WriteLine(numeros[i]);

string[] nomes = new string[5];
names[0] = "Macoratti";

float[,] DuasDimensoes= new float[rows, cols];
DuasDimensoes[2,0] = 4.5f;
int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] }; 
jagged[0][4] = 5;
Java
int numeros[] = {1, 2, 3};   ou   int[] numeros = {1, 2, 3};

for (int i = 0; i < numeros.length; i++)
           System.out.println(numeros[i]);

String nomes[] = new String[5];
nomes[0] = "Macoratti";

float DuasDimensoes[][] = new float[rows][cols];
DuasDimensoes[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;

Funções

C#
// Retorna um único valor
int Adiciona(int x, int y) { 
   return x + y; 
}
int soma = Adiciona(2, 3);
//  não retorna valor
void ImprimeSoma(int x, int y) { 
   Console.WriteLine(x + y); 
}
ImprimeSoma(2, 3);
// Passado por valor (default), in/out-reference (ref), and out-reference (out) 
void TesteFunc(int x, ref int y, out int z, Point p1, ref Point p2) { 
   x++;  y++;  z = 5; 
   p1.x++;       // Modifica a propriedade do objeto      
   p1 = null;    // Remove a referencia local do  objeto
   p2 = null;   // Libera o objeto 
}

class Point { 
   public int x, y; 
}

Point p1 = new Point(); 
Point p2 = new Point(); 
p1.x = 2; 
int a = 1, b = 1, c;   // parâmetro de saida não precisa de inicilização 
TesteFunc(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

// Aceita um número variável de argumentos
int Soma(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;
}

int total = Soma(4, 3, 2, 1);   // retorna 10
Java
// Retorna um único valor
int Adiciona(int x, int y) { 
   return x + y; 
}
int soma = Adiciona(2, 3);
// não retorna valor
void ImprimeSoma(int x, int y) { 
   System.out.println(x + y); 
}
ImprimeSoma(2, 3);
// Tipos Primitivos e por referência são sempre passados por valor
void TesteFunc(int x, Point p) {
   x++; 
   p.x++;         // Modifica a propriedade do objeto 
   p = null;     // Remove a referencia local do  objeto
}

class Point { 
   public int x, y; 
}

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


// Aceita um número variável de argumentos
int Soma(int ... nums) {
  int sum = 0;
  for (int i : nums)
    sum += i;
  return sum;
}

int total = Soma(4, 3, 2, 1);   // retorna 10

Strings

C#
// Concatenação de String
string escola = "de Campinas "; 
escola = escola + "Universidade";   // escola => "Universidade de Campinas"
// Comparação de Strings
string mascote = "Cavalo"; 
if (mascote == "Cavalo")                                  // true
if (mascote.Equals("Cavalo"))                          // true
if (mascote.ToUpper().Equals("CAVALO"))      // true
if (mascote.CompareTo("Cavalo") == 0)        // true

Console.WriteLine(mascote.Substring(2, 3));    // Imprime "val"

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

// string mutável 
System.Text.StringBuilder buffer = new System.Text.StringBuilder("dois "); 
buffer.Append("tres "); 
buffer.Insert(0, "um "); 
buffer.Replace("dois", "DOIS"); 
Console.WriteLine(buffer);      // Imprime  "um DOIS tres"
Java
// Concatenação de String
String escola = "de Campinas "; 
escola = escola + "Universidade";   // escola => "Universidade de Campinas"
// Comparação de Strings
String mascote = "Cavalo"; 
if (mascote == "Cavalo")                                 // Não é a forma correta de comparar strings
if (mascote.equals("Cavalo"))                               // true
if (mascote.equalsIgnoreCase("CAVALO"))    // true
if (mascote.compareTo("Cavalo") == 0)         // true

System.out.println(mascote.substring(2,3));   // Imprime "val"

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

// string mutável 
StringBuffer buffer = new StringBuffer("dois "); 
buffer.append("tres "); 
buffer.insert(0, "um "); 
buffer.replace(4, 7, "DOIS); 
System.out.println(buffer);     // Imprime  "um DOIS tres"

Tratamento de exceção

C#
Exception up = new Exception("Alguma coisa esta errada."); 
throw up; 

try {
  y = 0; 
  x = 10 / y;
} catch (Exception ex) {        // A variável 'ex' é optional
   Console.WriteLine(ex.Message); 
} finally {
    // Codigo que sempre será executado
}
Java
//  Precisa estar no método que é declarada para lançar esta exceção
Exception ex = new Exception("Alguma coisa esta errada."); 
throw ex;  
try {
  y = 0; 
  x = 10 / y;
} catch (Exception ex) {
  System.out.println(ex.getMessage()); 
} finally {
    // Codigo sempre será executado
}

Namespaces

C#
namespace Macoratti.Sistema.Artigos {
  ...
}
ou

namespace Macoratti {
  namespace Sistema {
    namespace Artigos {
      ...
    }
  }
}

// Importa uma única classe
using Retangulo = Macoratti.Sistema.Artigos.Retangulo;

// Importa todas as classes
using Macoratti.Sistema.Artigos
Java
package Macoratti.Sistema.Artigos;

Classes e interface

C#
palavras chaves para acessabilidade e escopo
public
private
internal
protected
protected internal
static
// herança
class JogoFutebol : Competicao {
  ...
}

// Definição de Interface
interface IAlarme {
  ...
}

// Estendendo uma interface 
interface IAlarme : IRelogio {
  ...
}

// Implementação de Interface
class AssisteJogo : IAlarme, ITimer {
   ...
}
Java
palavras chaves para acessabilidade e escopo
public
private
protected
static

 
// herança
class JogoFutebol extends Competicao {
  ...
}

// Definição de Interface
interface IAlarme {
  ...
}

// Estendendo uma interface 
interface IAlarme extends IRelogio {
  ...
}

// Implementação de Interface
class AssisteJogo implements IAlarme, ITimer {
   ...
}

Objetos

C#
SuperHero heroi = new SuperHeroi(); 

heroi.Name = "HomeMosca"; 
heroi.PowerLevel = 3;
heroi.Defend("Laura Jones");
SuperHeroi.Rest();                              // Chamando método estático

SuperHeroi heroi2 = heroi;                  // Ambos referem-se ao mesmo objeto
heroi2.Name = "MulherMaravilha"; 
Console.WriteLine(heroi.Name);          // Imprime MulherMaravilha

heroi = null ;                                                // Libera o objeto

if (heroi == null)
  heroi = new SuperHeroi();

Object obj = new SuperHeroi(); 
Console.WriteLine("tipo do objeto: " + obj.GetType().ToString()); 
if (obj is SuperHeroi) 
  Console.WriteLine("É um objeto SuperHeroi.");
Java
SuperHeroi heroi = new SuperHeroi();
heroi.setName("HomeMosca"); 
heroi.setPowerLevel(3); 

heroi.Defend("Laura Jones");
SuperHeroi.Rest();                                      // Chamando método estático

SuperHeroi heroi2 = hero;                        // Ambos referem-se ao mesmo objeto 
heroi2.setName("MulherMaravilha"); 
System.out.println(heroi.getName());      // Imprime MulherMaravilha

heroi = null;                                                       // Libera o objeto

if (heroi == null)
  heroi = new SuperHeroi();

Object obj = new SuperHeroi(); 
System.out.println("Tipo do objeto: " + obj.getClass().toString()); 
if (obj instanceof SuperHeroi) 
  System.out.println("É um objeto SuperHeroi.");

Propriedades

C#
private int mTamanho;
public int Tamanho{ 
  get { return mTamanho; } 
  set { 
    if (value < 0) 
      mTamanho= 0; 
    else 
      mTamanho= value; 
  } 
}

sapato.Tamanho++;      //incrementa valor da propriedade
Java
private int mTamanho;
public int getTamanho() { return mTamanho; } 
public void setTamanho(int value) {
  if (value < 0) 
       mTamanho= 0; 
  else 
      mTamanho= value; 
}


int s = sapato.getTamanho();    //obtem um valor da propriedade
sapato.setTamanho(s+1);          //atribui valor à propriedade

Structs

C#
struct AlunoRegistro {
  public string nome;
  public float gpa;

  public AlunoRegistro(string nome, float gpa) {
    this.nome = nome;
    this.gpa = gpa;
  }
}

AlunoRegistro stu = new AlunoRegistro("Macoratti", 3.5f);
AlunoRegistro stu2 = stu;  

stu2.name = "Miriam";
Console.WriteLine(stu.nome);    // Imprime "Macoratti"
Console.WriteLine(stu2.nome);   // Imprime "Miriam"
Java
Sem suporte a Structs

Console I/O

C#
Console.Write("Qual o seu nome? ");
string nome = Console.ReadLine();
Console.Write("Qual a sua idade? ");
int idade = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} tem {1} anos de idade.", nome, idade);
// ou
Console.WriteLine(nome + " tem " + idade + " anos de idade.");
int c = Console.Read();  // Lé um único char
Console.WriteLine(c);    // Imprime 65 se o usuário informar "A"

// O estúdio custa  R$499.00 por 3 meses
Console.WriteLine("O {0} custa {1:C} por {2} meses.\n", "studio", 499.0, 3);

// Hoje é  06/02/2017
Console.WriteLine("Hoje é  " + DateTime.Now.ToShortDateString());
C#
java.io.DataInput in = new java.io.DataInputStream(System.in);
System.out.print("Qual o seu nome? ");
String nome = in.readLine();
System.out.print("Qual a sua idade? ");
int idade = Integer.parseInt(in.readLine());
System.out.println(nome + " tem " + idade + " anos de idade.");

int c = System.in.read();    // Lé um único char
System.out.println(c);       // Imprime 65 se o usuário informar "A"

// O studio custa $499.00 por 3 meses
System.out.printf("O %s custa $%.2f por %d meses.%n", "estudio", 499.0, 3);

// Hoje é 06/25/04
System.out.printf("Hoje é %tD\n", new java.util.Date());

File I/O

C#
using System.IO;
// Escrita de Caractere Stream
StreamWriter writer = File.CreateText("c:\\meuArquivo.txt"); 
writer.WriteLine("Para arquivo"); 
writer.Close();

//Leitura de Caractere Stream
StreamReader reader = File.OpenText("c:\\meuArquivo.txt"); 
string linha = reader.ReadLine(); 
while (linha != null) {
    Console.WriteLine(linha); 
     line = reader.ReadLine(); 
} 
reader.Close();


// Escrita Binaria Stream
BinaryWriter out = new BinaryWriter(File.OpenWrite("c:\\meuArquivo.dat")); 
out.Write("dados texto"); 
out.Write(123); 
out.Close();

// Leitura Binaria Stream
BinaryReader in = new BinaryReader(File.OpenRead("c:\\meuArquivo.dat")); 
string s = in.ReadString(); 
int num = in.ReadInt32(); 
in.Close();
Java
import java.io.*;
// Escrita de Caractere Stream
FileWriter writer = new FileWriter("c:\\meuArquivo.txt");
writer.write("Para arquivo\n");
writer.close();

// Leitura de Caractere Stream
FileReader reader = new FileReader("c:\\meuArquivo.txt");
BufferedReader br = new BufferedReader(reader);
String linha = br.readLine(); 
while (linha != null) {
    System.out.println(linha); 
    linha = br.readLine(); 
} 
reader.close();

// Escrita Binaria Stream
FileOutputStream out = new FileOutputStream("c:\\meuArquivo.dat");
out.write("dados texto".getBytes());
out.write(123);
out.close();

// Leitura Binaria Stream
FileInputStream in = new FileInputStream("c:\\meuArquivo.dat");
byte buff[] = new byte[9];
in.read(buff, 0, 9);                              // Le os primeiros 9 byte em buff
String s = new String(buff);
int num = in.read();                           // O próximo é 123
in.close();