You are on page 1of 14

SENIOR HIGH SCHOOL

First Semester S.Y. 2020-2021

MODULE 5
COMPUTER PROGRAMMING 1
(JAVA)

Name: _______________________________ Date :__________


Grade/Section: ________________________ Week : 5
Track/Strand: _________________________
Lesson 5 COMPUTER PROGRAMMING 1 (JAVA) –
Primitive Data, Variables and the Assignment Statement

WHAT DO YOU EXPECT TO LEARN?

Content Standard:
The learners demonstrate understanding of the:
1. Data Types
2. Primitive Data vs. Objects
3. The Eight Primitive Data Types of Java
4. Numeric Data Types
5. Character and Boolean Data Types

Performance Standard:
The learners should be able to design a Java Program that utilizes
primitive data types.

Objectives:
After the lesson, the learners should be able to:
1. differentiate primitive data vs objects
2. enumerate the 8 primitive data types of Java
3. explain the importance of the different data types

PRELIMINARY ACTIVITY

Say that you came across the following torn slip of paper. What does it
mean?

DATA TYPES

You would like to see the rest of the paper, or know where it came
from. Without knowing the context, it is hard to say what MIX means.
It could be 1009 in Roman numerals, or it could be the English word "mix"
(which itself has several meanings), or it could be the last name of the
old-time radio hero Tom Mix. It could be part of a label on a music CD,
"MTV Dance MIX", or part of a label on a bottle, "BLOODY MARY MIX".
Or maybe you are looking at it upside down and it should be "XIW". Of
course, it might not be English at all. Without knowing the context, a
string of letters has little meaning.
Computer memory stores arbitrary bit patterns.
As with a string of letters, the meaning of a string of bits depends
on how it is used. The scheme being used for a particular string of bits is
its data type.

For example

0000000001100111

is a pattern of 16 bits that might be found somewhere in computer memory. What does
it represent?

Without knowing more about how the above pattern is being used, it is
impossible to say what it represents. The type short is one of Java's data types. If the
pattern is regarded as data type short, then it represents the value 103 (one hundred
and three). If the pattern is regarded as data type char, then it represents the character
'g'.

Question 1: What does the following 16 bit pattern represent?


0000000000000000

Answer: Without knowing more about how the pattern is being used, it is impossible to say.

THERE ARE MANY DATA TYPES

You might be tempted say that the pattern 0000000000000000 represents "zero".
But it doesn't necessarily. Even such an obvious pattern has no automatic meaning.

If you were told that the above pattern were of type short, then you would know
that it represents the integer zero. Here is another pattern:

1111111110011001
As a short, this pattern represents -103 (negative one hundred three).

There are unaccountably many types of data that can be represented in the
memory of a computer. If specific patterns always had specific meanings, then only a
few types of data could be represented. This would be much too restrictive. Many data
types are invented by programmers as they write programs. Without this flexibility
computers would be much less useful.

The main memory of a general-purpose computer (such as a desktop or a laptop


computer) contains very many bits. Programs can use this memory with whatever data
types they need. For example, one program may use data type int with four bytes of
memory, and data type double with another eight bytes of memory. A different
program may use the same memory with different data types.

Not all machines use memory this way. A simple electronic calculator, for
example, uses memory for one purpose only: to store floating point numbers. It uses
only one data type, and can do only those few things with that data type that it has been
wired to do. The engineers who designed the calculator decided how to represent
numbers with bit strings, and then designed the electronics to work with just those
strings. This is too restrictive for a general-purpose computer.

Question 2: Do you imagine that the computers of the 1960's were built to handle
audio data?

Answer: No — certainly this was not a common use for computers then.

PRIMITIVE DATA TYPES

But some 1960's computers did compute with audio data. The programmers


invented a way to represent audio with bit patterns and then wrote programs that were
consistent with that scheme.

Recall the fourth advantage of binary (from chapter 2): Anything that can be
represented with some sort of pattern can be represented with patterns of bits. Music can
certainly be represented with patterns of symbols, and so can be represented with
patterns of bits. (This is obvious now, but was not quite so obvious in 1960.)

It would be awkward if every time you used data you had to invent your own
scheme to represent it with bits. There are types of data that are so fundamental that
ways to represent them are built into Java. These are the primitive data types. The eight
primitive data types are: byte, short, int, long, float, double, char, and boolean.

Upper- and lower-case characters are important in these names. So "byte" is the
name of a primitive data type, but "BYTE" is not. Computer languages where case is
important are called case sensitive. Some languages are not case sensitive, especially
old languages that were designed when data entry equipment did not have lower case
characters.
In the phrase primitive data type the word primitive means "a fundamental
component that is used to create other, larger parts." This word is used frequently in
computer science. To solve a large problem, you look for the primitive operations that
are needed, then use them to build the solution.

