C# vs Java: Variables and operators cont'd

COMPARISON TABLE

 Expressions and operators     Java     C#
 Arithmetic operators                Yes      Yes
 Logical operators                     Yes      Yes
 Bitwise logic operators             Yes      Yes
 Conditional                             Yes Yes
 String concatenation                    Yes      Yes
 Casts                                      Yes      Yes
 Boxing                                      Yes; implicit   Yes; implicit
 Unboxing                                 Yes; implicit   Yes; explicit
 Lifted operators                     No      Yes
 Overflow control                      No      Yes
 Strict floating point evaluation************ Yes; opt-in/out   No
 Verbatim (here-)strings             No      Yes
 Userdefined value-types*             Yes; struct    No
 boolean data-type               boolean     bool
 Contextual keywords**              No       Yes
 Static initializaton block***            Yes      No
 Implicitly typed variables*****    No       Yes
 Variable lenght parameter list*****   Yes      Yes
 Unsigned integer types******     No       Yes
 binary value as integer type            Yes      No
 Underscore between digits             Yes      No
 Lifted nullable types*******     No       Yes
 const keyword********              No       Yes
 String literals*********             Regular     Regular nd verbatim
 Named Parameters**********     No       Yes
 Optional Parameters**********     No       Yes
 Ref/Out Keywords***********      No       Yes
 sizeOf Operator                          No       Yes

 *User-defined value-types
 C# allows the programmer to create user-defined value types, using the struct keyword. Unlike classes and like the standard primitives, such value types are passed and assigned by value rather than by reference. They can also be part of an object (either as a field or boxed), or stored in an array without the memory indirection that normally exists for class types. Struct are used to specify stack based classes, one declares them using the keyword struct instead of class. To create C# structs (also known as value types) one uses the new keyword to create it as is done with classes. If the struct is instantiated with the default constructor syntax then a struct with its fields zeroed out is created. However, it is not possible to define a default constructor for a struct and override this behavior.

 C# Code
 using System;

 struct Point {
     public int numOne;
     public int numTwo;

     public Point( int numOne, int numTwo){
  
     this.numne = numOne;
     this.Two = numTwo;

     }
  
     public override string ToString(){

     return String.Format("({0}, {1})", numOne, numTwo);
     }

     public static void Main(string[] args){

     Point start = new Point(5, 9);
     Console.WriteLine("Start: " + start);

     /* The line below wouldn't compile if Point was a class */
     Point end = new Point();
     Console.WriteLine("End: " + end);

     }
 }
 The code snippet above, uses struct in initializing and displaying the values of the variables numOne and numTwo;

 **CONTEXTUAL KEYWORDS
  C# provides contextual keywords that have special meaning in the context of the code where they are used. The contextual keywords are not reserved and can be used as identifiers outside the context of the code. When new keywords are added to C#, they are added as contextual keywords
 C# contextual keywords
 add   alias  ascending  async-await  descending   yield   dynamic  from   get   global   group   into   join   let  orderby partial remove  select   set     value     var   where


