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:
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”.
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”.
String aString = "A";
char aChar;
aChar = aString.charAt(0);
char aChar = "a";
String aString;
aString = String.valueOf(aChar);
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.
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.
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 | |||
---|---|---|---|
|
|
|
|
|
Uses signed twos complement. |
Stored as 01111111 |
Stored as 10000000 |
|
Uses signed twos complement. |
Stored as 01111111 11111111 |
Stored as 10000000 00000000 |
|
Uses signed twos complement. |
|
|
|
Uses signed twos complement. |
|
|
|
Uses single precision 32-bit IEEEE 754 floating point. Don't use for precise values, don't use for currency. |
|
|
|
Uses double precision 64-bit IEEEE 754 floating point. Don't use for precise values, don't use for currency. |
|
|
|
|
|
|
|
Unicode character (converts the binary value into a character) |
|
|
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:
Your task is to create a form that prompts the user for the following information:
The program should then, with appropriate titles,
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 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:
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:
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:
char letter;
int asciiVal;
letter = 'a';
asciiVal = (int)letter;
asciiVal = asciiVal + 4;
letter = (char)asciiVal;
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:
tempChar = origMessage.charAt(i);
tempAscii = (int)tempChar;
tempAscii = tempAscii + 3;
tempChar = (char)tempAscii;
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:
Notice that by subtracting 26 you are reverting back to the beginning of the alphabet.
The program above encrypted a message by using a Caesar cipher, but you can add a little bit more complexity to the encryption algorithm.
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.
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
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:
There are several different algorithms that can be used to determine whether or not a word is a palindrome.
You could
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:
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:
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
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
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 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:
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:
You can solve this number to get
which is
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:
Or, using exponents it looks as follows:
If you solve the above binary number you get
which is
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 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:
You can temporarily replace the “B” with 11 to get:
If we solve the above hexadecimal number we get:
which is
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:
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:
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:
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