CSC 160 Lab 1-2

Data Types

Remember that computers process data. All data is not the same: there are different categories or types of data.

A data type consists of a set of values together with the operations you can perform on those values. Integer number form a data type that is called int in Java. The values of type int look like this

1, 23, -13, 0,  48, -205

The type int uses symbols +, *, -, / to represent the familiar operations of addition of two numbers, multiplication, subtraction, and division. Here is a program that prints the sum of two numbers 12 and 34:

        package javaapplication2;

        public class JavaApplication2
        {
           public static void main(String[] args)
           {
                 System.out.println(12 + 34);
           }
       }
    

There are other data types, but we will return to those later.

Variables of Data Types

A variable is a name for a location in the computer's central memory where you can store data values. To create a variable with name V that will store values of a type T, you write

T  V;

Such a statement is called a variable declaration or a variable definition. Once you have created a variable, you store a value into it using the assignment operator =. Here is a program that creates two variables a and b, assigns values to them, and then prints the sum of the values in those variables.

.
package javaapplication2;

public class JavaApplication2
{
    public static void main(String[] args)
    {
        // Declare variables a and b
        int a;  
        int b;
        // Assign values to the variables
        a = 12;
        b = 34;
        // Print the sum of the two variables
        System.out.println(a + b);
    }
}
    

Exercise 1

Modify the program so it prints the product of 12 and 34 instead of the sum. Use the operator *.

Exercise 2

Modify the program so it prints the result of dividing 34 by 2. Use the operator /.

Exercise 3

Modify the program so it prints the result of dividing 34 by 3. Use the operator /. Are you surprised?

Variable Assignment and Initialization

A variable can be defined at most one time, but it can be assigned to many times. Each assignment to the variable replaces the value in the variable with a new one.

When you write variable definition such as

int a;

you do not specify a value to store in the variable, and you can use the assignment statement later to store a value. However, you can specify a value to be stored in a variable at the time you define it: in that case the variable declaration is called a variable initialization. This modification uses variable initializations:

package javaapplication2;

public class JavaApplication2
{
    public static void main(String[] args)
    {
        // initialize variables a and b
        int a = 12;  
        int b = 34;       
        // Print the sum of the two variables
        System.out.println(a + b);
        
        // Assign different values to a and b
        a = 50;
        b = -5;
        // Print the new sum
        System.out.println(a + b);
    }
}
    

The Scanner Class

We know how to do output by using the System.out object. Input can be done through the System.in object, unfortunately, that object can only read single characters. It is not able to directly read an integer or an entire string. To read integers and strings, we can use an object of the Scanner class.

To understand what is going on, we need to recall that a class is a pattern for creating or constructing objects. Not all classes allow objects to be created from them, but those that do provide methods called constructors that you can use to create an object of the class.

Google the phrase Java 7 Scanner, and click on the entry for Documentation for the Scanner class at the Oracle website. (Oracle is the corporation that puts out Java). That should take you to this link. Scroll down to the part with the heading Constructor Summary. Here you will find no less than 10 different constructors. These allow you to create a Scanner object in different ways. Note these three:

        Scanner(InputStream source)
        Scanner(String source)
        Scanner(File source)
    

These three constructors allow you to create a scanner that can read from an object of the InputStream class, or from a string object, or from a file object. Now it turns out that the System.in object, which represents the keyboard, is an object of the class InputStream. So to read from the keyboard, you need to create a scanner like this:

         Scanner sc;   // variable name for the scanner to be created
         sc = new Scanner(System.in);
    

The keyword new tells the compiler that you are using the constructor to create a new object.

Now, return to the documentation for the Scanner class and scroll down to look at its methods, under the section headed Method Summary. We are interested in three methods

        String next()
        String nextLine()
        int nextInt()
    

The nextInt() method is used to read an integer value from the keyboard. You then assign the integer read to an integer variable. The next() method is used to read a single token, or ``word" from the keyboard and return it as a string. The nextLine() method reads the rest of the current line from the keyboard, and returns it as a single string.

Here is a program that asks the user to enter an integer at the keyboard, and prints the square of that integer.

Note that to gain access to the Scanner class, you must add an import statement just below the package statement at the top.
package javaapplication2;

import java.util.Scanner;

public class JavaApplication2
{
    public static void main(String[] args)
    {
        // Create a Scanner object
        Scanner kbdScanner = new Scanner(System.in);
        // Variable for the number to be read
        int number;
        // Tell the user to enter a number
        System.out.print("Enter an integer: ");
        // Read the number using the scanner
        number = kbdScanner.nextInt();
        // Print the square of the number
        System.out.print("The square is ");
        System.out.println(number * number);
    }
}
    