***Static initialization block
Java provides the static block is used to initialize static variables  as selection as the class is launched. They are used when a block of code needs to be executed during loading of the class by JVM. They are executed before the main() method is executed.

                public class ClashApp
                {
                  static{
                     System.out.println("ClashApp in static block");
                    }
                  public static void staticMethod()
                   {
                    System.out.println("CodePlay in static method");
                   }
                   public static void main(String[] args)
                   {
                    System.out.println("Main method");
                    staticMethod();
                   }
                 }

                 The code snippet above, uses the static block, static method and the main method to display values to the console.

 ****IMPLICITLY TYPED VARIABLE
  When you declare and initialize a variable in a single step, you can use the var keyword in place of the type declaration. Variables declared using the var keyword are called implicitly typed variables. For implicitly typed variables, the compiler infers the type of the variable from the initialization expression

  using System;
  class ClashApp
  {
   public static void Main(String[] args)
   {
    var boolTest = true;
    var byteTest = 19;
    var intTest =140000;
    var stringTest = “David”;
    var flatTest = 14.5f;
    Console.WriteLine(“boolTest = {0}”, boolTest);
    Console.WriteLine(“byteTest = ” + byteTest);
    Console.WriteLine(“intTest = ” + intTest);
    }
  }

  In the code snippet above, four implicitly typed variables are declared and initialized with values. The values of each variable are displayed using the WriteLine()  method of the Console class.


 *****Variable Length Parameter Lists
 In C and C++ it is possible to specify that a function takes a variable number of arguments. This functionality is used extensively in the printf and scanf family of functions. Both C# and Java allow one to define a parameter that indicates that a variable number of arguments are accepted by a method. In C#, the mechanism for specifying that a method accepts a variable number of arguments is by using the params keyword as a qualifier to the last argument to the method which should be an array.

 C# Code
 using System;

 class ClashApp
 {

     public static void PrintInts(string title, params int[] args)
     {
      Console.WriteLine(title + ":");
      foreach(int num in args)
      Console.WriteLine(num);
     }
     public static void Main(string[] args)
     {
      PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
     }
 }

 In the code snippet above, a variable number of argument is passed to the PrintInts method which is declare with the params parameter.

 In Java, the same effect is achieved by appending the string "..." to the type name of the last argument to the method.

 class ClashApp{
     public static void PrintInts(String title, Integer... args){
     System.out.println(title + ":");
     for(int num : args)
         System.out.println(num);
           }

     public static void main(String[] args){
     PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
     }

 }
 In the code snippet above, a variable number of argument is passed to the PrintInts method which is declared by appending the string "..." to the Integer.


************strictfp 
Javas strictfp keyword enables strict floating-point calculations for a region of code. Strict floating-point calculations require that even if a platform offers higher precision during calculations, intermediate results must be converted to single/double. This ensures that strict floating point calculations return exactly the same result on all platforms. Without strict floating point a platform implementation is free to use higher precision for intermediate results during calculation. C# allows an implementation for a given hardware architecture to always use a higher precision for intermediate results if available, i.e. C# does not allow the programmer to optionally force intermediate results to use the potential lower precision of float/double.
 In Java, strictfp ensure strict floating point arithmetic that conforms to behavior specified in the IEEE standard 754 for binary floating-point arithmetic (IEEE 754). Within an FP-strict expression, all intermediate values must be members of the float or double value set, depending on whether the expression is evaluating floats or doubles. Within expressions that are not FP-strict, it is allowable for the JVM implementation to use an extended exponent range to represent intermediate results. The example below clarifies the difference between FP-strict and non-FP-strict expressions.
 C# specification covers floating point numbers and states that due to the excessive performance costs of enforcing that certain architectures perform operations with less precision than is possible, there is no way to enforce FP-strictness in C#.

 Java Code
 public class ClashApp {
     static strictfp double strictFp(double n){
     return n * 4.0  * 0.5;
     }

     static double strictNFP(double n){
     return n * 4.0 * 0.5;
     }

     public static void main(String[] args) {
    
     double d = 6.6e+307;
    
     System.out.println(strictFP(d));

     System.out.println(strictNFP(d));
     }

 }
 In the above example the value printed by calling strictFP() will be "Infinity" regardless of what JVM the application is run on. This is because Java enforces left-to-right evaluation of arguments and 6.6e+307 multiplied by 4.0 exceeds the maximum value for a double thus leading to all subsequent operations yielding Infinity. On the other hand the value printed on calling strictNFP() may not be the same on different JVMs depending on whether the target platform and JVM implementation support storing intermediate values in an extended format that has a larger range than that of doubles. Thus on some platforms the value 1.32E308 is printed as the value returned by strictNFP() while on others "Infinity" is printed.


OPERATOR OVERLOADING
 Operator overloading and user-defined casts are separate features that both aim to allow new types to become first-class citizens in the type system. By using these features in C#, types such as Complex and decimal have been integrated so that the usual operators like addition and multiplication work with the new types. Unlike C++, C# does restrict the use of operator overloading, prohibiting it for the operators new, ( ), ||, &&, =, and any variations of compound statements like +=. But compound operators will call overloaded simple operators, like -= calling - and =.

 public class Vector3D
 {
  public static Vector3D operator + (Vector3D v)
  {
   return (new Vector3D(x+v.x,y+v.y,z+v.z));
  }
 }

 The code snippet above shows the overloading of the addition operator.

