0% Complete
Minds on

MINDS ON

By now you are probably quite comfortable with the different variable types you’ve used in the course. You know that an integer is a whole number, a double contains decimals, a char is a single character, and a string is a series of characters together.

Perhaps what you didn’t know is that you can assign data of one variable type to another type. This is called type casting, or just “casting.”

The code snippets below will show you how to convert to and from different variable types:

From integer to double

 int anInteger = 5;
 double aDouble;

 aDouble = (double)anInteger;

Note that if you output anInteger, it would output “5”.  However, if you output aDouble, it would output as “5.0”.

From double to integer

 int anInteger;
 double aDouble = 5.0;

 anInteger = (int)aDouble;

Again, if you output anInteger, it would output “5”.  However, if you output aDouble, it would output “5.0”.

From String to char

 String aString = "A";
 char aChar;

 aChar = aString.charAt(0);

From char to String

 char aChar = "a";
 String aString;

 aString = String.valueOf(aChar);

From String to integer

 String aString = "756";
 int anInteger;

 anInteger = Integer.parseInt(aString);

Note that this will cause a run-time error if the string cannot be converted to an integer (i.e. if the string contained letters or two periods). Some programmers will use a try…catch command for this.

From String to double

 String aString = "199.43";
 double aDouble;

 aDouble = Double.parseInt(aString);

Note that this will cause a run-time error if the string cannot be converted to a double (i.e. if the string contained letters or two periods). Some programmers will use a try… catch command for this.

Did You Know?

Each of the variables in Java take up a specified amount of space in the computer.

For example, if a number is stored as an integer then it takes up 32 bits of data.

On the other hand, if the number is stored as a double, then it takes up 64 bits of data.

JAVA DATA TYPES
TYPE
STORAGE
MAXIMUM
MINIMUM
byte
8 bit
Uses signed twos complement.
127
Stored as 01111111
-128
Stored as 10000000
short
16 bit
Uses signed twos complement.
32,767
Stored as 01111111 11111111
-32,768
Stored as 10000000 00000000
int
32 bit
Uses signed twos complement.
2,147,483,647
-2,147,438,648
long
64 bit
Uses signed twos complement.
9,223,372,036,854,775,807
-9,223,372,036,854,775,808
float
32 bit
Uses single precision 32-bit IEEEE 754 floating point. Don't use for precise values, don't use for currency.
Humongous!
Negative Humongous!
double
64 bit
Uses double precision 64-bit IEEEE 754 floating point. Don't use for precise values, don't use for currency.
Extra Humongous!
Negative Extra Humongous!
boolean
Represents one bit (either a 1 or 0)
TRUE
FALSE
char
16 bit
Unicode character (converts the binary value into a character)
0
65,535

You may have noticed that there isn’t a string variable in the table above. In Java, a string is not an actual “primitive data type.” Instead, a string is something called an object.

In this course, you don't need to worry about things like “objects,” “signed twos complement” or “single precision 32-bit IEEEE,” but these are important concepts for computer scientists, and for the grade 12 course. If you are interested, you can read more about these concepts here:

This is the dropbox icon. Type Casting

Your task is to create a form that prompts the user for the following information:

  • a whole number and stores it as an integer
  • a decimal number and stores it as a Double
  • a single character and stores it as a char
  • a name and stores it as a String
  • a whole number and stores it as a String
  • a decimal number and stores it as a String

The program should then, with appropriate titles,

  • convert the whole number integer into a double and output it.
  • convert the decimal number Double into an integer and output it.
  • convert the single character into a String and output it.
  • convert the first character of the name into a char and output it.
  • convert the whole number String into an integer and output it.
  • convert the decimal number String into a Double and output it.

 
Action.

ACTION

Type Casting and Cryptography

Type casting is important when dealing with numbers and mathematics, because it can ensure that you get accurate results and that you make the program as efficient as possible in terms of storage. However, type casting can also be useful when it comes to manipulating strings and characters.