OBJECTS

All data in Java falls into one of two categories: primitive data and objects. There


are only eight primitive data types. However, Java has many types of objects, and you
can invent as many others as you need. Any
data type you invent will be a type of object.

Much more will be said about objects in


future chapters (since Java is a object
oriented programming language). The
following is all you need to know, for now:

 A primitive data value uses a small,


fixed number of bytes.
 There are only eight primitive data types.
 A programmer cannot create new primitive data types.

 An object is a big block of data. An object may use many bytes of memory.
 An object usually consists of many internal pieces.
 The data type of an object is called its class.
 Many classes are already defined in Java.
 A programmer can invent new classes to meet the particular needs of a program.

A (crude) analogy is that a primitive data value is like a nut or a bolt, but an
object is like a whole machine.

NUMERIC PRIMITIVE DATA TYPES

Numbers are so important in Java that six of the eight primitive data types are
numeric types.

There are both integer and floating-point primitive types. Integer types have no


fractional part; floating point types have a fractional part. On paper, integers have no
decimal point, and floating-point types do. But in main memory, there are no decimal
points. Even floating-point values are represented with bit patterns. There is
a fundamental difference between the method used to represent integers and the
method used to represent floating point numbers.

Each primitive type uses a fixed number of bits. This means that if you are using a
particular data type then the same number of bits will be used no matter what value is
represented.

For example, all values represented using the short data type use 16 bits. The
value zero (as a short) uses 16 bits and the value thirty thousand uses 16 bits.

All values represented using the long data type use 64 bits. The value zero (as
a long) uses 64 bits, the value thirty thousand uses 64 bits, and the value eight trillion
uses 64 bits.
Values that are large in magnitude (negative or positive) need more bits to be
represented. This is similar to writing out numbers on paper: large numbers need more
digits. If a value needs more bits than a particular data type uses, then it cannot be
represented using that data type.

In the tables, E means "ten to the power of". So, 3.5E38 means 3.5 x 1038

Question 3: Say that you want to deal with the number 1,023,004 in your
computer program. Would data type short be an appropriate choice?

Answer: No. Data of type short can be only in the range -32,768 to +32,767.

PRECISION OF FLOATING-POINT NUMBERS

Consider writing the value 1/3 in decimal notation:

0.333333333333333333

There is no limit to the number of 3's required for complete accuracy. However,
with a limited amount of paper, you cannot be completely accurate. With a data
type, there is a limited number of bits. Those bits cannot accurately represent a value
that requires more than that number of bits.

The data type float has 24 bits of precision. This is equivalent to only about 7


decimal places. (The rest of the 32 bits are used for the sign and size of the number.)

The number of places of precision for float is the same no matter what the size of
the number. Data type float can represent numbers as big as about 3.4E+38. But the
precision of these large numbers will also be about 7 decimal digits.
Remember: data type float has about the range and precision of a cheap pocket
calculator. This is usually not sufficient.

PRECISION OF DOUBLE

You might wish to argue that there are only five places used in the above number: the
places used by the digits 1, 2, 3, 8, and 9. However, the four 0's in the middle do
count. It takes bits to represent them, even if they are zeros.

Primitive data type double uses 64 bits, and has a much greater range, -1.7E+308 to


+1.7E+308. It also has a much greater precision: about 15 significant decimal digits.

Because of this, if you write a literal like 2.345 in a Java program, it will automatically be


regarded as a double, even though a float might be good enough. The other numbers in
the program might need to be double, so we might as well make them all double.

THE CHAR PRIMITIVE DATA TYPE

Computer programs frequently work with character data. The primitive data


type for characters in Java is named char. The char type represents a character using 16
bits. In many programming languages, only 8 bits are used for this purpose. Java uses
16 bits so that a very large number of characters can be represented, nearly all of the
characters in all of the World's languages. The method used is called Unicode.

For example, here is a 16 bit pattern:

0000000001100111

If you know that these 16 bits are of data type char, then you could look in a table
and discover that they represent the character 'g'. If you have a really good memory,
you might recall that the same 16 bits represent the integer 103 if they are regarded as
data type short. Knowing the data type of a pattern is necessary to make sense of it.

Upper and lower case characters are represented by different


patterns. Punctuation and special characters are also char data. There are also special
characters, like the space character that separates words.

Control characters are bit patterns that show the end of a line or where to start
pages. Other control characters represent the mechanical activities of old
communications equipment (such as Teletypes) that are rarely used these days. Many of
these control characters are no longer used for their original purpose.

Primitive type char represents a SINGLE character. It does not include any font


