Thursday, June 23, 2016

Type Casting Java

Type Casting

Converting one data type into another data type is called "Type Casting".

Type of Data Types

There are two types of data types,as given here:

  1. Primitive Data Types
  2. Referenced Data Types or Advances Data Types
Primitive Data Types or Fundamental Data Types:

The data types which represent a single entity(or value) are called Primitive Data Type.
For example,int type ,it can store only one integer value.

The following are the primitive data types:

char,byte,short,int,long,float,double,boolean .

Referenced Data Types or Advanced Data Types

These data types represent several values.For example Array,it can store several values.Similarly,take a class.It can store different values.So they are called Advanced data types.

The following are referenced data types:

any array, any class(String ,StringBuffer , Employee,Manager etc) .

What is difference between primitive data types and advanced data types?.
Ans:

Primitive data types represents single values.Advanced data types represent a group of values.Also,methods are not available to handle the primitive data types.In case of Advanced Data types ,methods are available to perform various operations.

Note:
  1. we can convert a primitive data type to another primitive data type using casting.
  2. we can not convert a primitive data type into a referenced data type by using casting.
Casting Primitive Data Types
It is possible to convert one primitive data type into another primitive data type.This is done in two ways, widening and narrowing . The primitive  data types are classified into two types,lower types ways and higher types. 

byte---->short----->char---->int---->long---->float---->double
lower-------------------------------------------------------->higher

Widening in Primitive Data Types

Converting a lower data type into a higher data type is called widening.
char ch='A';
int num=(int)ch;

Widening is safe because there will not be any loss of data or precision or accuracy hence this is also called implicit casting.This type of casting done by JAVA COMPILER automatically.

Narrowing in Primitive Data Type

Converting higher data type to lower data type is called Narrowing.

int n=66;
char c=(char)n;

This type of casting is called Explicit Casting and also it is compulsory while converting from higher data type to lower data type.


Casting Referenced Data Types

A class is referenced data type. converting a class type into another class type is also possible through casting.But the classes should have relationship between them by the way of Inheritance.

Generalization and Specialization

Generalization is a process where a sub class is promoted to a super class and hence becomes more general.Generalization needs widening or up-casting.

Specialization is a process where a super class is narrowed down to a sub class . Specialization needs narrowing or down-casting.

Widening using referenced data type sample program:


/**
 * 
 */
package com.typecasting;

/**
 * @author Abhinaw.Tripathi
 *
 */

class One
{
 void show1()
 {
System.out.println("Super class method");
 }
}

class Two extends One
{
void show2()
{
System.out.println("Sub class method");
}
}

public class CastApp 
{

/**
* @param args
*/
public static void main(String[] args) 
{
One o=(One)new Two();
o.show1();
}

}

Result: 

Super class method



Another Program:


/**
 * 
 */
package com.typecasting;

/**
 * @author Abhinaw.Tripathi
 *
 */

class One
{
 void show1()
 {
System.out.println("Super class method");
 }
}

class Two extends One
{
void show1()
{
System.out.println("Sub class method");
}
}

public class CastApp 
{

/**
* @param args
*/
public static void main(String[] args) 
{
One o=(One)new Two();
o.show1();
}

}

Result:

Sub class method


Narrowing in Referenced Data Types sample Program:


/**
 * 
 */
package com.typecasting;

/**
 * @author Abhinaw.Tripathi
 *
 */

class One
{
 void show1()
 {
System.out.println("Super class method");
 }
}

class Two extends One
{
void show2()
{
System.out.println("Sub class method");
}
}

public class CastApp 
{

/**
* @param args
*/
public static void main(String[] args) 
{
Two t=(Two)new One();
t.show1();
}

}


Result:


Exception in thread "main" java.lang.ClassCastException: com.typecasting.One cannot be cast to com.typecasting.Two
at com.typecasting.CastApp.main(CastApp.java:35)



Another Program:


/**
 * 
 */
package com.typecasting;

/**
 * @author Abhinaw.Tripathi
 *
 */

class One
{
 void show1()
 {
System.out.println("Super class method");
 }
}

class Two extends One
{
void show2()
{
System.out.println("Sub class method");
}
}

public class CastApp 
{

/**
* @param args
*/
public static void main(String[] args) 
{
One o=(One)new Two();
o.show1();
Two t=(Two)o;
t.show2();
}

}

Result:

Super class method
Sub class method

Which is the super class for all the classes including your classes also?

Ans: Object Class because object class reference can store any reference of any object.This becomes advantage when we want to write a method that needs to handle objects of unknown type.

The methods of Object class are given below:
  • equals() - this methods compare's the reference of two objects.
  • toString() - this methods return a string representation of an object.
  • getClass() - This method gives an object that contains the same name of a class to which an object belongs.
  • hashCode() - This method returns hash code number of an object.
  • notify() - This method sends a notification to a thread which is waiting for an object.
  • notifyAll() - This method sends a notification for all waiting thread for the object.
  • wait() - This method causes a thread to wait till a notification is received from a notify() or notifyAll() methods.
  • clone() - This method creates a bit wise exact copy of an existing object.
  • finalize() - This method is called by the garbage collector when an object is removed from memory.
Cloning the class objects

The process of creating an exact copy of an object is called Cloning .When we clone the object a bit wise copy of the object will result. The original and cloned object will be same bit by bit.

There are two types of cloning.

  1. Shallow Cloning- When the cloned object is modified,original object will also affect or same modification will also affect.                                                                                                             
  2. Deep Cloning- When the cloned object is modified ,if the original object is not changed  the it is called Deep Cloning.

Sample Program:

/**
 * 
 */
package com.typecasting;

/**
 * @author Abhinaw.Tripathi
 *
 */

class Employee implements Cloneable
{
int id;
String name;
public Employee(int id,String name) 
{
this.id=id;
this.name=name;
}
void getData()
{
System.out.println("Id : "+id);
System.out.println("Name :" +name);
}
public Object myClone() throws CloneNotSupportedException
{
return super.clone();
}
}

public class CloneDemo 
{
public static void main(String[] args) throws CloneNotSupportedException
{
       Employee e1=new Employee(10, "Abhinaw");
       System.out.println("Original Object:");
       
       e1.getData();
       
       Employee e2=(Employee)e1.myClone();
       System.out.println("Cloned Object: ");
       e2.getData();
}
}

Result:

Original Object:
Id : 10
Name :Abhinaw
Cloned Object: 
Id : 10
Name :Abhinaw


Can you write an interface without any methods?
Ans: Yes

What do you call the interface without any members?

Ans: An interface without any members is called marking interface or tagging interface. it marks the class objects for a special purpose. For example - Cloneable and Serializable are two marking interfaces. Cloneable interface indicates that a particular class objects are cloneable while serializable interface indicates that a particular class objects are serializable.


No comments: