Cannot comprehend Output Of The Program - java

import java.util.Scanner;
public class asdf
{
public static void main(){
String temp = "165";
int ch = temp.charAt(0);
int ch1 = temp.charAt(1);
int ch2 = temp.charAt(2);
System.out.println(ch);
System.out.println(ch1);
System.out.println(ch2);
}
}
Output:
49
54
53
I cannot understand the output.Is it implicit cast according to which a character is converted to a number . Any help is appreciated.

It is printing the ASCII values of the digits. 1,6,5.
Note that the ASCII value of 0 is 48. So, 49 is ASCII value of character 1 and so on.
Have a look here: http://www.asciitable.com/
Try this to get the actual characters printed instead of the ASCII values:
char ch = temp.charAt(0);
char ch1 = temp.charAt(1);
char ch2 = temp.charAt(2);

char is a subset of int. It contains values from 0 to 2^16-1. Each value corresponds with a character.
When you assign a char to an int variable and print that variable, you'll see that int value that corresponds with the character.
'1' corresponds with 49
'6' corresponds with 54
'5' corresponds with 53

it gives the ASCII value, you can cast it as char to get the expected answer
System.out.println((char) ch);
System.out.println((char) ch1);
System.out.println((char) ch2);

Related

Decimal to Hex help understanding

import java.util.*;
public class Dec2Hex {
public static void main (String[] args){
Scanner input new Scanner (System.in);
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
char hexDigit = (0 <= hexValue && hexValue <= 9)?
(char)(hexValue + '0'): (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal/16;
}
System.out.println("The hex number is " + hex);
}
}
This is an example in my book. I understand most of it but can't quite grasp a few parts. The example uses 1234 as the decimal entered.
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is 2 + '0'. But hexDigit is a character so what is the meaning of combining or adding 2 and '0'?
The final answer is 4D2. Where in the code did we ever provide instruction for any letter other than 'A'? How did it come up with a 'D'?
Thank you!
I understand now that the second part of the condition is takin a number like "13", subtracting 10 and adding that to 'A'. 3 + 'A' is 'D' in unicode.
I still do not understand adding the '0' to the first part of the condition. Couldn't we just say (char)(hexValue)? Why add '0'?
Thanks!
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is 2 + '0'. But hexDigit is a character so what is the meaning of combining or adding 2 and '0'?
The value 2 is an integer value, however the variable type is char. No problem in assigning such a value to a char variable, however this would result in the 0x02 character/byte, which is a control character, not a visible character to display. The digits in the ASCII table to display begins at 0x30 (which is the digit '0'). To get the character value to save in the char variable you add your calculated value 2 with the offset 0x30. To make this calculation easier you use the expression '0'. This is the exact value of 0x30 (or 48 in decimal).
The final answer is 4D2. Where in the code did we ever provide instruction for any letter other than 'A'? How did it come up with a 'D'?
The calculation is as follow:
1234 divided by 16 is 77 with a remainder of 2.
77 divided by 16 is 4 with a remainder of 13 (which is D).
4 divided by 16 is 0 with a remainder of 4.
This results in 4D2. To verify:
4*16*16 + 13*16 + 2 = 1234
Every char has a value number between 0 to 256, each of these numbers encode a printable sign.
For example the value of '0' is 48, and the value of 'A' is 65.
So when adding a constant offset to a character it's like going to that offset in that encoding.
For example '0' + 5 is '5', or 'A' + 3 is 'D'.
So as for your questions:
'0' + 2 is '2', i.e. the printable character of 2.
In the code hexValue had the value of 13, so hexDigit got the value (hexValue - 10 + 'A'), which is (hexValue - 10 + 'A') = 13 - 10 + 'A' = 'A' + 3 = 'D'.
2 + '0' = 2 + 48 = 50
(char)50 = '2'
Note that
'0' = 48
'1' = 49
'2' = 50
...
'9' = 57
Check ASCII Table to learn more about ASCII values.
Demo:
public class Main {
public static void main(String[] args) {
System.out.println((char) 50);
}
}
Output:
2
Ascii table is used for char type, so characters can be represented by decimal values. For example:
'0' in decimal 48
'1' in decimal 49
'2' in decimal 50
...
'9' in decimal 57
'A' in decimal 65
'B' in decimal 66
'C' in decimal 67
'D' in decimal 68
...
'Z' in decimal 90
'a' in decimal 97
'b' in decimal 98
...
'z' in decimal 122
Having that in mind your here are the answers to your questions:
We focus on the line
char hexDigit = (0 <= hexValue && hexValue <= 9)?
(char)(hexValue + '0'): (char)(hexValue - 10 + 'A');
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is
2 + '0'. But hexDigit is a character so what is the meaning of
combining or adding 2 and '0'?
For this question the part of interest is
(char)(hexValue + '0')
The value hexValue is 2, so hexValue + '0' is 50, because in ascii table '0' has decimal value 48. Than value of 50 is casted to char, which by ascii table is '2'.
The final answer is 4D2. Where in the code did we ever provide
instruction for any letter other than 'A'? How did it come up with a
'D'?
For this question the part of interest is
(char)(hexValue - 10 + 'A')
The value hexValue is 13. By asci table 'A' has value of 65 and 'D' has value of 68. So hexValue - 10 is 3 and when we sum 3 and 'A' we get 68. Finally we do cast to char and get 'D'.
You can easyly test the answers by executing this piece of code:
public class Main {
public static void main(String[] args) {
System.out.println("Decimal value: "+(2+'0')+" Char value:" +(char)(2+'0'));
System.out.println("Decimal value: "+(3 + 'A')+" Char value: "+ (char)(3+'A'));
}
}
Regards