information. When you want to deal with more than one character at a time (almost
always), you need to use objects that have been built out of char data.

CHARACTER LITERALS

A character literal is a single character with an apostrophe on each side:

'm' 'y' 'A'

A control character is represented with a special sequence of characters:

'\n' '\t'
Each of these represents a single control character. The first one represents the
newline character and the second one represents the tabulation character. You will
rarely use any control characters other than these two. Several others are listed in the
Java documentation.

Warning: The following is not a character literal:

"Hello"

This is a String, which is not primitive data. It is, in fact, an object. Strings are


surrounded by double quote marks ", not by apostrophes.

PRIMITIVE DATA TYPE BOOLEAN

Another of the primitive data types is the type boolean. It is used to represent


a single true/false value. A boolean value can have only one of two values:

true false

In a Java program, the words true and false always mean these boolean values.


The data type boolean is named after George Boole, a nineteenth century
mathematician, who discovered that a great many things can be done with true/false
values. Although the amount of information in a boolean primitive is logically one bit,
for convenience Java uses more than that to represent it.

VARIABLES AND ASSIGNMENT STATEMENTS

The billions of bytes of main storage in your home computer are used to store
both machine instructions and data. The electronic circuits of main memory (and all
other types of memory) make no distinction between the two. It just holds bit patterns.

When a program is running, some memory locations


are used for machine instructions and others for data. Later,
when another program is running some of the bytes that
previously held machine instructions may now hold data, and
some that previously held data may now hold machine
instructions.

Using the same memory for both instructions and data was the idea of John von
Neumann, a computer pioneer.

Recall that a data type is a scheme for using bit patterns to represent a value.
Think of a variable as a little box made of one or more bytes that can hold a value using
a particular data type.
To put a value in memory, and later to get it back, a program must have a name
for each variable. Variables have names such as payAmount. (Details will be given in a
few pages.)

Variables come and go as a running program needs them. When a running


program no longer needs a variable, that section of memory may be reused for some
other purpose.

Question 4: Must a variable always have a data type?

Answer: Yes. Otherwise it would not be clear what its bits represent.

DECLARATION OF VARIABLEE

The example program uses the variable payAmount. The statement

long payAmount = 123;

is a declaration of a variable. A declaration of a variable is where a program says that it


needs a variable. For our small programs, place declaration statements between the two
braces of the  main  method.

The declaration gives a name and a data type for the variable. It may also ask
that a particular value be placed in the variable. In a high level language (such as Java)
the programmer does not need to worry about how the computer hardware actually
does what was asked. If you ask for a variable of type long, you get it. If you ask for the
value 123 to be placed in the variable, that is what happens. Details about bytes, bit
patterns, and memory addresses are up to the Java compiler.

In the example program, the declaration requests an eight-byte section of


memory named payAmount which uses the primitive data type long for representing
values. When the program starts running, the variable will initially have the value
123 stored in it.

A variable cannot be used in a program unless it has been declared.

SYNTAX OF VARIABLE DECLARATION

The word syntax means the grammar of a programming language. We can talk


about the syntax of just a small part of a program, such as the syntax of variable
declaration.
There are several ways to declare variables:

dataType variableName;

 This declares a variable, declares its data type, and reserves memory for it. It says
nothing about what value is put in memory. (Later in these notes you will learn
that in some circumstances the variable is automatically initialized, and that in
other circumstances the variable is left uninitialized.)

dataType variableName = initialValue;

 This declares a variable, declares its data type, reserves memory for it, and puts
an initial value into that memory. The initial value must be of the correct data
type.

dataType variableNameOne, variableNameTwo ;

 This declares two variables, both of the same data type, reserves memory for
each, but puts nothing in any variable. You can do this with more than two
variables, if you want.

dataType variableNameOne = initialValueOne,


variableNameTwo = initialValueTwo ;

 This declares two variables, both of the same data type, reserves memory, and
puts an initial value in each variable. You can do this all on one line if there is
room. Again, you can do this for more than two variables as long as you follow
the pattern.

If you have several variables of different types, use several declaration


statements. You can even use several declaration statements for several variables of the
same type.

NAMES FOR VARIABLES

The programmer picks a name for each variable in a program. Various things in
a program are given names. A name chosen by a programmer is called
an identifier. Here are the rules for identifiers:

 Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', and
characters '$' and '_'.
 An identifier cannot contain the space character.
 Do not start with a digit.
 An identifier can be any length.
 Upper and lower case count as different characters.
o SUM  and  Sum  are different identifiers.
 An identifier cannot be a reserved word.
 An identifier must not already be in use in this part of the program.

A reserved word is a word which has a predefined meaning in Java. For