Cryptography

Cryptography involves keeping information secret or hidden by encrypting a regular message into code, and then being able to decrypt the coded message back into a regular, readable message.

People have been using cryptography for thousands of years. One of the simplest forms of encryption is known as the Caesar cipher or shift cipher. Julius Caesar used this method of encryption which involved “shifting” each letter in the alphabet. Instead of using the letter “a” in a message, the sender might shift the “a” three spots in the alphabet so that the letter “d” is used to represent the letter “a”. The same shift is used for each letter.

The following interactive will allow you to take a closer look at the Caesar cipher:

caeser

Long Description

 

Creating a Caesar Cipher in Java

There are a few different algorithms that could be used to create a Caesar cipher in Java. One is to simply use a series of if ... then ... else statements. The program could convert each letter in the string to a char, then use 26 statements like the ones below:

if (currentChar == “a”)
 {
     currentChar = “c”;
 }
else if (currentChar == “b”)
 {
    currentChar = “d”;
 }
Etc…

The algorithm above, however, is not that elegant and would involve a lot of repetition. Also, the programmer would need another 26 if ... then ... else statements to handle capital letters as well.

if (currentChar == “A”)
 {
     currentChar = “C”;
 }
else if (currentChar == “B”)
 {
    currentChar = “D”;
 }
Etc..

A second algorithm is based on the idea that a character can be converted into an integer. Yes, that’s right.  Read it again.  A character can be converted into an integer!

When you type letters or characters on a computer, they are actually interpreted as numbers in the computer. The American Standard Code for Information Interchange (ASCII) has assigned a corresponding integer value to the printable characters you type, and some of the command keys you press as well (like ENTER, BACKSPACE, TAB, etc). These ASCII values were developed in the 1960s and 1970s, and are implemented in most digital devices today.

The table below shows the corresponding ASCII values for the characters:

This is an image showing the ASCII values of a variety of characters.

You can download a version of this ASCII table here.

This means that when you type the word “Dog,” the computer actually interprets it as the characters corresponding to 68, 111 and 103.

The reason that these ASCII values are so important in encryption is that you can convert the characters into their ASCII values, add or subtract numbers to them, and then convert them back into characters.

Let’s look at an example written with actual Java code:

  • Let’s convert the character “a” into an ASCII integer:

        char letter;
        int asciiVal;       

        letter = 'a';
        asciiVal = (int)letter;

  • Let’s add four to the integer:        

        asciiVal = asciiVal + 4;

  • Now, let’s cast the new ASCII value back into a character:

         letter = (char)asciiVal;

  •  When you output the character it will no longer be an “a”; it will now output the character "e", since the “a” was bumped 4 places down the alphabet to “e”:

        System.out.println(letter);

Now that you’ve seen how to encrypt one character, let’s take a look at a program that prompts the user for a full message, and then encrypts the message by altering each character by 3:

 

Let’s take a closer look at the algorithm so that you can see how each small step leads to the String becoming encrypted:

  • Store one character from the String into the tempChar variable:

          tempChar = origMessage.charAt(i);   

  • Convert the character into an ASCII value:

          tempAscii = (int)tempChar;              

  • Add 3 to the ASCII value:

          tempAscii = tempAscii + 3;             

  • Convert the new ASCII value back into a character:

          tempChar = (char)tempAscii;             

  • Add the new character to the encrypted String variable:

          encMessage = encMessage + tempChar;     

Did You Know?

In the program above, the characters are shifted by 3 spaces. This means that the letter “a” becomes a “d”, the letter “g” becomes a “j”, etc. What will the letters “x”, “y” and “z”, at the end of the alphabet, become?

Since you are using the ASCII values, they will become the symbols “{“, “|” and “}” respectively.

If you don’t want this to happen, then you can include a “special case” if ... then ... else statement to handle these three characters.

