FaltuTech.Club : Fane of Advanced Logical Thriving Utopian Technical Club

Use of getClass() and getName() on Objects in Java

Use of getClass() and getName() on Objects in Java




class test{
	public static void main(String args[]){
	
	byte arrByte[] = {4,6,4,3,5,6,3};
	short arrShort[] = {4,5,5,6,7,8};	
	int arrInt[] = {4,6,3,6,2,6};
	float arrFloat[] = {4f,8f,0f,9f}; // you can use f or F or simply nothing
	double arrdouble[] = {8d,9d,99d,98d}; // you can use d or D or simply nothing
	long arrLong[] = {4L,6L,3L,6L,7L}; // you can use l or L or nothing 
	char arrChar[] = {'d','d','e','f'}; // you can also write {100,100,101,102} -> ASCII Values
	String arrString[] = {"d","d","e","f"};

	System.out.println("1. class of arrByte : " + arrByte.getClass());
	System.out.println("2. class of arrShort : " + arrShort.getClass());
	System.out.println("3. class of arrInt : " + arrInt.getClass());
	System.out.println("4. class of arrFloat : " + arrFloat.getClass());
	System.out.println("5. class of arrdouble : " + arrdouble.getClass());
	System.out.println("6. class of arrLong : " + arrLong.getClass());
	System.out.println("7. class of arrChar : " + arrChar.getClass());
	System.out.println("8. class of arrString: " + arrString.getClass());
	
	
	}

}


Output


1. class of arrByte : class [B
2. class of arrShort : class [S
3. class of arrInt : class [I
4. class of arrFloat : class [F
5. class of arrdouble : class [D
6. class of arrLong : class [J
7. class of arrChar : class [C
8. class of arrString: class [Ljava.lang.String;


Discussion

Now from above we can say that array is a class and we have created various objects of it and we can also find which type of data it contains.
But be carefull that you don’t use getClass() with primitive type because those are not classes and that’s why getClass() function is not applicable. If you try following :


int a = 5;
System.out.println(a.getClass());

Then You will get error :


error: int cannot be dereferenced