CSC/ECE 517 Fall 2011/ch3 3h ss: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(18 intermediate revisions by 2 users not shown)
Line 1: Line 1:
'''Primitive objects in object-oriented languages'''
== Introduction ==  
== Introduction ==  


Line 23: Line 25:
=== Java ===
=== Java ===


In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double
In [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java], there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. <ref>http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types</ref>


For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.
For each of these primitive types, Java provides [http://en.wikipedia.org/wiki/Primitive_wrapper_class wrapper classes] to create primitive objects which wrap the primitive data values. A wrapper  not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion.
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].  
The primitive objects are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack heap] in memory while the variables containing primitive values are stored on [http://www.maxi-pedia.com/what+is+heap+and+stack stack].<ref>http://www.informit.com/articles/article.aspx?p=31755&seqNum=8 Stack and Heap memory</ref>


{| class="wikitable"
{| class="wikitable"
Line 73: Line 75:




In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.
In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.<ref>http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java</ref>


Example:  
Example:  
Line 89: Line 91:
=== C# ===
=== C# ===


[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types. [http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm See [1]]
[http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29 C#] is a [http://en.wikipedia.org/wiki/Strong_typing strongly typed] language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.<ref>http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes</ref><ref>http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#</ref>


Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:
Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:
Line 120: Line 122:
=== JavaScript ===
=== JavaScript ===


There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined.
There are 5 primitive data types in [http://en.wikipedia.org/wiki/JavaScript JavaScript]: string, number, boolean, null and undefined. <ref>http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables</ref>


For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values.  
For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values.  
Line 147: Line 149:
=== Ruby ===
=== Ruby ===


Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.  
Since [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] is a [http://www.jvoegele.com/software/langcomp.html pure object oriented] language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.<ref>http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby</ref>
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].
All integers are primitive objects of either class [http://corelib.rubyonrails.org/classes/Fixnum.html Fixnum] or [http://corelib.rubyonrails.org/classes/Bignum.html Bignum]. A numeric literal with a decimal point and/or an exponent is a primitive object of [http://corelib.rubyonrails.org/classes/Float.html Float]. Single quoted literals and double quoted literals are primitive objects of [http://corelib.rubyonrails.org/classes/String.html String].


Line 179: Line 181:
== Advantages of primitives ==
== Advantages of primitives ==


There are several advantages of treating primitives differently from class objects. Here are some:
There are several advantages of treating primitives differently from class objects. <ref>http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives</ref>


*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.
*Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.
Line 192: Line 194:
== Conclusion ==
== Conclusion ==


Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler.
Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler. Dealing with primitive objects is easier at times. In brief, the primitive objects help to increase the productivity of the programmers.


== References ==
== References ==
 
<references/>
1. [http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types]<br/>
2. [http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables]<br/>
3. [http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes]<br/>
4. [http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby]<br/>
5. [http://msdn.microsoft.com/en-us/library/ms228360%28v=vs.80%29.aspx Data Types (C# vs. Java)]<br/>
6. [http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives]<br/>
7. [http://www.informit.com/articles/article.aspx?p=31755&seqNum=8 Stack and Heap memory]<br/>
8. [http://www.cs.unc.edu/~dewan/comp114/f05/notes/12Pointers.doc Primitives Vs. Objects]<br/>
9. [http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java]

Latest revision as of 16:37, 15 October 2011

Primitive objects in object-oriented languages

Introduction

In any programming language, the data type refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.

The primitive data types refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably. But not all data types are primitive. Programming languages have some non-primitive data types or derived data types which are provided by the language by making use of its primitive data types.

The common built-in data types or primitive data types are integers, floating point numbers, characters, strings and boolean.

  • Integers - Integers represent the whole numbers which can be positive or negative or zero, e.g. 9999, 0, -25, etc.
  • Floating point numbers - Floating point numbers represent the numbers which are fractions or contain floating-decimal points, e.g. -3.002, 2.5, 22.0, etc.
  • Characters - Characters represent any single letter, number, space, punctuation mark, or symbol that can be typed on a computer, e.g. 'a', '9', ' ', '!' , '\n', etc.
  • Strings - Strings represent the sequences of characters or simply any text, e.g. "Hello!", "9 am to 6 pm", etc.
  • Booleans - Booleans represent the true or false values. Sometimes, instead of true and false, 1 and 0 are used to represent the boolean values.

Many object-oriented programming languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types.

Definition

Primitive objects refer to the objects of built-in classes which provide more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects (i.e., in such languages all primitive types are objects).

Different object-oriented programming languages implement these primitive data types and primitive objects in a different manner.

Primitive objects in different OO languages

Java

In Java, there are 8 primitive types: boolean, char, byte, short, int, long, float, and double. <ref>http://www.cafeaulait.org/course/week2/02.html Java's Primitive Data Types</ref>

For each of these primitive types, Java provides wrapper classes to create primitive objects which wrap the primitive data values. A wrapper not only contains the primitive data value, but it also defines properties and methods that can be used to manipulate that data. In Java, the primitive values are not implicitly converted to primitive objects. Instead, methods are provided for doing explicit conversion. The primitive objects are stored on heap in memory while the variables containing primitive values are stored on stack.<ref>http://www.informit.com/articles/article.aspx?p=31755&seqNum=8 Stack and Heap memory</ref>

Primitive Type Wrapper Class Size
boolean Boolean 1-bit
char Character 16-bit
byte Byte 8-bit
short Short 16-bit
int Integer 32-bit
long Long 64-bit
float Float 32-bit
double Double 64-bit

Example:

   int i = 10;
   int ii = 20;
   Integer I = new Integer(i);
   Integer II = new Integer(ii);
   System.out.println(I+II);            
   System.out.println(I.equals(II));    

Output:

   30
   false


To find out if these wrapper classes are primitive or not, we can use the isPrimitive() method.

   System.out.println(INTEGER.TYPE.isPrimitive());
   System.out.println(BOOLEAN.TYPE.isPrimitive());

Output:

   true
   true


In Java, the comparison operations work in the same way on the primitive objects as well as any other class objects but different on the primitive types. The == operator when used on objects checks whether they refer to the same object but when used on variables of primitive types checks whether they contain the same value.<ref>http://leepoint.net/notes-java/data/expressions/22compareobjects.html Comparisons in Java</ref>

Example:

   int i = 10;
   int ii = 10;
   Integer I = new Integer(i);
   Integer II = new Integer(ii);
   System.out.println(I==II);            
   System.out.println(i==ii);

Output:

   false
   true

C#

C# is a strongly typed language, where it is necessary to declare the data type of a variable and also be aware of the data type conversion. C# provides a significant number of primitive data types.<ref>http://condor.depaul.edu/sjost/ndp/notes/cs1/CSDatatypes.htm C# Primitive Datatypes</ref><ref>http://www.java2s.com/Tutorial/CSharp/0040__Data-Type/PrimitivesinC.htm Primitives in C#</ref>

Because C# represents all primitive data types as objects, it is possible to call an object method on a primitive data type. For example:

   static void Main()
   {
       int x = 7;
       object o = x;
       System.Console.WriteLine(o.ToString());
   }

Some data types (e.g. Decimal and String) can appear like primitives at first sight, but are actually not. So it is important to exercise caution before making such assumptions. To test whether a particular type is a primitive or not you can use the property Type.IsPrimitive.

Consider the following example:

   if (t.IsPrimitive)    // where t is the type
   {
       // Is Primitive
   } else if (t == typeof(Decimal))
   {
       // Is Decimal
   } else if (t == typeof(String))
   {
       // Is String
   } else
   {
       // Other type
   }

JavaScript

There are 5 primitive data types in JavaScript: string, number, boolean, null and undefined. <ref>http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html JavaScript Data Types and Variables</ref>

For string, number and boolean values, there are corresponding classes just like in Java to create primitive objects which wrap the primitive values.

Primitive Type Wrapper Class
string String
number Number
boolean Boolean

In JavaScript, the primitive value is implicitly converted to a primitive object whenever someone tries to access a property or invoke a method on the primitive value and the primitive object is used in place of the primitive value. Since the object contains properties and methods, the use of primitive value as an object succeeds. After the property is accessed or the method is processed, the primitive object is no longer needed and hence discarded. The same is true for the other primitive types and their corresponding primitive objects.

Example:

   var upperCaseString = "APPLE";
   var lowerCaseString = upperCaseString.toLowerCase();  // assigns string "apple" to lowerCaseString 
   var s = "Hello"
   var len = s.length;                                   // assigns value 5 to len

Ruby

Since Ruby is a pure object oriented language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class.<ref>http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Classes in Ruby</ref> All integers are primitive objects of either class Fixnum or Bignum. A numeric literal with a decimal point and/or an exponent is a primitive object of Float. Single quoted literals and double quoted literals are primitive objects of String.

Example:

   puts 10.class
   puts 7.45.class
   puts 'hi'.class
   puts "hello".class

Output:

   Fixnum
   Float
   String
   String

This indicates that 10 is converted into an object of type Fixnum, 7.45 is converted into an object of type Float, 'hi' and "hello" are both converted into an object of type String.

Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstrate the same for integer and float using the following example:

   a=10
   puts a.to_f  
   b=20.5
   puts b.to_i

Output:

   10.0
   20

Advantages of primitives

There are several advantages of treating primitives differently from class objects. <ref>http://www.research.ibm.com/people/a/alpert/ptch/ptch.html Pros and cons of primitives</ref>

  • Accessing an object may require a lot of memory look-ups, depending on the implementation of the language. Accessing the values of primitive variables is faster that accessing data in objects since primitives require fewer memory fetches.
  • It improves performance and verification. Primitive types such as integers, boolean, floats are the frequently used features of an object oriented programming language like. So, we want operations involving variables of these types—operations that are at the heart of our computing model—to run fast.
  • It provides several methods and instance variables to the primitive types in some languages, which simplifies the code.

Disadvantages of primitives

  • The primitive types limit the range of values a variable can take. e.g. In Java, a variable of type int or an object of Integer can have only one of the 2^32 values i.e. from -(2^16) to (2^16)-1.
  • The primitive type values cannot be passed to a method which expects the objects. Also they cannot be passed by references.
  • Primitives types cannot be extended.

Conclusion

Having primitive data types as primitive objects enhances the object oriented functionality of a language and takes it closer to being pure. The closer the language is to being a pure object oriented language, the more powerful it is. It also bridges the gap between novice programmers and experienced programmers by making powerful features basic to the language and makes coding simpler. Dealing with primitive objects is easier at times. In brief, the primitive objects help to increase the productivity of the programmers.

References

<references/>