How to get ASCII representation of a character?

I have very basic question.
How is possible for int a = 'a' to give 97 in output.
Below is my code:
class myClass {
int last = 'a' ;
myClass () {
System.out.println(last );
}
}
You can have a look at this: Why are we allowed to assign char to a int in java?
Basically, you are assigning a char to your int. A char is technically an unsigned 16-bit character. That's why you can assign it to an int.
Hope this helps.
You can basically cast the char to the int and store it as int:
int a = (int)'a';
System.out.println(a); //prints 97
Since Java can do the basic castings from your type specifications, you do not need to explicity write casting even.
int a = 'a';
System.out.println(a); // prints 97
The output is the ASCII value of the character stored in last. The ASCII value of the character 'a' is 97, and hence the output on the console is 97.
you have to take 'a' as a char
char char1 = 'a';
then cast it to int
int num = (int) char1 ;

Finding location of char in the alphabet

If I have a char, for example:
char letter = 'g'
is there a way for me to find out where in the alphabet this letter is? (assuming it is in the alphabet)
So for clarification, the answer for letter would be 7, since g is the 7'th letter in the alphabet.
For starters, you can always get the ASCII int value for a character in Java by simply casting that character to an int as follows:
char letter = 'g';
int ascii = (int) letter; # ascii = 103
To get the 1-based position in the alphabet, you can offset this value keeping in mind that character a has a value of 97:
int getPosition(char input) {
char smalla = 'a';
int alphabetStart = (int) smalla; # alphabetStart = 97
int position = (int) input - alphabetStart + 1;
return position;
}
Keep in mind that I have only considered lowercase letters of the alphabet in my solution. Uppercase characters have ASCII values which run from 65 (A) to 90 (Z), and the solution to take those into account would be a bit more complex.
Use indexOf() to get position of character from abcdefg... string
Here is the simple solution.
public static int getCharPosition(char c)
{
String line = "abcdefghijklmnopqrstuvwxyz";
int position = line.indexOf(String.valueOf(c).toLowerCase())+1;
return position;
}
Input : z
Output : 26
As being said in the comments, the easiest way to find index of a char is:
c.toLowerCase() - 'a' + 1
In the ASCII table each letter has an ordinal number. You can get the ordinal number of a char by casting it to int.
The lower case letter a has an ordinal number of 97, so you have to substract it from your letter's ordinal number. Since the ASCII table starts at ordinal number 0, substract an additional 1.
Java code:
char letter = 'g';
int asciiNumber = (int)letter; // 103
final int offset = 97 - 1; // 97 is ASCII code for 'a', -1 since ASCII table starts at 0
int numberInAlphabet = asciiNumber - offset;
System.out.println("Position of letter '" + letter + "': " + numberInAlphabet);
To handle both lowercase and uppercase you can do something like this :
public int alphabetPosition(char c) {
int a='a';
int position=(String.valueOf(c).toLowerCase().codePointAt(0))-a+1;
return position;
}
public class SearchAlphabet {
public static void main(String args[])
{
char letter='d';
int ascii=97; //ascii value of a
int counter=1;
for(int a=0;a<=27;a++)
{
if(ascii==(int)letter)
{
System.out.println("Position");
System.out.println(counter);
break;
}
ascii++;
counter++;
}
}
}
Here,we start counter from 1 and incremented by 1 on every iteration after matching the given character ascii.And after matching the with concern character, we print the counter value.

