(char) (i + 'a') JAVA: what's happening here? [duplicate] - java

This question already has answers here:
Adding and subtracting chars, why does this work? [duplicate]
(4 answers)
Parentheses around data type?
(5 answers)
What does a 'int' in parenthesis mean when giving a value to an int?
(7 answers)
What is the purpose and meaning of (char)i or (int)i in java?
(3 answers)
Closed 2 years ago.
I encountered a similar piece of code:
public class print {
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.print((char) (i + 'a'));
}
}
}
If I run it, I get "abcdef".
My question regards this expression: (char) (i + 'a').
I kind of intuitively get what's going on, but I want a rigorous step-by-step explanation of how the computer translates it. As indicated in some answers, the char is simply a number displayed as a character. Fine, but what does this syntax with parentheses actually do? Is it a conversion? Can I use it for other types as well?

The ASCII value of a is 97.
When i = 0, i + 'a' = 0 + 97 => When cast into char, it will be a
When i = 1, i + 'a' = 1 + 97 => When cast into char, it will be b
When i = 2, i + 'a' = 2 + 97 => When cast into char, it will be c
...and so on

Java char is a 16-bit integral type. 'a' is the same as 97, which you can see with System.out.println((int) 'a'); - it follows that 98 is 'b' and so on across the entire ASCII table.

You can use char as an integer value and vise versa
Below code may help:
char aChar = 'a'; // a char
int aCharAscii = aChar; // 97
char bChar = 'a' + 1; // b char
int bCharAscii = aChar + 1; // 98

Related

what is '^=' operator in java [duplicate]

This question already has answers here:
Short hand assignment operator, +=, True Meaning?
(2 answers)
Difference between variable += value and variable = variable+value;
(4 answers)
Closed 3 years ago.
My code is as following:
char ch = t.charAt(t.length() - 1);
// result of XOR of two char is Integer.
for(int i = 0; i < s.length(); i++){
ch = ch^s.charAt(i);
ch = ch^t.charAt(i);
}
return ch;
it throws error
Line 6: error: incompatible types: possible lossy conversion from int to char
ch = ch^s.charAt(i);
Line 7: error: incompatible types: possible lossy conversion from int to char
ch = ch^t.charAt(i);
2 errors
However, When I change
ch = ch^s.charAt(i);
ch = ch^t.charAt(i);
to
ch ^= s.charAt(i);
ch ^= t.charAt(i);
Then, my code can work.
Are '^=' and '* = ^' different?? Why I search this question about '^=', it says they are same??
What is the '^=' operator?
From the functionality, they are the same: both perform an exclusive OR.
But the data types are different:
if I do x = x ^ y, the data type of x ^ y is always int or greater. When the result is assigned to something smaller, you have to cast.
if I do x ^= y, the data type doesn't grow as the assignment "knows its type".
See the language specification at https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2 for more details.
You need to declare ch to be an int, or store the result of the bitwise xor ^= in an int field. Right now it's trying to store it in a char which is where the error is coming from.

How to shift characters in an array left in Java? [duplicate]

This question already has answers here:
How do I shift array characters to the right in Java?
(2 answers)
Closed 5 years ago.
This is what I have right now:
class encoded{
public static void main(String[] args){
int shift = In.getInt();
String s1 = "bool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
System.out.print(c);
}
}
}
This code works to shift all characters in the string left by however much I want it to shift. The problem arises when, for example, I shift 'abc' 1 left, it returns '`ab'. What I want is for the characters to wrap back around to 'z' instead, so that the shifted 'abc' becomes 'zab' instead. How would I go about doing this? The characters need to always wrap back around to z when they're shifted left of 'a', and need to wrap back around to a when they're shifted right of 'z' (this would be done by changing "'a' - shift" to "'a' + shift".
Thanks so much in advance!
Not doing your homework for you, but giving you some hints:
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
You see, you are doing the shift operation unconditionally. Instead, read about using the if statement. You want to do your program different things, compared on the value of ch[i]. For some cases, just "shift", for others to replace values.
The problem is that the modulo operation can yield negative results.
In Java8 you can use Math.floorMod as an alternative:
class Main{
public static void main(String[] args){
int shift = 1;
String s1 = "abool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) ((Math.floorMod((ch[i] - 'a' - shift), 26)) + 'a');
System.out.print(c);
}
}
}
An alternative would be to use char c = (char) ( (((ch[i] - 'a' - shift) % 26) + 26) % 26 + 'a');

Converting a int to char [duplicate]

