(FRONT) FRONT (2016)

Java Datatypes

1. Basic Java types

Primitive Types: These are the fundamental building blocks of data. They are not objects and are stored directly as values.

Reference Types: Everything else in Java is an object.


2. Compare with C#

3. Automatic Implicit Conversions in C#

C# automatically performs implicit conversions when the compiler can guarantee that the conversion will not result in data loss or an exception. These conversions are considered safe and do not require explicit casting.

Here are some common scenarios where C# implements automatic implicit conversions:


  1. Widening Conversions:
    • Converting a smaller data type to a larger data type (e.g., int to long, float to double).
    • This is safe because the larger type can accommodate the full range of values of the smaller type.
  2. Numeric Type Conversions:
    • Converting between certain numeric types where the conversion is considered safe (e.g., int to double, short to int).
    • This is typically allowed when the target type has a larger range or higher precision than the source type.
  3. Reference Type Conversions:
    • Converting from a derived class to a base class.
    • This is safe because a derived class inherits all the members of its base class.
  4. Nullable Type Conversions:
    • Converting a non-nullable value type to a nullable version of the same type (e.g., int to int?).
    • This is safe because the nullable type can represent the full range of values of the non-nullable type, plus the null value.
  5. User-Defined Implicit Conversions:
    • You can define custom implicit conversion operators for your own types to control how they are implicitly converted to other types.
    • This allows you to create seamless conversions between your types without requiring explicit casting.

In this example, myInt is implicitly converted to a long without requiring an explicit cast. This is safe because a long can store the full range of values of an int.


   1:  int myInt = 10;
   2:  long myLong = myInt; // Implicit conversion from int to long

4. Automatic Implicit Conversions in Java

Similar to C#, Java also performs implicit conversions, also known as widening conversions


   1:  int myInt = 10;
   2:  long myLong = myInt; // Implicit conversion from int to long
   3:   
   4:  byte myByte = 5;
   5:  int myInt2 = myByte; // Implicit conversion from byte to int
   6:   
   7:  char myChar = 'A';
   8:  int myInt3 = myChar; // Implicit conversion from char to int
   9:   
  10:  Dog myDog = new Dog();
  11:  Animal myAnimal = myDog; // Implicit conversion (upcasting) from Dog to Animal

Important Considerations about automatic conversion:





Java context:



Comments ( )
Link to this page: http://www.vb-net.com/Java/Index02.htm
< THANKS ME>