Character literals – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Code Learning #JAVA#3808    siteicon   siteicon  

Character literals

Use of character literals as direct character assignment, unicode assignment or octal assignment.

Learning Objectives

  • Character literal assignment forms, single quote form, integer form.

Source Code

TC++ #3808

Source Code

Run Output

A
A
A
65
65
65
A
A
A
A

Code Understanding

//single quote form to char type assignment
char cx=’A’;
Here ‘A’ is a character literal which is marked by its containment in single quotes. More than one character will become a string literal so for being a character literal only 1 character is allowed

char cy=’u0041′;
This is character literal of 16 bit unicode form. In this case u precedes the 16 bit hex code of character code u0041 is for capital A only.

char cz=’101′;
This is a character literal in Octal form. In this case just a single precedes the octal value of character as per ascii or unicode. 101 is octal for capital A.

//single quote form to int type assignment
int ix=’A’;
int iy=’u0041′;
int iz=’101′;
All above assignment as same as done before, but they have storage type marked as int. In both cases the actual storage is same, but at the time of printing the default storage space type is considered.

//int form to char type assignment
char ca=65;
char cb=0x41;
char cc=0101;
char cd=0b01000001;
Here we are storing the integer form representation of A as 65 in decimal, 0x41 in hexadecimal, 0101 in octal, 0b01000001 in binary.

System.out.println(cx); System.out.println(cy); System.out.println(cz);
Here we print as A as storage defined was char.

System.out.println(ix); System.out.println(iy); System.out.println(iz);
Here we print 65 as storage defined was int.

System.out.println(ca); System.out.println(cb); System.out.println(cc); System.out.println(cd);
Here we print A again as storage defined is again char although integer literals were assigned.

Notes

  • The storage content for char and int both types is actually binary only. The char storage is however only the positive values while the integer forms can be both positive and negative values.For this reason char type should not be typecasted to short or byte type as precision loss may occur. For e.g.
    char x=’A’;
    int a=x;  //is OK
    short a=x; //is not OK
    byte a=x; //is not OK
    short a=(short) x; //is allowed but not recommended
    byte a=(byte) x; //is allowed but not recommended
  • One can read the standard document at the following link
    https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html


Suggested Filename(s): CharLiterals.java



Share

sunmitra| Created: 11-Mar-2018 | Updated: 11-Mar-2018|






Back