When you run the program, you should click your mouse in the output window, just after the user prompt (the message prompting you to enter a number), so that when you enter the number, it does not go into the edit window and mess up your code:

Once you have entered your data, the results should look like this:

Exercise 4

Write a program that asks the user to enter two integer numbers (separated by blanks), and then prints the sum of the two numbers, the product of the two numbers, the difference of the two numbers, and the quotient of the two numbers. (The quotient is the result of dividing the first number by the second.) Here is what a sample interaction should look like:

Enter two integers: 12 5
The sum is 17
The product is 60
The difference is 7
The quotient is 2
    

The char and boolean types

The values of the type char are single characters. It differs from the String class, whose values are sequences of characters. You write single characters using single quotes, like this:

'a',  'b',  'A', 'B', '?', '!'. '"'

These are the literal characters lowercase a, lowercase b, uppercase A, uppercase B, the question mark, the exclamation, the double quote character.

The newline character is written as the character n preceded by the backslash, it is written like this: '\n'. The backslash character \ is called the escape character, it is used to escape from, or alter, the meaning of other characters. If you want to write the backslasch character, you must escape its usual meaning by using two backslashes: '\\' represents a single backslash character.

The boolean type has only two values, written true and false. The boolean type has several operations, but we study those later.

You can create variables of char and boolean types. Also, when you compare two primitive types of the same type, like two char values, or two integer values, using the comparison operators > or < you get a boolean value of either true or false.

Run this program and think about what you see.
package javaapplication2;

public class JavaApplication2
{
    public static void main(String[] args)
    {
       // Create a char variable and assign a value
       char ch;
       ch = 'A';
       // Create a boolean value and assign a value
       boolean bValue;
       bValue = true;       
       // Print the character and the boolean value
       System.out.println(ch);
       System.out.println(bValue);       
       // Assign a truth value of comparing ch to 'A' ro see they are equal
       bValue = ch == 'A';
       System.out.println(bValue);       
       // Assign a truth value of comparing ch to 'a' ro see they are equal       
       bValue = ch == 'a';
       System.out.println(bValue);       
       // Print the truth value of the comparing if 'a' is less than 'b'
       System.out.println('a' < 'b');       
        // Print the truth value of the comparing if 'a' is greater than 'b'
       System.out.println('a' > 'b');         
    }
}
    

The String Class

The String class is very useful. You can google Java 7 String to get to the documentation of the String class, at this link. This class has several instance methods, that is methods that work on a specific individual object of the class:

int length()
boolean isEmpty()
char charAt(int index) 
int indexOf(char ch)
int indexOf(String str)
String toUpperCase()
String toLowerCase()
String concat(String str)
    

int length() returns an integer representing the length of the string. The following statements print 5 and 6 respectively.

package javaapplication57;

public class JavaApplication57
{
    public static void main(String[] args)
    {
        String str = "World!"; // string has length 6
        //Print length of the string "hello"
        int len = "hello".length();
        System.out.println(len);  // Prints 5
        // Print length of "World!"
        System.out.println(str.length());
    }
}	
	

A string is a sequence of characters. The first character in the string is at position 0, the second character is at position 1, the third at position 2, and so on. The position of a character in a string is called its index. For example, in the string "hello" the character at index 0 is 'h', while the character at index 2 is 'l'.

The String method charAt returns the character at a given position in the string. For example,

	System.out.print("xyz".charAt(1))
	

prints the character 'y'. Read the documentation of the rest of eight string methods we have listed above, and see if you can figure out what they do.

.

Exercise 5

Write a program that uses a scanner to read in a string, and prints its uppercase version. Here is a sample input output interaction.

        Enter a string: NorthCentral
        The uppercase version is NORTHCENTRAL	
	

Use a scanner, and the next() method of the scanner to read the string.

Exercise 6 (Lab 1-2 Homework)

This program (Exercise 6) must be turned in for grading. Write a program that asks the user to enter two strings separated by blanks. The program then prints the two strings in reverse order, then prints the lengths of the two strings, and then prints the last character of each string. Here is a sample of the input/output interaction.

Enter two strings:North Central
The two strings in reverse order are: 
Central North
The lengths of the strings are: 5 7
The last characters of the strings are: h l	
	

How to submit Your Program

Locate the project folder on your computer. Make a note of this when you create the project. In Windows explorer, right click on the program folder, and then select Send to Compressed Folder. This will create a zip folder on your computer. Right click on the zip folder, and select Send to Groupwise Recipient. This will create an email with the zip folder attached. Add a subject CSC 160 Lab1-2 Submission and email it to Godfrey Muganda .

Due Date

This is due Friday at the end of Week 1, at midnight.