SlideShare a Scribd company logo
.
.

C# / Java Language Comparison
Robert Bachmann

April 4, 2011

1 / 22
Outline

My favorite pitfalls
Common conventions
Type system
Generics
Keywords
Exceptions
Speci c features of Java
Speci c features of C#

2 / 22
My favorite pitfalls

str == "hello"
Checks equality in C#. Checks identity in Java.
Virtual methods
Opt-out in Java (final keyword) vs. opt-in in C# (virtual keyword)
Dates
new GregorianCalendar(2011, 3, 4)1 vs.
new DateTime(2011,4,4)

1

Hint: use YodaTime, Date4J, …
3 / 22
Common conventions

Package names / Namespaces: org.acme.foo vs. Acme.Foo
Interfaces: Supplier vs. ISupplier
Methods: doSomething vs. DoSomething
Opening braces: Same line in Java vs. next line in C#

4 / 22
Type system
Basic types

Java
String
Object
boolean
char
short
int
long
double
oat
byte
—
—
—
—

C#
string
object
bool
char
short
int
long
double
oat
sbyte
byte
ushort
uint
ulong

CLR Type
String
Object
Boolean
Char
Int16
Int32
Int64
Double
Single
SByte
Byte
UInt16
UInt32
UInt64
5 / 22
Type system
Java has reference and primitive types.
C# has reference and value types.
Uses an uni ed type system, for example you can do 42.ToString()
It’s possible to create custom value types:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public override string ToString ()
{
return String . Format ("({0} ,{1})", X, Y);
}
}

6 / 22
Generics

Java uses type erasure. Generics are (mostly) a compiler feature.
new ArrayList <Integer >(). getClass ();
// -> ArrayList
new ArrayList <String >(). getClass ();
// -> ArrayList

C# uses rei ed generics. Generics are a runtime feature.
new List <int >(). GetType ();
// -> List `1[ Int32 ]
new List <string >(). GetType ();
// -> List `1[ String ]

7 / 22
Generics in Java
Code:
ArrayList <String > list1 = new ArrayList <String >();
list1 .add(" hello ");
String s = list1 .get (0);
ArrayList <Integer > list2 = new ArrayList <Integer >();
list2 .add (42);
int i = list2 .get (0);

Decompiled:
ArrayList list1 = new ArrayList ();
list1 .add(" hello ");
String s = ( String ) list1 .get (0);
ArrayList list2 = new ArrayList ();
list2 .add( Integer . valueOf (42));
int i = (( Integer ) list2 .get (0)). intValue ();
8 / 22
Generics in C#
Code:
List <string > list1 = new List <string >();
list1 .Add(" hello ");
string s = list1 [0];
List <int > list2 = new List <int >();
list2 .Add (42);
int i = list2 [0];

Decompiled:
List <string > list = new List <string >();
list.Add(" hello ");
string text = list [0];
List <int > list2 = new List <int >();
list2 .Add (42);
int num = list2 [0];
9 / 22
Generics
List factory method example

public class ListFactory {
public static <T> List <T> newList () {
// ^^^
return new ArrayList <T >();
}
}
// use with
List <String > list = ListFactory . newList ();

10 / 22
Generics
List factory method example

public class ListFactory
{
public static IList <T> newList <T >()
// ^^^
{
return new List <T >();
}
}
// use with
IList <int > list = ListFactory .newList <int >();
// Does not work:
IList <int > list = ListFactory . newList ();
// The type arguments for method
// ListFactory .newList <T >() ' cannot be inferred
// from the usage .
// Try specifying the type arguments explicitly .
11 / 22
Generics
Constraints

<T extends Comparable <T>> T max(T a, T b) {
if (a. compareTo (b) > 0)
return a;
else
return b;
}
T max <T >(T a, T b)
where T : IComparable <T>
{
if (a. CompareTo (b) > 0)
return a;
else
return b;
}
12 / 22
Generics
Constraints

where T : ClassOrInterface,
same as T extends ClassOrInterface
where T : new(), T has a parameterless constructor.
where T : class, T is a reference type.
where T : struct, T is a value type.

