C# vs Java Programming Construct
Programming Construct
Both programming language makes use of constructs in controlling the flow of the execution of a program based on whether a certain condition is satisfied or not. They both make use of the selection, looping and branching constructs.
Selection construct - which executes a particular block based on a Boolean condition, example of selection construct similar in both languages are: if, if… else, switch…case constructs.
If selection construct
int num = -4;
if (num < 0)
{
Console.WriteLine(“The number is negative”);
}
Looping construct - which enables you to iteratively or repeatedly execute a single statement or a block of statements,example of looping construct similar in both C# and Java are: while, do...while, for, enhanced for looping construct.
public int val = 1;
while (val <= 10)
{
Console.WriteLine(num);
val++;
}
}
Branching construct - These are used to transfer control from one point in a program to another, example of branching construct similar in both languages are:
break, continue, return
Console.WriteLine(“Even numbers between 1-100”);
for (int i=1; i<=100; i++)
{
if (i % 2 != 0)
{
continue;
}
Console.Write(i + “ “);
}
COMPARISON TABLE
Statements Java C#
Loops Yes Yes
Conditionals Yes Yes
Flow control Yes Yes
Assignment Yes Yes
Exception control Yes Yes
Variable declaration Yes Yes
Variable type inference No Yes
Deterministic disposal (ARM-blocks) Yes (starting with Java 7) Yes
long type in switch statement Yes No
String type in switch statement Yes Yes
Case fall-through* Yes No
Labelled statements Yes; goto statement Yes; Expanded continue and break statement
goto jump statement** No Yes
*Case fall-through
In C#, the flw of execution from one case Java allows statement executing associated with one case to continue into the
statement is not allowed to continue to the next case next case, This continuation of execution into the next case is referred to as falling through
statement. This is referred to as the
‘no-fall-through’ rule of C#. Case Fall-through in Java
class ClashApp
{
public static void main(String[] args)
{
string input;
switch (input)
{
case “MONDAY”:
case “TUESDAY”:
case “WEDNESDAY”:
case “THURSDAY”:
case “FRIDAY”:
Console.WriteLine (“Week days of the week”);
break;
case “SATURDAY”:
case “SUNDAY”:
Console.WriteLine (“Weekends of the week”);
break;
default:
Console.WriteLine (“Incorrect choice”);
break;
}
}
}
The code snippet above illustrate how fall-through within case statements is allowed.
**goto jump statement
C# supports the goto jump statements. This enables you to directly execute a labeled(an identifier ending with a colon.) statement or a labeled block of statements.
using System;
class ClashApp
{
public static void Main(String[] args)
{
int i = 0;
labelledBlock:
Console.WriteLine(“ClashApp”);
i++;
if (i < 10)
{
goto labelledBlock;
}
}
}
On encountering the goto statement the execution of the program is directed to the labeledBlock.
Java defines an expanded form of break and continue statements. These expanded forms can be used
within any block. It is not necessary that the blocks must be part of loop or a switch statement. These are also referred to as labeled statements
{
public class ClashApp {
public static void main(String[] args)
{
outer:
for (int j = 1; j < 5; j++) {
if(j == 4)
{
continue outer;
System.out.print(j);
}
System.out.print("Thank you");
}
}
Upon the incremental value of j equals 4, the execution is transferred to the outer labelled statement and displays "Thank you".
Partial types, Classes and Objects
Brief similarity
~All Objects are References
Reference types are very similar to pointers in C++, particularly when setting an identifier to some new class instance. But when accessing the properties or methods of this reference type, use the "." operator, which is similar to accessing data instances in C++ that are created on the stack. All class instances are created on the heap by using the new operator, but delete is not allowed, as both languages use their own garbage collection schemes.
~DATE/CALENDAR COMPLEX TYPES
Both languages' libraries define classes for working with dates and calendars in different cultures. The Java java.util.Date is a mutable reference type, where the C# System.DateTime is a struct value type. C# additionally define a TimeSpan type for working with time periods. Both languages support date and time arithmetic according to different cultures.
~New operator
The new operator is used to instantiate an object, On encountering the new operator, the JIT compiler allocates memory for the object and returns a reference of that allocated memory.
C# Code
using System;
class ClashApp
{
ClashApp()
{
Console.WriteLine("In instance constructor");
}
public static void Main(string[] args)
{
ClashApp objectClashApp = new ClashApp();
}
} In the snippet above, the new operator is used to create an instance of the ClashApp class.
Java Code
class ClashApp{
ClashApp()
{
System.out.println("In instance constructor");
}
public static void main(String[] args){
ClashApp objectClashApp = new ClashApp();
}
In the snippet above, the new operator is used to create an instance of the ClashApp class.
~Member Initialization at Definition and Static Constructors
Instance and static variables can be initialized at their point of definition in both C# and 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. 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. These code blocks are called are called static constructors in C# and static initialization blocks in 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.
C# Code
using System;
class ClashApp
{
ClashApp()
{
Console.WriteLine("In instance constructor");
}
static ClashApp(){
Console.WriteLine("In static constructor");
}
public static void Main(string[] args)
{
ClashApp objectClashApp = new ClashApp();
}
}
Java Code
class ClashApp{
ClashApp()
{
System.out.println("In instance constructor");
}
static
{
System.out.println("In static constructor");
}
public static void main(String[] args){
ClashApp objectClashApp = new ClashApp();
}
}
OUTPUT FROM BOTH EXAMPLES:
In static constructor
In instance constructor
From the snippet above, it is clear that the static constructor/block is first executed even before the main method.
Comparison table
Partial types, classes, objects Java C#
Static Constructor* No Yes
Destructors** No Yes
Finalizers** Yes Yes
Dispose Method*** No Yes
New modifier**** No Yes
Initialization block***** Yes No
Partial types****** No Yes
*STATIC CONSTRUCTORS C# provides the static constructor which is used to initilize static variables of the class and to perform a partiular action only once. It is invoked before any static member of the class is accessed.
class Multiplication
{
static int numOne = 10;
static int numTwo;
static Initializer()
{
Console.WriteLine(“Static Constructor initialized”);
numTwo = numOne;
}
public static void Printer()
{
Console.WriteLine(numTwo);
}
static void Main(string[] args)
{
Multiplication.Printer();
}
}
The static constructor Initializer initializes the static variable numTwo.
**DESTRUCTORS/FINALIZERS
C# also has the concept of destructors which use syntax similar to C++ destructor syntax but have the mostly the same semantics as Java finalizers. The finalize() method is called by the garbage collector on an object when it is identified to have no more references pointing to it. Although finalizers exist doing work within them is not encouraged for a number of reasons including the fact that there is no way to control the order of finalization which can lead to interesting problems if objects that hold references to each other are finalized out of order. Finalization also causes more overhead because objects with finalizers aren't removed after the garbage collection thread runs but instead are eliminated after the finalization thread runs which means they have to be maintained in the system longer than objects without finalizers. Below are equivalent examples in C# and Java.
C# Code
using System;
public class ClashApp
{
static int num_created = 0;
int i = 0;
ClashApp()
{
i = ++num_created;
Console.WriteLine("Created object #" + i);
}
//destructor
~ClashApp()
{
Console.WriteLine("Object #" + i + " is being finalized");
}
public static void Main(string[] args){
for(int i=0; i < 10000; i++)
new ClashApp();
}
} In the code snippet above, the destructor is called using the ~symbol on the ClashApp object prepping it for garbage collection
Java Code
public class ClashApp {
static int num_created = 0;
int i = 0;
ClashApp(){
i = ++num_created;
System.out.println("Created object #" + i);
}
public void finalize(){
System.out.println("Object #" + i + " is being finalized");
}
public static void main(String[] args){
for(int i=0; i < 10000; i++)
new ClashApp();
}
} In the code snippet above, the finalize method is called on the ClashApp object prepping it for garbage collection
***Dispose method
If a class is disposable, it is best to make usage of the Dispose() method of the IDisposable interface, Calling the Dispose() method does not request that the object is garbage collected , although it does speed up collection by eliminating the need for finalization.
C# Code
using System;
using System.IO;
public class ClashApp : IDisposable {
bool disposed = false;
FileStream f;
StreamWriter sw;
private String name;
private int numShowNameCalls = 0;
ClashApp(string name){
f = new FileStream("logfile.txt", FileMode.OpenOrCreate);
sw = new StreamWriter(f);
this.name = name;
Console.WriteLine("Created " + name);
}
~ClashApp(){
Dispose(false);
}
public void Dispose(){
if(!disposed){
Dispose(true);
}
} ****NEW Modifier
the new modifier is used to hide the methods or variables of the base class that are inherited in the derived class. This allows you to redefie the inherited methods or variables in the derived class.
class CodePlay
{
int val = 1;
public void Display()
{
Console.WriteLine(“Value:“ + val);
}
}
class ClashApp : CodePlay
{
int val;
new void Display()
{
base.Display();
}
static void Main(String[] args)
{
ClashApp objectClashApp = new ClashApp();
objectClashApp.Display();
}
}
The new Modifier provides another implementation of the Display method thereby overriding the Display method provided by the base class CodePlay.
*****Initialization block
java uses initialization blocks which initializes the instance variables or fields of the class. The initialization blocks are basically used to perform complex initialization sequences.
C#
public class ClashApp
{
//Initialization block
private int numOne;
{
numOne = 1;
}
public void display()
{
System.out.println(numOne);
}
}
In the code snippet above the initialization block within the class ClashApp intializes the private variable numOne.
******PARTIAL TYPES
C# allows a class, structures and interface definition to be split across several source files using a feature called partial types. Each part must be marked with the keyword partial. All the parts must be presented to the compiler as part of a single compilation.
using System;
using System.Collections.Generic;
using System.Text;
//Stored in AppDetails.cs fie
namespace Application
{
public partial class AppDetails
{
string appName;
public AppDetails(string name)
{
appName = name;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
//Stored in App.cs fie
namespace Application
{
public partial class AppDetails
{
public void Display()
{
Console.WriteLine(“Appication Name: “ + appName);
}
}
public class Application
{
static void Main(string[] args)
{
AppDetails objApplication = new AppDetails(“ClashApp”);
objApplication.Display();
}
}
}
On compiling both files in the Application namespace, the partial classes AppDetails existing in two different files are merged together producing an .exe file.
Both programming language makes use of constructs in controlling the flow of the execution of a program based on whether a certain condition is satisfied or not. They both make use of the selection, looping and branching constructs.
Selection construct - which executes a particular block based on a Boolean condition, example of selection construct similar in both languages are: if, if… else, switch…case constructs.
If selection construct
int num = -4;
if (num < 0)
{
Console.WriteLine(“The number is negative”);
}
Looping construct - which enables you to iteratively or repeatedly execute a single statement or a block of statements,example of looping construct similar in both C# and Java are: while, do...while, for, enhanced for looping construct.
public int val = 1;
while (val <= 10)
{
Console.WriteLine(num);
val++;
}
}
Branching construct - These are used to transfer control from one point in a program to another, example of branching construct similar in both languages are:
break, continue, return
Console.WriteLine(“Even numbers between 1-100”);
for (int i=1; i<=100; i++)
{
if (i % 2 != 0)
{
continue;
}
Console.Write(i + “ “);
}
COMPARISON TABLE
Statements Java C#
Loops Yes Yes
Conditionals Yes Yes
Flow control Yes Yes
Assignment Yes Yes
Exception control Yes Yes
Variable declaration Yes Yes
Variable type inference No Yes
Deterministic disposal (ARM-blocks) Yes (starting with Java 7) Yes
long type in switch statement Yes No
String type in switch statement Yes Yes
Case fall-through* Yes No
Labelled statements Yes; goto statement Yes; Expanded continue and break statement
goto jump statement** No Yes
*Case fall-through
In C#, the flw of execution from one case Java allows statement executing associated with one case to continue into the
statement is not allowed to continue to the next case next case, This continuation of execution into the next case is referred to as falling through
statement. This is referred to as the
‘no-fall-through’ rule of C#. Case Fall-through in Java
class ClashApp
{
public static void main(String[] args)
{
string input;
switch (input)
{
case “MONDAY”:
case “TUESDAY”:
case “WEDNESDAY”:
case “THURSDAY”:
case “FRIDAY”:
Console.WriteLine (“Week days of the week”);
break;
case “SATURDAY”:
case “SUNDAY”:
Console.WriteLine (“Weekends of the week”);
break;
default:
Console.WriteLine (“Incorrect choice”);
break;
}
}
}
The code snippet above illustrate how fall-through within case statements is allowed.
**goto jump statement
C# supports the goto jump statements. This enables you to directly execute a labeled(an identifier ending with a colon.) statement or a labeled block of statements.
using System;
class ClashApp
{
public static void Main(String[] args)
{
int i = 0;
labelledBlock:
Console.WriteLine(“ClashApp”);
i++;
if (i < 10)
{
goto labelledBlock;
}
}
}
On encountering the goto statement the execution of the program is directed to the labeledBlock.
Java defines an expanded form of break and continue statements. These expanded forms can be used
within any block. It is not necessary that the blocks must be part of loop or a switch statement. These are also referred to as labeled statements
{
public class ClashApp {
public static void main(String[] args)
{
outer:
for (int j = 1; j < 5; j++) {
if(j == 4)
{
continue outer;
System.out.print(j);
}
System.out.print("Thank you");
}
}
Upon the incremental value of j equals 4, the execution is transferred to the outer labelled statement and displays "Thank you".
Partial types, Classes and Objects
Brief similarity
~All Objects are References
Reference types are very similar to pointers in C++, particularly when setting an identifier to some new class instance. But when accessing the properties or methods of this reference type, use the "." operator, which is similar to accessing data instances in C++ that are created on the stack. All class instances are created on the heap by using the new operator, but delete is not allowed, as both languages use their own garbage collection schemes.
~DATE/CALENDAR COMPLEX TYPES
Both languages' libraries define classes for working with dates and calendars in different cultures. The Java java.util.Date is a mutable reference type, where the C# System.DateTime is a struct value type. C# additionally define a TimeSpan type for working with time periods. Both languages support date and time arithmetic according to different cultures.
~New operator
The new operator is used to instantiate an object, On encountering the new operator, the JIT compiler allocates memory for the object and returns a reference of that allocated memory.
C# Code
using System;
class ClashApp
{
ClashApp()
{
Console.WriteLine("In instance constructor");
}
public static void Main(string[] args)
{
ClashApp objectClashApp = new ClashApp();
}
} In the snippet above, the new operator is used to create an instance of the ClashApp class.
Java Code
class ClashApp{
ClashApp()
{
System.out.println("In instance constructor");
}
public static void main(String[] args){
ClashApp objectClashApp = new ClashApp();
}
In the snippet above, the new operator is used to create an instance of the ClashApp class.
~Member Initialization at Definition and Static Constructors
Instance and static variables can be initialized at their point of definition in both C# and 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. 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. These code blocks are called are called static constructors in C# and static initialization blocks in 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.
C# Code
using System;
class ClashApp
{
ClashApp()
{
Console.WriteLine("In instance constructor");
}
static ClashApp(){
Console.WriteLine("In static constructor");
}
public static void Main(string[] args)
{
ClashApp objectClashApp = new ClashApp();
}
}
Java Code
class ClashApp{
ClashApp()
{
System.out.println("In instance constructor");
}
static
{
System.out.println("In static constructor");
}
public static void main(String[] args){
ClashApp objectClashApp = new ClashApp();
}
}
OUTPUT FROM BOTH EXAMPLES:
In static constructor
In instance constructor
From the snippet above, it is clear that the static constructor/block is first executed even before the main method.
Comparison table
Partial types, classes, objects Java C#
Static Constructor* No Yes
Destructors** No Yes
Finalizers** Yes Yes
Dispose Method*** No Yes
New modifier**** No Yes
Initialization block***** Yes No
Partial types****** No Yes
*STATIC CONSTRUCTORS C# provides the static constructor which is used to initilize static variables of the class and to perform a partiular action only once. It is invoked before any static member of the class is accessed.
class Multiplication
{
static int numOne = 10;
static int numTwo;
static Initializer()
{
Console.WriteLine(“Static Constructor initialized”);
numTwo = numOne;
}
public static void Printer()
{
Console.WriteLine(numTwo);
}
static void Main(string[] args)
{
Multiplication.Printer();
}
}
The static constructor Initializer initializes the static variable numTwo.
**DESTRUCTORS/FINALIZERS
C# also has the concept of destructors which use syntax similar to C++ destructor syntax but have the mostly the same semantics as Java finalizers. The finalize() method is called by the garbage collector on an object when it is identified to have no more references pointing to it. Although finalizers exist doing work within them is not encouraged for a number of reasons including the fact that there is no way to control the order of finalization which can lead to interesting problems if objects that hold references to each other are finalized out of order. Finalization also causes more overhead because objects with finalizers aren't removed after the garbage collection thread runs but instead are eliminated after the finalization thread runs which means they have to be maintained in the system longer than objects without finalizers. Below are equivalent examples in C# and Java.
C# Code
using System;
public class ClashApp
{
static int num_created = 0;
int i = 0;
ClashApp()
{
i = ++num_created;
Console.WriteLine("Created object #" + i);
}
//destructor
~ClashApp()
{
Console.WriteLine("Object #" + i + " is being finalized");
}
public static void Main(string[] args){
for(int i=0; i < 10000; i++)
new ClashApp();
}
} In the code snippet above, the destructor is called using the ~symbol on the ClashApp object prepping it for garbage collection
Java Code
public class ClashApp {
static int num_created = 0;
int i = 0;
ClashApp(){
i = ++num_created;
System.out.println("Created object #" + i);
}
public void finalize(){
System.out.println("Object #" + i + " is being finalized");
}
public static void main(String[] args){
for(int i=0; i < 10000; i++)
new ClashApp();
}
} In the code snippet above, the finalize method is called on the ClashApp object prepping it for garbage collection
***Dispose method
If a class is disposable, it is best to make usage of the Dispose() method of the IDisposable interface, Calling the Dispose() method does not request that the object is garbage collected , although it does speed up collection by eliminating the need for finalization.
C# Code
using System;
using System.IO;
public class ClashApp : IDisposable {
bool disposed = false;
FileStream f;
StreamWriter sw;
private String name;
private int numShowNameCalls = 0;
ClashApp(string name){
f = new FileStream("logfile.txt", FileMode.OpenOrCreate);
sw = new StreamWriter(f);
this.name = name;
Console.WriteLine("Created " + name);
}
~ClashApp(){
Dispose(false);
}
public void Dispose(){
if(!disposed){
Dispose(true);
}
} ****NEW Modifier
the new modifier is used to hide the methods or variables of the base class that are inherited in the derived class. This allows you to redefie the inherited methods or variables in the derived class.
class CodePlay
{
int val = 1;
public void Display()
{
Console.WriteLine(“Value:“ + val);
}
}
class ClashApp : CodePlay
{
int val;
new void Display()
{
base.Display();
}
static void Main(String[] args)
{
ClashApp objectClashApp = new ClashApp();
objectClashApp.Display();
}
}
The new Modifier provides another implementation of the Display method thereby overriding the Display method provided by the base class CodePlay.
*****Initialization block
java uses initialization blocks which initializes the instance variables or fields of the class. The initialization blocks are basically used to perform complex initialization sequences.
C#
public class ClashApp
{
//Initialization block
private int numOne;
{
numOne = 1;
}
public void display()
{
System.out.println(numOne);
}
}
In the code snippet above the initialization block within the class ClashApp intializes the private variable numOne.
******PARTIAL TYPES
C# allows a class, structures and interface definition to be split across several source files using a feature called partial types. Each part must be marked with the keyword partial. All the parts must be presented to the compiler as part of a single compilation.
using System;
using System.Collections.Generic;
using System.Text;
//Stored in AppDetails.cs fie
namespace Application
{
public partial class AppDetails
{
string appName;
public AppDetails(string name)
{
appName = name;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
//Stored in App.cs fie
namespace Application
{
public partial class AppDetails
{
public void Display()
{
Console.WriteLine(“Appication Name: “ + appName);
}
}
public class Application
{
static void Main(string[] args)
{
AppDetails objApplication = new AppDetails(“ClashApp”);
objApplication.Display();
}
}
}
On compiling both files in the Application namespace, the partial classes AppDetails existing in two different files are merged together producing an .exe file.
Comments
Post a Comment