Discussion Forum Unit 7 4 PDF

Title Discussion Forum Unit 7 4
Course Programming 1
Institution University of the People
Pages 1
File Size 46.1 KB
File Type PDF
Total Downloads 44
Total Views 151

Summary

Regards Discussion Forum or Discussion Assignment Unit 7 4 in CS 1102 or Programming 1....


Description

Discussion Forum Unit 7 In Java we have objects and primitive types that can be used for creating variables. Primitive types are represented by int, char, boolean, etc. These types are powerful tools, but sometimes, it is better to use objects instead of primitive types because objects can solve many problems much more straightforward and reduce the size of code. However, primitive types cannot be used with objects because the objects need to have parameterized types. Unfortunately, primitive types do not work with parameterized types (Eck, 2019). Therefore, for example, we can’t use the following declaration: ArrayList arrayChar = new ArrayList(); To solve this problem we can use the Wrapper classes. “They are used for representing primitive type values as objects” (Eck, 2019, p. 351). In other words, if we want to use the “char” type together with ArrayList, we can take the wrapper class of “char” that is called “Character”. There is the wrapper class for each primitive type. As you may know, Java is a strongly typed programming language and we must define a variable type each time. So, we must convert objects into primitive types and vice versa. Fortunately, Java gives us two more useful tools. They are named Autoboxing and Unboxing. According to Eck, "In fact, autoboxing and unboxing make it possible in many circumstances to ignore the difference between primitive types and objects" (Eck, 2019, p. 352 An example of autoboxing ArrayList characters = new ArrayList(); char someChar = 'a'; characters.add(someChar); As you can see, we shouldn't use manual conversion of the “someChar” variable to add to the “characters” ArrayList. The Java compiler will do it automatically with the help of autoboxing. An example of unboxing ArrayList characters = new ArrayList(); characters.add('a'); char someChar = characters.get(0);

Here you can see an example of unboxing. A variable with an index [0] from the “characters” ArrayList is an object and has the “Character” class. When we try to assign the object to the primitive type we won’t get any errors because the Java compiler does unboxing and automatically converts the object to the primitive type. Reference Eck, D. J. (2019). Introduction to programming using Java, version 8.1. http://math.hws.edu/javanotes...


Similar Free PDFs