Casting, Converting & Comparing Object (CCCO)


CCCO:   SOLD       




In this section, we will learn how to use typecasting. Typecasting or casting is the process of converting data from a certain data type to another data type. We will also learn how to convert primitive data types to objects and vice versa. Then, finally we will learn how to compare an object.


Getting to Know Casting, Converting and Comparing Objects

1. Primitive Type Casting

Casting between primitive types allows you to convert a value from one data type to another primitive type. This usually happens between numeric data types.

There is a primitive data type that we still cannot cast, and that is the boolean data type.

An example of typecasting is when you store an integer to a variable with the data type double. For example:

int numInt = 10;
double numDouble = numInt; //implicit cast

In this example we can see that, even though the target variable (double) has a value greater than the value we will place in it, we can implicitly cast the data to the double data type.

Another example is if we want to typecast an int to a char or vice versa. A character can be used as an int because each character has a numeric value that represents its position in a character set. If a variable has a value of 65, then the cast (char) i will produce the value 'A'. The numeric code that represents a capital A is 65, based on the ASCII character set, and Java has adopted this part to support characters.

char valChar = 'A';
int valInt = valChar;
System.out.print( valInt ); //casting explisit: keluaran 65

When we convert large data types to smaller data types, we must use explicit casts. Explicit casts follow the following form:

(dataType)value

Where,

  • dataType, is the name of the data type you are converting
  • value, is a statement that is generated on the value of the source type.

As an example;

double valDouble = 10.12;
int valInt = (int)valDouble; //men-convert valDouble ke tipe int
double x = 10.2;
int y = 2;
int result = (int)(x/y); //hasil typecast operasi ke int

2. Casting Objects

Instances of classes can also be selected to instances of other classes, with one restriction: the source and destination classes must be connected by an inheritance mechanism; one class must be a subclass of the other. We will explain inheritance in more detail later.

In line with the selection of primitive values ​​for larger types, some objects may not need to be selected explicitly. In fact, because all subclasses contain the same information, you can use an instance of a subclass wherever a superclass is expected.

For example, consider a method that takes two arguments, one of type object and another of type window. You can pass instances of several classes for the object argument because all Java classes are subclasses of object. For the window argument, you can pass any of its subclasses, such as dialog, FileDialog, and frame. This is true anywhere in the program, not just in calling the method. If you have a variable defined as class window, you can pass an object of that class or any of its subclasses to the variable without selection.


Figure 2 Example of Class Hierarchy

This is true in the reverse case, and you can use the superclass when a subclass is created. There is a catch in this case, however: Because the subclass contains more possible actions than the superclass, there is a loss of balance in involvement. The superclass object may not have all the possible actions necessary for the action at the subclass object's location. For example, if you have an operation that calls methods on an object of class Integer, using an object of class Number will not contain the many methods specified in Integer. An error occurs if you try to call a method that does not have a target object.

To use superclass objects where subclass objects are expected, you must explicitly select them. You do not lose any information in selecting, but you gain the benefits of all the methods and variables that define the subclass. To select an object to another class, you use the same operations as for primitive types:

To select,

(classname)object

Where,

  • classname, is the name of the target class.
  • object, is something that points to the source object.

Note: this selection creates a reference to the old object of type classname; the old object continues to act as it did before.


Figure 3 Class Hierarchy for the Employee superclass

The following example selects an instance of the VicePresident class to an instance of the Employee class; VicePresident is an Employee with more information, which defines that VicePresident has executive washroom privileges,

Employee emp = new Employee();
VicePresident veep = new VicePresident();
emp = veep; // tidak adah pemilihan yang diperlukan untuk penggunaan yang cenderung naik
veep = (VicePresident)emp; // Harus memilih dengan pemilihan secara eksplisit

3. Convert Primitive Types to Objects and Vice Versa

One thing you can't do in some cases is choose from an object to a primitive data type, or vice versa. Primitive types and objects are very different things in Java, and you can't directly choose between the two or swap them.