The if ... then ... else statement could look like this:

This is an image of source code that shows the if statement necessary to handle the conversion of  x, y and z.

Notice that by subtracting 26 you are reverting back to the beginning of the alphabet.

Added Layers of Encryption

The program above encrypted a message by using a Caesar cipher, but you can add a little bit more complexity to the encryption algorithm.

Adding Extra Characters

Some encryption algorithms add extra characters to the messages in order to decrease the chance of someone being able to decrypt the message. You can add extra characters to your encrypted string using a few different techniques:

1. Simply add an extra character when you output the encrypted message. This can be done with a line of code like this:

          System.out.println("dfgtrfgg" + encMessage + "orkdnmxns");

This results in a string like “abc” being output as “dfgtrfggdeforkdnmxns”.

Notice that “def” is the encrypted string.

2. Generate random substrings to place before and after the message. These random substrings can be created by generating random ASCII values for the characters. Notice that the random number that is generated will be between 97 and 122. This is done because the ASCII values of lowercase letters are from 97 to 122.

for (int i = 0; i <= 7; i = i + 1)
{
 tempExtraAscii =(int)Math.round(Math.random()*25+1+96);   //generate a random integer between 97 and 122
 tempExtraChar = (char)tempExtraAscii;                              //convert the random integer into a character
 extraString1 = extraString1 + tempExtraChar;                     //add the extra character to tempExtraString1                    
}
        
for (int i = 0; i <= 7; i = i + 1)
{
    tempExtraAscii =(int)Math.round(Math.random()*25+1+96);    //generate a random integer between 97 and 122
    tempExtraChar = (char)tempExtraAscii;                                //convert the random integer into a character
    extraString2 = extraString2 + tempExtraChar;                       //add the extra character to tempExtraString2    
}
       

encMessage = extraString1 + encMessage + extraString2;        //concatenates the three Strings together
        
System.out.println("Encrypted Message:");
System.out.println(encMessage);                                     //output the reversed, encrypted String with a random leading and trailing String        
    
    

In this case, the person receiving these messages would have to know the number of characters, or sequence of characters, at the start and end of the string in order to decrypt the message.

Reversing a String

If you wanted to add another layer of encryption to your program, you could flip, or reverse, the provided string and then perform the Caesar cipher afterwards.

To “flip” or reverse a String we simply need to copy the Strings characters, one at a time, in reverse order, to a second String.

You can initialize a second, reverse string at the top of your program,

String revMessage = “”;

Then the key to reversing a string is the following for loop:

for (int i = origMessage.length() - 1 ; i >= 0 ; i = i - 1)

{
   revMessage = revMessage + origMessage.charAt(i);
}

This loop copies each character from the original string into the revMessage string. The important part is that it goes from back to front, so it starts at the last character of the origMessage string, copies it to the first spot in the revMessage string, and then copies the second last character of origMessage and copies it to the second spot in revMessage. This continues until it has copied all characters from the origMessage.

Now your program

  • reads in a message typed by the user.
  • reverses the message.
  • bumps each character by 3 in the alphabet.
  • generates 8 random characters to be placed at the front of the string, and 8 random characters to be placed at the end of the string.

The following video will explain the various components of the program:

 

Did You Know?

A palindrome is a “word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction.” (from palindromeList.com)

Usually, when you consider palindromes, you disregard punctuations and spacing.

The following are just a few examples:

  • mom
  • dad
  • kayak
  • radar
  • tacocat
  • a man, a plan, a canal: panama ●
  • was it a rat I saw?

There are several different algorithms that can be used to determine whether or not a word is a palindrome.

You could

  • compare the first letter to the last letter, then compare the second letter to the second last letter, then compare the third letter to the third last letter, etc.
This is an image of the word racecar with lines drawn comparing the various letters.
  • store the word in a second string, but store it backwards. You would then only have to compare the two strings.