Why does this lead to an ArrayIndexOutOfBoundsException?

There is something that doesn't quite make sense to me. Why does this:
public static int[] countNumbers(String n){
int[] counts = new int[10];
for (int i = 0; i < n.length(); i++){
if (Character.isDigit(n.charAt(i)))
counts[n.charAt(i)]++;
}
return counts;
}
bring up an ArrayOutOfBounds error while this:
public static int[] countNumbers(String n){
int[] counts = new int[10];
for (int i = 0; i < n.length(); i++){
if (Character.isDigit(n.charAt(i)))
counts[n.charAt(i) - '0']++;
}
return counts;
}
does not? The only difference between the two examples is that the index for counts is being subtracted by zero in the second example. If I'm not mistake, shouldn't the first example display correctly since the same value is being checked?
Here are the value being passed for the two methods:
System.out.print("Enter a string: ");
String phone = input.nextLine();
//Array that invokes the count letter method
int[] letters = countLetters(phone.toLowerCase());
//Array that invokes the count number method
int[] numbers = countNumbers(phone);
This is the problem:
counts[n.charAt(i)]++;
n.charAt(i) is a character, which will be converted to an integer. So '0' is actually 48, for example... but your array only has 10 elements.
Note that the working version isn't subtracting 0 - it's subtracting '0', or 48 when converted to an int.
So basically:
Character UTF-16 code unit UTF-16 code unit - '0'
'0' 48 0
'1' 49 1
'2' 50 2
'3' 51 3
'4' 52 4
'5' 53 5
'6' 54 6
'7' 55 7
'8' 56 8
'9' 67 9
The code is still broken for non-ASCII digits though. As it can only handle ASCII digits, it would be better to make that explicit:
for (int i = 0; i < n.length(); i++){
char c = n.charAt(i);
if (c >= '0' && c <= '9') {
counts[c - '0']++;
}
}
'0' is quite different from 0. '0' is the code of the "zero" character.
problem is in the line counts[n.charAt(i)]. here n.charat(i) may return values larger than 9;
The confusion here is that you're thinking '0' == 0. This is not true. When treated as a number, '0' has the ASCII value for the character 0, which is 48.
Because n.charAt(i) returns a character which is then boxed to a number. In this case the character 0 is actually ASCII value 48.
By subtracting character '0', you are subtracting the value 48 and taking the index into a range that is 0-9 because you've checked the character is a valid digit.

Converting characters to integers in Java

Can someone please explain to me what is going on here:
char c = '+';
int i = (int)c;
System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));
This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?
Edit: Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?
Edit2: 43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?
Character.getNumericValue(c)
The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.
The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
This method returns the numeric value of the character, as a
nonnegative int value;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 if the character has no numeric value.
And here is the link.
As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:
int value = (int)c.charValue();
Try any one of the below. These should work:
int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');
From the Javadoc for Character#getNumericValue:
If the character does not have a numeric value, then -1 is returned.
If the character has a numeric value that cannot be represented as a
nonnegative integer (for example, a fractional value), then -2 is
returned.
The character + does not have a numeric value, so you're getting -1.
Update:
The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back.
http://en.wikipedia.org/wiki/ASCII
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}

Categories

Resources