As an alternative, the java.lang package contains classes corresponding to each primitive data type: Float, Boolean, Byte, and so on. Most of these classes have the same name as their data type, except that the class name begins with a capital letter (Short -> sort, Double -> double and so on). Also two classes have different names from their corresponding data types: Character is used for char variables and Integer for int variables. (Called Wrapper Classes) Java represents data types and class versions very differently, and a program will not compile if you use only one when the other is also needed.

Using appropriate classes for each primitive type, you can create an object that has the same value.

Example:

//Pernyataan berikut membentuk sebuah instance bertype Integer
// class dengan nilai integer 7801 (primitive -> Object)
Integer dataCount = new Integer(7801);

//Pernyataan berikut meng-converts sebuah object Integer ke
//tipe data primitive int nya. Hasilnya adalah sebuah int //dengan nilai 7801
int newCount = dataCount.intValue();

// Anda perlu suatu translasi biasa pada program
// yang meng-convert sebuah String ke sebuah tipe numeric, //seperti suatu int
// Object->primitive
String pennsylvania = "65000";
int penn = Integer.parseInt(pennsylvania);

NOTE: The Void class does not represent anything in Java, so there is no reason to use it when translating between primitive values ​​and objects. This is an explanation of the void keyword, which is used in method definitions to indicate that the method does not have a return value.

4. Comparing Objects

In our previous discussion, we learned about operators for comparing values ​​---equal, not equal, less than, and so on. These operators mostly work only on primitive types, not on objects. If you try to use other values ​​as operands, the Java Compiler will throw an error.

The exceptions to this rule are the equality operators: == (equal) and != (not). When applied to objects, these operators don't do what you actually want. Instead of checking if one object has the same value as another, they recognize that both sides of the operator refer to the same object.

To compare instances of a class and have meaningful results, you must implement special methods in your class and call those methods. A good example of this is the String class.

It is possible to have two String objects that have the same value. If you use the == operator to compare these objects, however, we will consider the values ​​​​to be unequal. Even though their contents match, they are not the same object.

To see if two String objects have the same value, a method of the class called equals() is used. The method tests each character in the string and returns true if the two strings have the same value.

The following code illustrates this,

class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
str2 = new String(str1);
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
System.out.println("Same value? " + str1.equals(str2));
}
}

output,

String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
Same value? True

Now let's discuss about the code

String str1, str2;
str1 = "Free the bound periodicals.";


Figure 4 Both point to the same object

The first part of this program declares two variables (str1 and str2), assigns the literal "Free the bound periodicals." to str1, and then assigns that value to str2. As you learned earlier, str1 and str2 now point to the same object, and the equality test proves this.

str2 = new String(str1);

In the second part of the program, you create a new String object with the same value as str1 and assign str2 to the new String object. You now have two different String objects, str1 and str2, both of which have the same value. Test them to see if they are the same object by using the == operator, which returns the desired value: false---they are not the same object in memory. Test them using the equals() method, which also returns the desired answer: true---they have the same value.


Figure 5 Now moving on to a different object

Note: Why can't you just use another literal when you modify str2, instead of using new? String literals are reliable in Java; if you create a string using a literal and then use another literal with the same characters, Java knows enough to give you the first String object back. Both Strings are the same object; you should avoid creating two separate objects.

5. Determining the Class of an Object

Want to find out what class an object is? Here are the steps to do it for an object given as a variable key:

1. getClass() method

Returns a Class object (where Class itself is a class) that has a method called getName(). In turn, getName() returns a string representing the name of the class.

As an example,

String name = key.getClass().getName();

2. InstanceOf operator

instanceOf has two operands: a reference to an object on the left and a class name on the right. The statement returns true or false depending on whether the object is an instance of the named class or some subclass of that class.

As an example,

boolean ex1 = "Texas" instanceof String; // true
Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false

Hope this is useful & happy learning!


Post a Comment

Previous Next

نموذج الاتصال