This is an image showing the word racecar being stored in a variable, and then being stored in reverse in a second variable.

You have already looked at how to reverse a string, so if you took your “Reverse Word” algorithm from above, you could just add the comparison of the two strings at the bottom and you would have a palindrome finder:

This is an image of the source code that determines whether or not a string is a palindrome.

 

This is the dropbox icon. Creating an Encryption Program

Your task is to create a program that implements a GUI form to encrypt and decrypt messages. You might want the GUI form to resemble the following:

This is an image of the GUI form for the program.

 

The user should be able to enter a decrypted message and then click the ENCRYPT button to encrypt the message.

The user should also be able to enter in an encrypted message and click the DECRYPT button to decrypt the message.

The program should only accept messages that are less than 31 characters long. You can decide the level of complexity for your encryption.

You might want to

  • reverse the message.
  • perform a Caesar cipher.
  • add extra characters to the start or end of the message.
  • program an encryption algorithm that you find online or elsewhere.

Just be sure that your encrypted messages can be decrypted. The user should be able to decrypt an encrypted message and it should return to its original form.

NOTE: You can use the encryption code above or modify it if you like.

Your program should include

  • appropriately named variables and constants.
  • a user-friendly interface that allows for simple and easy use of your program.
  • a modular implementation with tasks broken up into methods.

 
Consolidation

CONSOLIDATION

Earlier in this activity, it was mentioned that characters such as “a” and “S” are stored as ASCII values in the computer. While this is true, it’s important to note that these letters would not be stored in decimal format, as 97 or 83.

Instead, they would actually be stored as the binary numbers 1100001 and 1010011. Since all data, and even all instructions, are stored as 0s and 1s on the computer, it’s important for you to develop some understanding of how binary numbers work.

Binary

Binary is a number system that uses 2 as it’s base. This contrasts with a decimal number system that uses 10 as it’s base. While a decimal number system uses 10 different digits (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9), the binary number system uses only two digits: 0 and 1.  Using 0s and 1s, the computer can represent any number imaginable.

So how does it work?

First let’s look at how the decimal number system works.

Imagine the number 267310.

Did You Know?

The small 10 that is written after the number means that it is written in base 10, or decimal notation. You usually don’t write that when you use numbers, because in our world, everyone counts using base 10, so it is our standard. But what would happen if different cultures used different number systems to count and communicate? That would get pretty confusing! In computer science, you need to know how to convert between different number systems to communicate with the computer, because it only understands 0s and 1s.

Remember when you were in elementary school and you learned how to add numbers? You used the concept of place values or columns. There was the ones column, tens column, hundreds column, thousands column, etc. for each digit.

In our decimal number system, the value of a digit depends on its place, or position, in the number. Each place has a value of 10 times the place to its right.

~ Math.com

Using the idea of place values, 267310 can be thought of as:

This is an image of the number 2673 broken up into 2 times 1000, 6 times 100, 7 times 10 and 3 times 1.

Note that the red numbers represent the place values or columns.  Since this is a base 10 number system, each place value is ten to the power of a number, starting from 0.

If you think of it this way, then 267310 can be thought of as:

This is an image of the number 2673 broken up into 2 times 10 to the exponent 3, 6 times 10 to the exponent 2, 7 times 10 to the exponent 1 and 3 times 10 to the exponent 0.

You can solve this number to get

2000 + 600 + 70 + 3

which is

267310

The binary system works in the same way, but in base 2. This means that starting from the ones column, each place value goes up by 2: ones, twos, fours, eights, sixteens, thirty-twos, etc.

Let’s take a look at the binary number 110102.  110102 can be thought of as:

This is an image of the number 11010 broken up as 1 times 16 plus 1 times 8 plus 0 times 4 plus 1 times 2 plus 0 times 1.

Or, using exponents it looks as follows:

This is an image of the number 11010 broken up into 1 times 2 to the exponent 4 plus 1 times 2 to the exponent 3 plus 0 times 2 to the exponent 2 plus 1 times 2 to the exponent 1 plus 0 times 2 to the exponent 0.

If you solve the above binary number you get

16 + 8 + 0 + 2 + 0

which is

2610

 

There are several different ways to convert binary numbers to decimal numbers. There are also several ways to convert decimal numbers to binary numbers.

 

The following videos will take you through a few of these techniques:

 
 

The Hexadecimal Number System

The hexadecimal number system is often used in Computer Studies to quickly represent binary numbers. Computers don’t use hexadecimal numbers, but when computer scientists, programmers or even graphic designers work with binary numbers, they sometimes work in hexadecimal to make things a little easier.

Example:

When developing web pages or designing logos, colours are often expressed as hexadecimal values. This page shows you some of the colours expressed using hexadecimal colour codes:

The hexadecimal system works in the same way as decimal and binary. It uses a place value system, but the base is not 10 or 2, it’s 16.

One problem you encounter with a base 16 system is that you will need 16 digits to represent your numbers. Of course, you only know 10: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.  This is why the hexadecimal number system uses letters as digits. The 16 digits in the hexadecimal number system are:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

When you are working with the hexadecimal number system, you can think of the letters as representing the following:

A = 10
B = 11
C = 12
D = 13
E = 14
F = 15

Did You Know?

The following are all numbers in the hexadecimal (base 16) system:

BAD16
FEED16
ACDC16
CAFE16
DECAF16

In order to understand the hexadecimal number system, let’s take a look at the hexadecimal number 2B7516.

2B7516 can be thought of as:

This is an image showing the number 2B75 represented as 2 times 16 to the exponent 3 plus b times 16 to the exponent 2 plus 7 times 16 to the exponent 1 plus 5 times 16 to the exponent 0.

You can temporarily replace the “B” with 11 to get:

This is an image showing the number 2B75 represented as 2 times 16 to the exponent 3 plus 11 times 16 to the exponent 2 plus 7 times 16 to the exponent 1 plus 5 times 16 to the exponent 0.

If we solve the above hexadecimal number we get:

8192 + 2816 + 112 + 5

which is

1112510, or just 11,125

There are several different ways to convert hexadecimal numbers to decimal numbers. There are also several ways to convert decimal numbers to hexadecimal numbers.

The following videos will take you through a few of these techniques:

 
 

This is the dropbox icon. Binary and Hexadecimal Converters

The focus of the last few activities has been on solving problems and developing algorithms. You have looked at top-down design with structure charts, the importance of flowcharts, and how writing pseudocode can help clarify instructions before programming. It is now your chance to design and implement your own algorithm. Your task is to create a program that converts numbers to and from decimal, binary and hexadecimal systems. Your program should resemble the following, whereby a user can convert decimal numbers to binary and hexadecimal numbers, or they can convert binary and hexadecimal numbers to decimal numbers:

This is an image of the GUI form to be made for the program.

 

Each of the conversions should be implemented in your program as a subroutine. When the user clicks the appropriate button, the correct subroutine should be called.

The key to this program will be to design appropriate algorithms for each conversion. To do so, think carefully about the methods used in the videos:

  • How can these methods be applied using programming concepts?
  • Will a loop be necessary?
  • Will arithmetic operators like *, % and / be required?

This is the type of program where algorithm design will possibly take up more time than actual programming.

As you go to create your algorithm, be sure to

  • create a top-down design outlining inputs, processes and outputs.
  • design a flowchart outlining each of the conversions, as well as 1 main flowchart that will call each of the other subroutines. In total you will make 5 flowcharts.
  • create a document to keep track of test cases. After you have created the program, create test cases for your program and list appropriate test inputs and expected outputs as well as any invalid data. Complete your test plan indicating actual outputs, and any fixes that were required. Your test cases can be created with word processing or spreadsheet software. This template might be helpful.

 

 

test text.