13 / 22
Keywords

Visibility
Common: public, protected, and private
Java: Package visibility.
C#: internal and protected internal
final vs. sealed (for methods and classes)
final vs. readonly (for members)
for (T item : items) vs. foreach (T item in items)
instanceof vs. is
Foo.class vs. typeof(Foo)

14 / 22
Exceptions

Java
Must throw a Throwable
Has checked and unchecked exceptions
Re-throw with throw e;

C#
Must throw an Exception
Has no checked exceptions
Re-throw with throw;
throw e; has a different semantic

15 / 22
Speci c features of Java

Anonymous inner classes
static import

16 / 22
Speci c features of C#

First class properties
using blocks
Preprocessor
Delegates and lambda expressions
LINQ

17 / 22
Speci c features of C#
using blocks

// using ( IDisposable )
static String ReadFirstLineFromFile ( String path) {
using ( StreamReader reader = File. OpenText (path )) {
return reader . ReadLine ();
}
}
// http :// download .java.net/jdk7/docs/ technotes /
// guides / language /try -with - resources .html
// try ( AutoClosable )
static String readFirstLineFromFile ( String path)
throws IOException {
try ( BufferedReader br =
new BufferedReader (new FileReader (path )) {
return br. readLine ();
}
}
18 / 22
Speci c features of C#
Preprocessor

public static void Main( string [] args)
{
#if DEBUG
Console . WriteLine (" Debug ␣...");
# endif
Console . WriteLine (" Hello ");
}

19 / 22
Speci c features of C#
Delegates and lambda expressions

public delegate bool Predicate <T>(T obj );
public static void Main( string [] args)
{
List <string > list = new List <string >{
" Hello ", " World ", "what 's", "up"
};
Predicate <String > shortWord ;
shortWord = delegate ( string s) { return s. Length < 4;};
shortWord = s => s. Length < 4;
list.Find( shortWord );
// or just
list.Find(s => s. Length < 4);
}

20 / 22
Speci c features of C#
LINQ

public static void Main( string [] args)
{
var list = new List <string > {
" Hello ", " World ", "what 's", "up"
};
var result = from item in list select item. Length ;
foreach (int i in result ) {
Console . WriteLine (i);
// -> 5, 5, 6, 2
}
}

21 / 22
Speci c features of C#
More features

Operator overloading
dynamic pseudo-type
yield keyword, similar to Python
Extension methods
Expression trees
Explicit interfaces
Partial classes
…
See http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java

22 / 22

More Related Content

What's hot

Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
Sagar Pednekar
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
Sunil OS
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
Michael Stal
 
C++11
C++11C++11
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
Bartlomiej Filipek
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
Sunil OS
 

What's hot (20)

Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
C++ oop
C++ oopC++ oop
C++ oop
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
C++11
C++11C++11
C++11
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 

Viewers also liked

Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
Robert Bachmann
 
JNA
JNAJNA
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?
NIIT India
 
Java vs .net
Java vs .netJava vs .net
Java vs .netTech_MX
 
Java vs .net (beginners)
Java vs .net (beginners)Java vs .net (beginners)
Java vs .net (beginners)
Ravi Vishwakarma
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
Tejasvi Rastogi
 
Jython
JythonJython
Organizing edmngt
Organizing edmngtOrganizing edmngt
Organizing edmngt
Datu jhed
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard7jebarrett
 
Unidad I Análisis Vectorial
Unidad I Análisis VectorialUnidad I Análisis Vectorial
Unidad I Análisis Vectorial
Maria Naar
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013learnerchamp
 
Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica.
Javier Camiña Muñiz
 
Danielle davis learning theory
Danielle davis   learning theoryDanielle davis   learning theory
Danielle davis learning theory
daneedavis
 
Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]
Javier Camiña Muñiz
 
Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...
Javier Camiña Muñiz
 
Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal.
Javier Camiña Muñiz
 
Cefalea en la mujer.
Cefalea en la mujer. Cefalea en la mujer.
Cefalea en la mujer.
Javier Camiña Muñiz
 
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelUtilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Javier Camiña Muñiz
 