ENUMERATION
  Both languages define enumerations, but they are implemented in fundamentally different ways. As such, enumerations are one area where tools designed to automatically translate code between the two languages (such as Java to C# converters) fail.
  In both C# and Java, programmers can use enumerations in a switch statement without conversion to a string or primitive integer type.
  C# has implemented enumerations in a manner similar to C, that is as wrappers around the bit-flags implemented in primitive integral types (int, byte, short, etc.). This has performance benefits and improves interaction with C/C++ compiled code, but provides fewer features and can lead to bugs if low-level value types are directly cast to an enumeration type, as is allowed in the C# language. In contrast, Java implements enumerations as full featured collection of instances, requiring more memory and not aiding interaction with C/C++ code, but providing additional features in reflection and intrinsic behavior.

  DEFINING
 Enumerations in C# are implicitly derived from the Enum type that again is a value type derivative. The value set of a C# enumeration is defined by the underlying type that can be a signed or unsigned integer type of 8, 16, 32 or 64 bits. The enumeration definition defines names for the selected integer values. By default the first name is assigned the value 0 (zero) and the following names are assigned in increments of 1. Any value of the underlying primitive type is a valid value of the enumeration type, though an explicit cast may be needed to assign it.

C# Code
 using System;

 public enum Days{
     SUNDAY,
     SATURDAY,
     MONDAY,
     TUESDAY,
     WEDNESDAY,
     THURSDAY,
     FRIDAY
 }

 public class ClashApp{
     public static bool isDay(Days day){
  return !isEnd(day);  
     }

     public static bool isEnd(DaysOfWeek day){
  return (day == Days.SUNDAY || day == Days.SATURDAY);
     }

     public static void Main(String[] args){
  Days a = Days.SUNDAY;
  Console.WriteLine(isEnd(a));
  Console.WriteLine(isDay(a));

  /* Example of how C# enums are not type safe */
  a = (Days) 1;
  Console.WriteLine(a);

     }
 }

The code snippet above, creates an enum to save the values of the days of the week.
In Java, the enumeration type is a class, and its values are objects (instances) of that class. The only valid values are the ones listed in the enumeration. The enumeration type may declare fields, allowing each individual enumerated value to reference additional data associated uniquely with that specific value. The enumeration type may also declare or override methods, or implement interfaces.
               
                Java Code
                   enum DaysOfWeek{
                       SUNDAY,
                       MONDAY,
                       TUESDAY,
                       WEDNESDAY,
                       THURSDAY,
                       FRIDAY,
                       SATURDAY;

                       public boolean isWeekDay(){
                    return !isWeekEnd();  
                       }

                       public boolean isWeekEnd(){
                    return (this == SUNDAY || this == SATURDAY);
                       }

                   }
                   public class ClashApp{
                       public static void main(String[] args) throws Exception{
                    DaysOfWeek sun = DaysOfWeek.SUNDAY;
                    System.out.println("Is " + sun + " a weekend? " + sun.isWeekEnd());
                    System.out.println("Is " + sun + " a week day? " + sun.isWeekDay());
                       }
                   }

                   The code snippet above, creates an enum to save the values of the days of the week.

Combining enumerated values
C# supports bit-mapped enumerations where an actual value may be a combination of enumerated values bitwise or'ed together. The formatting and parsing methods implicitly defined by the type will attempt to use these values.
                   Java enumeration set and map collections provide functionality to combine multiple enumeration values to a combined value. These special collections allows compiler optimization to minimize the overhead incurred by using collections as the combination mechanism.

******PRIMITIVE DATA TYPES
 C# supports unsigned in addition to the signed integer types. The unsigned types are byte, ushort, uint and ulong for 8, 16, 32 and 64 bit widths, respectively. Unsigned arithmetic operating on the types are supported as well. For example, adding two unsigned integers (uints) still yields a uint as a result; not a long or signed integer.
 Java does not feature unsigned integer types. In particular, Java lacks a primitive type for an unsigned byte. Instead Java's byte type is sign extended which is a common source of bugs and confusion.
 Unsigned integers were deliberately left out of Java because James Gosling believed that programmers would not understand how unsigned arithmetic works.

 Pre-defied data types in C#   
 byte Unsigned 8-bit integer 0 to 255 
 sbyte Signed 8-bit integer -128 to 127
 short Signed 16-bit integer -32,768 to 32,767
 ushort Unsigned 16-bit integer 0 to 65,535
 int Signed 32-bit integer -2,147,483,648 to 2,147,483,647
 uint Unsigned 32-bit integer 0 to 4,294,967,295
 long Signed 64-bit integer -9,223,372,036,854,775, 808 to
 9,223,372,036,854,775,807
 ulong Unsigned 64-bit integer 0 to 18,446,744,073,709,551,61
 5
 flat 32-bit flatig point with 7 digits
 precision
 ±1.5e−45 to ±3.4e38
 double 64-bit flatig point with 15-16
 digits precision
 ±5.0e−324 to ±1.7e308
 decimal 128-bit flatig point with 28-29
 digits precision
 ±1.0 × 10e−28 to ±7.9 × 10e28
 char Unicode 16-bit character U+0000 to U+ff
 bool Stores either true or false true or false

 Predefined datatype in java(doesnot support unsigned integer)
 byte 8-bit integer -128 to 127.
 short 16-bit integer 32,768 to 32,767
 int 32-bit integer  -2,147,483,648 to 2,147,483,647
 long 64-bit integer-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
 float 32-bit floatig point with 7 digits precision ±1.5e−45 to ±3.4e38
 double 64-bit floatig point with 15-16 digits precision ±5.0e−324 to ±1.7e308
 char Unicode 16-bit character 0 (‘\u0000’) to 65,535 (‘\uffff’)
 bool Stores either true or false true or false

*******LIFTED NULLABLE TYPES
 C# allows primitive types to be "lifted" to allow the special null value in addition to the type's native values. A type is lifted by adding a ? suffix to the type name, this is equivalent to using the Nullable<T> generic type, where T is the type to be lifted. Conversions are implicitly defined to convert between values of the base and the lifted type. The lifted type can be compared against null or it can be tested for HasValue. Also, lifted operators are implicitly and automatically defined based on their non-lifted base, where — with the exception of some boolean operators — a null argument will propagate to the result.

 using System;
 public class ClashApp
 {

  public static void Main(string[] args){
   int? clash = 5;
 
   if(clash.HasValue){
    Console.WriteLine("clash value is " + clash.Value);
   }

   clash = null;
   //prints 0
   Console.WriteLine(clash.GetValueOrDefault());
  }

 }
 In the code snippet above, the variable clash is lifted so as to allow a null value using the "?" suffix.

Java does not support type lifting as a concept, but all of the built-in primitive types have corresponding wrapper types, which do support the null value by virtue of being reference types (classes).
              null literal for reference types
              { ClashClass objectApp = null;}
  There is also the GetValueOrDefault() method which either returns the value of the nullable type or the default value of the underlying value type if it is null.

 The ?? operator is called the null coalescing operator and is used for testing the value of a nullable type and returning its value or an alternate if its value is null. Thus x ?? y is equivalent to x == (null ? y : x).

C# Code
 using System;

 public class Test{
  public static void Main(string[] args)
  {

   int? clash = null;
   int  app = clash ?? 1;

   //prints out 1
   Console.WriteLine(app);
  }

 }
 In the code snippet above, the coalesce operator "??" is used to initialize the app variable to 1 if clash = null.

********CONSTANTS AND LITERALS
 Constants are variables with identifier modifier allowing only read access on the identifier variable after creation and initialization. An attempt to modify the variable afterwards will generate a compile-time error.
 The const keyword is used in C# for compile time constants while the readonly keyword is used for runtime constants. The semantics of constant primitives and object references in C# is the same as in Java.

 C# Code

 using System;
 public class ClashApp
 {
  public static void Main(String [] args)
  {
   const float _pi = 3.14F;
   float radius = 5;
   public static readonly int app = 5;
   readonly Object o = new Object();
   flat area = _pi * radius * radius;
   Console.WriteLine(“Area of the circle is ” + area);
  }
 }

 In the code snippet above, the compile time constant "_pi" is declared with the const keyword and the runtime constant "o" is declared with readonly keyword.

 The final keyword is used in Java to declare constants. Final variables can be set either at compile time or run time. In Java, when the final is used on a primitive it makes the value of the primitive immutable while when used on object references it makes the reference constant meaning that the reference can only point to only one object during its lifetime. Final members can be left uninitialized when declared but then must be defined in the constructor.

            Java Code

            import java.util.*;
            public class ClashApp
            {
               
                final int app1 = 1;  //compile time constants

                public static final int l1 = 5; //run time constants
             
                /* object reference as constant */
                final
Constn v = new Constn();
        
            }
            In the code snippet above, the final keyword is used to declare both compile time constant as seen in the case of the app1 variable and runtime constant as in the case of the l1 variable.
         
 Unlike C++, it is not possible to specify an immutable class via language constructs in either C# or Java. Neither is it possible to create a reference through which it's impossible to modify a mutable object. Java also supports having final parameters to a method. Which is used to allow arguments to a method to be accessible from within inner classes declared in the method body.

 *********STRING LITERALS
  There are two types of string literals in C#, regular and verbatim. A regular string literal is a standard string. A verbatim string literal is similar to a regular string literal but is prefied by the ‘@’ character. A string literal is always enclosed in double quotes.

 using System;
 class VerbatimTest
 {

     public static void Main()
     {
      string AppName  = @"ClashApp";
      Console.WriteLine("name: " + name);
      string Companyname =  "CodePlay";
      Console.WriteLine("Companyname:" + Companyname);
     }

 }
 In the code snippet above, a verbatim string AppName is declared to store the name of the app.

**********NAMED PARAMETERS/OPTIONAL PARAMETERS
 C# provides named parameters which Enable the user to associate a method argument with a name rather than its position in the argument list. while optional parameters allows the user to define a method with an optional argument with a default value. The caller of the method may or may not pass the optional argument value during the method invocation.

 named parameters
 class ClashApp
 {
   void Count(int boys, int girls)
   {
    Console.WriteLine(boys + girls);
   }
   static void Main(string[] args)
   {
    TestProgram objTest = new TestProgram();
    objTest.Count(boys: 16, girls: 24);
   }
 }

 In the code snippet above, the argument for the parameters boys and girls were passed through their names respectively.

 Optional parameters
 class CodePlay
  {
   void AppName(String name=”Not Available”)
  {
    Console.WriteLine(“{0}”, name);
  }
   static void Main(string[] args)
   {
    CodePlay objCp = new CodePlay();
    objCp.AppName("ClashApp");
    objCp.AppName();
   }
 }

 The optional argument "Not Available" would be displayed if the user has not passed the "ClashApp" to the AppName method.

 ***********REF/OUT KEYWORDS
 Ref
 C# provides the ref keyword which causes arguments to be passed in a method by reference. In call by reference, the called method changes the value of the parameters passed to it from the calling method. Any changes made to the parameters in the called method will be reflected in the parameters passed from the calling method when control passes back to the calling method. It is necessary that both the called method and the calling method must explicitly specify the ref keyword before the required parameters. The variables passed by reference from the calling method must be first initialized.

 public class ClashApp
 {
  public int compute(ref int numValueOne, ref int numValueTwo)
  {
   numValueOne = numValueOne * 5;
   numValueTwo = numValueTwo / 5;
  static void Main(string[] args)
  {
  int numOne = 10;
  int numTwo = 20;
  compute(ref numOne, ref numTwo);
  Console.WriteLine(numOne + numTwo);
  }
 }

 In the snippet above, the arguments numOne and numTwo are both passed using the ref keyword.

Out
 The out keyword is similar to the ref keyword and causes arguments to be passed by reference. The only difference between the two is that the out keyword does not require the variables that are passed by reference to be initialized. Both the called method and the calling method must explicitly use the out keyword.

 Out Keyword
 class ClashApp
 {
  static void compare(out int value)
  {
   value = 2;
   int numOne = val * 5/100;
   Console.WriteLine(numOne);
  }
  static void Main(string[] args)
  {
   int value;
   compare(out value);
  }
 }

  In the snippet above, the arguments value is passed using the out keyword which does not require initialization.

Comments

  1. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information.http://www.BESTDOTNETTRAININGINCHENNAI.COM

    ReplyDelete

Post a Comment

Popular posts from this blog

Firebase Test Lab for Android Robo Test

C# and Java Language History and Evolution

Local Jobs and Info for Information Technology Careers