This question already has answers here:
Java - Change int to ascii
(9 answers)
Closed 5 years ago.
I am looking to convert numbers to their corresponding letter in the alphabet.
As seen here alphabetical characters start from either 65 or 97 (depending on capitalization) so you just add either 64 or 96 to your value and then just cast it to a char.
Random rand = new Random();
int TargetNumber = rand.nextInt(25) + 1;
char TargetChar = (char) (TargetNumber+64);
Try this
Random rand = new Random();
int TargetNumber = rand.nextInt(25) + 1;
char c = (char)(TargetNumber+96);
This adds 96 to the generated value, and then type casts it into a char. This works for a-z. To make it through A-Z replace 96, by 64.
i think you can do this:
char a = (char)20;

Shift character in Alphabet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ROT-13 function in java?
I have to shift all char from a string 13 places in the alphabet
private static String encode(String line) {
char[] toEncode = line.toCharArray();
for (int i = 0; i < toEncode.length; i++) {
if (Character.isLetter(toEncode[i])) {
toEncode[i] += 13;
}
}
line = String.valueOf(toEncode);
return line;
}
The Problem is that for example 'z' get to a ?. How can I solve that?
Thx for help.
It is because next chars after 'z' is punctuation chars and so on. You can shift so that 'z' will be 'n' for example.
toEncode[i] = (toEncode[i] + 13 - (int)'a') % 26 + (int)'a';
System.out.println(('z'+ (char)13)); //output -135
System.out.println((char)('z'+ (char)13)); //output - ?
If the calculated char is greater than the last letter (z => 122 or Z => 90) just substract the value of the last letter from the calculated value. You find these numbers all over the internet, e.g. here.

Conversion from ASCII values to Char

String source = "WEDGEZ"
char letter = source.charAt(i);
shift=5;
for (int i=0;i<source.length();i++){
if (source.charAt(i) >=65 && source.charAt(i) <=90 )
letterMix =(char)(('D' + (letter - 'D' + shift) % 26));
}
Ok what I'm trying to do is take the string WEDGEZ, and shift each letter by 5, so W becomes B and E becomes J, etc. However I feel like there is some inconsistency with the numbers I'm using.
For the if statement, I'm using ASCII values, and for the
letterMix= statement, I'm using the numbers from 1-26 (I think). Well actually, the question is about that too:
What does
(char)(('D' + (letter - 'D' + shift) % 26)); return anyway? It returns a char right, but converted from an int. I found that statement online somewhere I didn't compose it entirely myself so what exactly does that statement return.
The general problem with this code is that for W it returns '/' and for Z it returns _, which I'm guessing means it's using the ASCII values. I really dont know how to approach this.
Edit: New code
for (int i=0;i<source.length();i++)
{
char letter = source.charAt(i);
letterMix=source.charAt(i);
if (source.charAt(i) >=65 && source.charAt(i) <=90 ){
letterMix=(char)('A' + ( ( (letter - 'A') + input ) % 26));
}
}
Well I'm not sure if this homework, so i'll be stingy with the Code.
You're Writing a Caesar Cipher with a shift of 5.
To address your Z -> _ problem...I'm Assuming you want all the letters to be changed into encoded letters (and not weird Symbols). The problem is ASCII values of A-Z lie between 65 and 90.
When coding Z (for eg), you end up adding 5 to it, which gives u the value 95 (_).
What you need to do is Wrap around the available alphabets. First isolate, the relative position of the character in the alphabets (ie A = 0, B = 1 ...) You Need to subtract 65 (which is ASCII of A. Add your Shift and then apply modulus 26. This will cause your value to wrap around.
eg, it your encoding Z, (ASCII=90), so relative position is 25 (= 90 - 65).
now, 25 + 5 = 30, but you need the value to be within 26. so you take modulus 26
so 30 % 26 is 4 which is E.
So here it is
char letter = message(i);
int relativePosition = letter - 'A'; // 0-25
int encode = (relativePosition + shift) % 26
char encodedChar = encode + 'A' // convert it back to ASCII.
So in one line,
char encodedChar = 'A' + ( ( (letter - 'A') + shift ) % 26)
Note, This will work only for upper case, if your planning to use lower case, you'll need some extra processing.
You can use Character.isUpperCase() to check for upper case.
You can try this code for convert ASCII values to Char
class Ascii {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
char ch=sc.next().charAt(0);
if(ch==' ') {
int in=ch;
System.out.println(in);
}
}
}

Categories

Resources