Viewers also liked (20)

Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
 
JNA
JNAJNA
JNA
 
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?
 
Java vs .net
Java vs .netJava vs .net
Java vs .net
 
Java vs .net (beginners)
Java vs .net (beginners)Java vs .net (beginners)
Java vs .net (beginners)
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
 
Jython
JythonJython
Jython
 
Sv eng ordbok-2012
Sv eng ordbok-2012Sv eng ordbok-2012
Sv eng ordbok-2012
 
Organizing edmngt
Organizing edmngtOrganizing edmngt
Organizing edmngt
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard
 
Unidad I Análisis Vectorial
Unidad I Análisis VectorialUnidad I Análisis Vectorial
Unidad I Análisis Vectorial
 
Behaviorism Powerpoint
Behaviorism PowerpointBehaviorism Powerpoint
Behaviorism Powerpoint
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013
 
Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica.
 
Danielle davis learning theory
Danielle davis   learning theoryDanielle davis   learning theory
Danielle davis learning theory
 
Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]
 
Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...
 
Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal.
 
Cefalea en la mujer.
Cefalea en la mujer. Cefalea en la mujer.
Cefalea en la mujer.
 
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelUtilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
 

Similar to C# / Java Language Comparison

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
CodeOps Technologies LLP
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
Lesson11
Lesson11Lesson11
Lesson11
Alex Honcharuk
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
Kevin Pilch
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Java generics
Java genericsJava generics
Java generics
Hosein Zare
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Primitives in Generics
Primitives in GenericsPrimitives in Generics
Primitives in Generics
Ivan Ivanov
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
Raffi Khatchadourian
 

Similar to C# / Java Language Comparison (20)

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
C# programming
C# programming C# programming
C# programming
 
Lesson11
Lesson11Lesson11
Lesson11
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Clean Code
Clean CodeClean Code
Clean Code
 
Java generics
Java genericsJava generics
Java generics
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Primitives in Generics
Primitives in GenericsPrimitives in Generics
Primitives in Generics
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