example int, double, true, and import are reserved words. Rather than worry about the
complete list of reserved words, just remember to avoid using names that you know
already mean something, and be prepared to make a change if you accidentally use a
reserved word you didn't know.
Although dollar sign is legal in identifiers, by convention it is used for special
purposes. Don't use it for ordinary variables, even if the compiler lets you.

Although legal, it is unwise to start an identifier with underscore. Also, older


Java compilers allowed a single underscore as an identifier, but recent ones do not.

As a matter of programming style, a name for a variable usually starts with a


lower case letter. If a name for a variable is made of several words, capitalize each word
except the first. For example, payAmount and grandTotal. These conventions are not
required by syntax, but make programs easier to read.

VARIABLES AND ASSIGNMENT STATEMENTS

So far, the example programs have been using the value initially put into a
variable. Programs can change the value in a variable. An assignment
statement changes the value that is held in a variable. The program uses an assignment
statement.

The assignment statement puts the value 123 into the variable. In other words,
while the program is executing there will be a 64 bit section of memory that holds the
value 123.

Remember that the word "execute" is often used to mean "run". You speak of
"executing a program" or "executing" a line of the program.

Assignment statements look like this:

variableName = expression ;

 The equal sign = is the assignment operator.


 variableName is the name of a variable that has been declared previously in the
program.
 expression is a collection of characters that calls for a value to be calculated.

Here are some example assignment statements (assume that the variables have
already been declared):

total = 3 + 5;
price = 34.56;
tax = total*0.05;
In the source file, the variable must be declared before any assignment statement
that uses that variable.

Question 4: Is the following correct?


int sum;
sum = 42 - 12 ;

Answer: Yes, the statements are syntactically correct.

ASSIGNMENT STATEMENT SEMANTICS

The syntax of a programming language says what programs look like. It is the


grammar of how to arrange the symbols. The semantics of a programming language
says what the program does as it executes. It says what the symbols mean. This page
explains the semantics of the assignment statement.

An assignment statement does its work in two steps:

1. First, do the calculation on the RIGHT of the equal sign.


o If there is nothing to calculate, use the value on the right.
2. Next, replace the contents of the variable on the LEFT of the equal sign with the
result of the calculation.

Example

value = 2*3

1. FIRST, do the multiplication


2*3 to get the value 6.

2. NEXT, put the result of the calculation into


the "little box of memory" used for the
variable value:

It will really, really help you to think carefully about


these two steps. Sometimes even second year computer
science majors get confused about this and write buggy
code.

ASSESSMENT

MULTIPLE CHOICE
Direction: For each question, choose the correct answer. Encircle the letter only.
1. Which one of the following is a reserved word?
A. apple B. 7up
D. boolean
C. grandTotal
2. Which one of the following is NOT a correct variable name?
A. 2bad C. theLastValueButOne
B. zero D. year2000

3. Which of the following shows the syntax of an assignment statement?


A. variableName = expression; C. expression = variableName;
B. expression = expression; D. dataType = variableName;

4. Which of the following is NOT the name of a Java primitive data type?
A. int C. double
B. float D. String
5. What is an expression?
A. The same thing as a statement.
B. An expression is a list of statements that make up a program
C. An expression is a combination of literals, operators, variables, and
parentheses used to calculate a value.
D. An expression is a number expressed in digits.
6. Say that a particular item of data in a Java program does NOT use a primitive data
type. What must it be?
A. An object. C. A literal.
B. A number. D. A boolean.

7. What are the two steps that take place when an assignment statement is executed?
A. (i) Evaluate the Expression, and (ii) Store the value in the variable.
B. (i) Store the value in the variable, and (ii) Evaluate the Expression.
C. (i) Reserve memory, and (ii) fill it with a number.
D. (i) Evaluate the variable, and (ii) store the results.

8. What is a data type?

A. The part of the CPU that does arithmetic.


B. A part of main memory used to store data.
C. A particular scheme for representing values with bit patterns.
D. The collection of variables that a program uses.

9. What is the value of the following expression:


(2 - 6) / 2 + 9
A. 7 C. 9
B. 8 D. 10

10. What is a Java primitive data type?


A. A method for representing values that is so useful that it is a fundamental part of
the language.
B. A crude form of representing numbers.
C. The part of Java that is the same as in older languages.
D. A data type that cannot be used as part of an object.

FEEDBACK

________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
__________________________________________________________

HOW DO YOU LIKE OUR TOPIC?

REFERENCES

1. http://programmedlessons.org/Java9/chap08/ch08_01.html
2. https://www.youtube.com/watch?v=qUXbJziVs_o
3. http://programmedlessons.org/Java9/chap09/ch09_01.html
4. https://www.youtube.com/watch?v=RA7wkTV6z4k

You might also like