-2

Hi everyone I am new to Java programming...This is a code for ENCRYPTION/DECRYPTION of a message entered by a user program taken from a library book...Here strings "encrypt" and "decrypt" are made to contain char types...It should have been written as "char encrypt=(char)something;" but not as "String encrypt=(char)something;"...But this code works absolutely perfect without compilation error...please help

import java.util.Scanner;

class CaesarsCode
{
public static void main(String[] agrs)
{
    Scanner in=new Scanner(System.in);
    String encrypt="",decrypt="";

    System.out.println("Enter the message to be encrypted:");
    String msg=in.nextLine();
    for(int i=0;i<msg.length();i++)
    {   encrypt+= (char)(msg.charAt(i)+3);//how type-casting allowed here   }

    System.out.println("Encrypted message : "+encrypt);

    for(int i=0;i<msg.length();i++)
    {   decrypt+=(char)(encrypt.charAt(i)-3);//how type-casting allowed her }

    System.out.println("Decrypted message : "+decrypt);
}
}

2 Answers2

1

It is not a String <-> char casting, but only char arithmetic. String.at() returns a char, char allows arithmetic (it's a 16bit unicode value), and can be appended to a string. So there's no error in this code.

HappyCactus
  • 1,935
  • 16
  • 24
0

Example

String g = "line";
char c = g.charAt(0);  // returns 'l'
char[] c_arr = g.toCharArray(); // returns a length 4 char array ( 'l','i','n','e' )
Lokesh
  • 313
  • 2
  • 12