C# / Java Language Comparison

  • 1. . . C# / Java Language Comparison Robert Bachmann April 4, 2011 1 / 22
  • 2. Outline My favorite pitfalls Common conventions Type system Generics Keywords Exceptions Speci c features of Java Speci c features of C# 2 / 22
  • 3. My favorite pitfalls str == "hello" Checks equality in C#. Checks identity in Java. Virtual methods Opt-out in Java (final keyword) vs. opt-in in C# (virtual keyword) Dates new GregorianCalendar(2011, 3, 4)1 vs. new DateTime(2011,4,4) 1 Hint: use YodaTime, Date4J, … 3 / 22
  • 4. Common conventions Package names / Namespaces: org.acme.foo vs. Acme.Foo Interfaces: Supplier vs. ISupplier Methods: doSomething vs. DoSomething Opening braces: Same line in Java vs. next line in C# 4 / 22
  • 6. Type system Java has reference and primitive types. C# has reference and value types. Uses an uni ed type system, for example you can do 42.ToString() It’s possible to create custom value types: public struct Point { public int X { get; set; } public int Y { get; set; } public override string ToString () { return String . Format ("({0} ,{1})", X, Y); } } 6 / 22
  • 7. Generics Java uses type erasure. Generics are (mostly) a compiler feature. new ArrayList <Integer >(). getClass (); // -> ArrayList new ArrayList <String >(). getClass (); // -> ArrayList C# uses rei ed generics. Generics are a runtime feature. new List <int >(). GetType (); // -> List `1[ Int32 ] new List <string >(). GetType (); // -> List `1[ String ] 7 / 22
  • 8. Generics in Java Code: ArrayList <String > list1 = new ArrayList <String >(); list1 .add(" hello "); String s = list1 .get (0); ArrayList <Integer > list2 = new ArrayList <Integer >(); list2 .add (42); int i = list2 .get (0); Decompiled: ArrayList list1 = new ArrayList (); list1 .add(" hello "); String s = ( String ) list1 .get (0); ArrayList list2 = new ArrayList (); list2 .add( Integer . valueOf (42)); int i = (( Integer ) list2 .get (0)). intValue (); 8 / 22
  • 9. Generics in C# Code: List <string > list1 = new List <string >(); list1 .Add(" hello "); string s = list1 [0]; List <int > list2 = new List <int >(); list2 .Add (42); int i = list2 [0]; Decompiled: List <string > list = new List <string >(); list.Add(" hello "); string text = list [0]; List <int > list2 = new List <int >(); list2 .Add (42); int num = list2 [0]; 9 / 22
  • 10. Generics List factory method example public class ListFactory { public static <T> List <T> newList () { // ^^^ return new ArrayList <T >(); } } // use with List <String > list = ListFactory . newList (); 10 / 22
  • 11. Generics List factory method example public class ListFactory { public static IList <T> newList <T >() // ^^^ { return new List <T >(); } } // use with IList <int > list = ListFactory .newList <int >(); // Does not work: IList <int > list = ListFactory . newList (); // The type arguments for method // ListFactory .newList <T >() ' cannot be inferred // from the usage . // Try specifying the type arguments explicitly . 11 / 22
  • 12. Generics Constraints <T extends Comparable <T>> T max(T a, T b) { if (a. compareTo (b) > 0) return a; else return b; } T max <T >(T a, T b) where T : IComparable <T> { if (a. CompareTo (b) > 0) return a; else return b; } 12 / 22
  • 13. Generics Constraints where T : ClassOrInterface, same as T extends ClassOrInterface where T : new(), T has a parameterless constructor. where T : class, T is a reference type. where T : struct, T is a value type. 13 / 22
  • 14. Keywords Visibility Common: public, protected, and private Java: Package visibility. C#: internal and protected internal final vs. sealed (for methods and classes) final vs. readonly (for members) for (T item : items) vs. foreach (T item in items) instanceof vs. is Foo.class vs. typeof(Foo) 14 / 22
  • 15. Exceptions Java Must throw a Throwable Has checked and unchecked exceptions Re-throw with throw e; C# Must throw an Exception Has no checked exceptions Re-throw with throw; throw e; has a different semantic 15 / 22
  • 16. Speci c features of Java Anonymous inner classes static import 16 / 22
  • 17. Speci c features of C# First class properties using blocks Preprocessor Delegates and lambda expressions LINQ 17 / 22
  • 18. Speci c features of C# using blocks // using ( IDisposable ) static String ReadFirstLineFromFile ( String path) { using ( StreamReader reader = File. OpenText (path )) { return reader . ReadLine (); } } // http :// download .java.net/jdk7/docs/ technotes / // guides / language /try -with - resources .html // try ( AutoClosable ) static String readFirstLineFromFile ( String path) throws IOException { try ( BufferedReader br = new BufferedReader (new FileReader (path )) { return br. readLine (); } } 18 / 22
  • 19. Speci c features of C# Preprocessor public static void Main( string [] args) { #if DEBUG Console . WriteLine (" Debug ␣..."); # endif Console . WriteLine (" Hello "); } 19 / 22
  • 20. Speci c features of C# Delegates and lambda expressions public delegate bool Predicate <T>(T obj ); public static void Main( string [] args) { List <string > list = new List <string >{ " Hello ", " World ", "what 's", "up" }; Predicate <String > shortWord ; shortWord = delegate ( string s) { return s. Length < 4;}; shortWord = s => s. Length < 4; list.Find( shortWord ); // or just list.Find(s => s. Length < 4); } 20 / 22
  • 21. Speci c features of C# LINQ public static void Main( string [] args) { var list = new List <string > { " Hello ", " World ", "what 's", "up" }; var result = from item in list select item. Length ; foreach (int i in result ) { Console . WriteLine (i); // -> 5, 5, 6, 2 } } 21 / 22
  • 22. Speci c features of C# More features Operator overloading dynamic pseudo-type yield keyword, similar to Python Extension methods Expression trees Explicit interfaces Partial classes … See http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java 22 / 22