EEI3262 Unit 1 Session 2
EEI3262 Unit 1 Session 2
Session 2
Data Types and Variables in Java
Contents
Introduction, p13
2.1 Syntax and Semantics in Java, p 13
2.2 Naming guidelines in Java, p 14
2.3 Variables, p 16
2.4 Data Types, p 18
2.5 Literals, p 22
2.6 Variables in Java, p23
Summary, p25
Learning Outcomes, p26
Review Questions, p26
Introduction
Before learning to write programs in Java applying object oriented concepts,
you have to get familiar with some common syntax and semantics in Java.
In a programming language, syntax is the set of rules defines the
combination of symbols or characters which forms a correctly structured
fragment in that language. Semantics show how to specify the meaning of
programming language fragments. When we write programs, we should
write both syntactically and semantically correct code, if not the program
will not be compiled correctly and will identify syntax and semantic errors.
This session will provide you an insight to Java programming concepts such
as basic language syntax, variables, literals and primitive data types. You
will be writing a simple Java program, compile and execute it in this
session. Thereby you will be able to differentiate syntax and semantic errors
and you will learn to error free programs.
13
Session 2 : Data Types and Variables in Java
2.1.1 Syntax
Programming languages differ from ordinary human languages in being
completely unambiguous and very strict about ‘what is’ and ‘what is not’
allowed in a program. The rules that determine what is allowed are called
the syntax of the language. Syntax rules specify the basic vocabulary of the
language and how programs can be constructed using things like loops,
branches, and subroutines. A syntactically correct program is one that can
be successfully compiled or interpreted; programs that have syntax errors
will be rejected.
2.1.2 Semantics
So, to be a successful programmer, you must develop a detailed knowledge
of the syntax of the programming language that you are using. However,
syntax is only part of the story. It's not enough to write a program that will
run if you want a program that will run and produce the correct result. That
is, the meaning of the program must be right. The meaning of a program is
referred to as its semantics. More correctly, the semantics of a programming
language is the set of rules that determine the meaning of a program written
in that language. A semantically correct program is one that does what you
want it to.
Let’s learn to write Java statements avoiding syntax and semantic errors. If
you get compile or run time errors during the compilation or execution you
can always fix them. To fix the errors you should be able to identify them. If
you have written your code well, it will be easier for you to locate if there
are any errors. To write code well, there are many techniques you can use,
using naming guidelines, which is explained in the next section.
14
Session 2 : Data Types and Variables in Java
According to the syntax rules of Java, the most basic names are identifiers.
Identifiers can be used to name classes, variables, and subroutines. We
introduce classes to you in Session 5 and the variables in the next section.
An identifier is a sequence of one or more characters. It must begin with a
letter or underscore and must consist entirely of letters, digits, and
underscores. ("Underscore" refers to the character '_'.)
Reserved words are not identifiers, since they can't be used as names for
things.
Java is liberal about what counts as a letter or a digit. Java uses
the Unicode character set, which includes thousands of characters from
many different languages and different alphabets, and many of these
characters count as letters or digits.
The pragmatics of naming includes style guidelines about how to choose
names for things. For example, it is customary for names of classes to begin
with upper case letters, while names of variables and of subroutines begin
with lower case letters. You can avoid a lot of confusion by following this
standard convention in your own programs. Most Java programmers do not
use underscores in names, although some do use them at the beginning of
the names of certain kinds of variables. When a name is made up of several
words, such as HelloWorld or interestRate, it is customary to
capitalize each word, except possibly the first. This is sometimes referred to
as camel case, since the upper case letters in the middle of a name are
supposed to look something like the humps on a camel's back.
In addition to simple identifiers, Java can have compound names which
consist of several simple names separated by periods. Compound names are
also called qualified names. An example is given below.
System.out.println();
2.3 Variables
Programs manipulate data that are stored in memory. In machine language,
data can only be referred to by giving the numerical address of the location
in memory where the data is stored. In a high-level language such as Java,
names are used instead of numbers to refer data. It is the job of the computer
to keep track of where in memory the data is actually stored; the
programmer only has to remember the name. A name used in this way, to
refer the data stored in memory is called a variable.
A variable is not a name for the data itself but for a location in memory that
can hold data. This is shown in Fig. 2.1. You should think of a variable as a
container or box where you can store data that you will need to use later.
Data
Variable
The variable refers directly to the box and only indirectly to the data in the
box. Since the data in the box can change, a variable can refer to different
data values at different times during the execution of the program, but it
always refers to the same box. Confusion can arise, especially for beginners
of programming, because when a variable is used in a program in certain
ways, it refers to the container, but when it is used in other ways, it refers to
the data in the container.
In Java, the only way to get data into a variable, which is into the box,
which the variable name is with an assignment statement.
An assignment statement takes the form:
variable name= data;
where expression represents anything that refers to or computes a data
value. When the computer comes to an assignment statement during the
execution of a program, it evaluates the expression and puts the resulting
data value into the variable.
For example, consider the simple assignment statements
rate = 0.07;
principal = 1000;
16
Session 2 : Data Types and Variables in Java
0.07 1000
rate principal
0.07 * 1000
interest
17
Session 2 : Data Types and Variables in Java
18
Session 2 : Data Types and Variables in Java
19
Session 2 : Data Types and Variables in Java
20
Session 2 : Data Types and Variables in Java
double 64 8 NA NA 0.0d
boolean 1 NA NA NA false
char 16 NA NA NA ''
It is important to remember that a primitive type value is represented using
only a certain, finite number of bits. So, an int can't be an arbitrary integer.
It can only be an integer in a certain finite range of values.
Similarly, float and double variables can only take on certain values.
They are not true real numbers in the mathematical sense. For example, the
mathematical constant π can only be approximated by a value of
type float or double, since it would require an infinite number of
decimal places to represent it exactly. For that matter, simple numbers like
1/3 can only be approximated by floats and doubles.
State whether the following statements are TRUE or FALSE. If the statement is False
correct it and re-write.
1 Java is a weakly typed language True / False
2 7 primitive data types are there in Java True / False
3 In Java byte, short, int and long these are unsigned True / False
4 Size of int in Java is 16 bit True / False
5 The smallest integer type is short and its size is 1 byte True / False
6 Size of float and double in Java is 32 and 64 True / False
21
Session 2 : Data Types and Variables in Java
Write the suitable data type to create variables to store following data.
Number of students : 45 E.g. int
Salary : Rs. 25,000
Body Mass Index : 18.5 kg/m2
Grade : ‘A’
Height: 150 cm
Age<= 35 : true
Distance between earth and
sun : 149,600,000 km
pi(𝜋) value : 3.14159265359
2.5 Literals
A data value is stored in the computer as a sequence of bits. In the
computer's memory, it doesn't look anything like a value written on this
page. You need a way to include constant values in the programs that you
write. In a program, you represent constant values as literals. A literal is
something that you can type in a program to represent a value. It is a kind of
name for a constant value.
For example, to type a value of type char in a program, you must surround
it with a pair of single quote marks, such as 'A', '*', or 'x'. The
character and the quote marks make up a literal of type char. Without the
quotes, A would be an identifier and * would be a multiplication operator.
The quotes are not part of the value and are not stored in the variable; they
are just a convention for naming a particular character constant in a
program. If you want to store the character A in a variable ch of type char,
you could do so with the assignment statement
ch = 'A';
Certain special characters have special literals that use a backslash, \, as an
"escape character". In particular, a tab which is used to advance the cursor
to the next tab stop is represented as '\t', a carriage-return which is used
to move the output point back to the beginning of the line, without moving
down as '\r', a linefeed as '\n', the single quote character as '\'', and the
backslash itself as '\\'. Note that even though you type two characters
22
Session 2 : Data Types and Variables in Java
between the quotes in '\t', the value represented by this literal is a single tab
character.
For the type boolean, there are precisely two literals: true and false.
These literals are typed without quotes, but they represent values, not
variables. Boolean values occur most often as the values of conditional
expressions. For example,
rate > 0.05
is a boolean-valued expression that evaluates to true if the value of the
variable rate is greater than 0.05, and to false if the value of rate is not
greater than 0.05.
/**
* This class implements a simple program that
* will compute the amount of interest that is
* earned on $17,000 invested at an interest
* rate of 0.027 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {
public static void main(String[] args) {
/* Declare the variables. */
double principalInvesment;
double annualInterestRate;
double annualInterest;
/* Do the computations. */
principalInvesment = 17000;
annualInterestRate = 0.027;
annualInterest = principalInvesment * annualInterestRate;
principalInvesment = principalInvesment + annualInterest;
// Compute value of investment after one year, with
interest.
// (Note: The new value replaces the old value of
principal.)
/* Output the results. */
System.out.print("The interest earned is $");
System.out.println(interest);
System.out.print("The value of the investment after one year
is $");
System.out.println(principalInvesment);
} // end of main()
} // end of class Interest
24
Session 2 : Data Types and Variables in Java
There are two more variable types available excluding local variables,
instancevariables and static variables. You will be learning more details
about these types of variables in Session 5. Local variables are stored on
stack while instance and static variables are stored on the heap.
Summary
A language consists of words or tokens, a way of structuring the words, and
a set of rules to aid when interpreting the constructed words. Syntax is the
fragments of words or symbols constructs the program and semantic is the
grammar or the set of rules which is used to understand the meaning of the
set of coding fragments. When compiling the program, the compiler which
is a special program processes statements written using the programming
language and turns them in to the byte code. If there are syntax or semantic
errors the compiler will be notifying the programmer. Programmers should
be aware of the syntax and semantics of a programming language to write
error free programs.
Similarly, the programmers should adhere to naming guidelines as well as
the coding standards. For an example there are reserved words in any
programming language which cannot be used as identifiers. In Java a space
cannot be used when writing identifiers. It is a good practice if we can use a
meaningful name as an identifier whenever possible. There are plenty of
such naming guidelines in programming languages. Therefore, it is
necessary for you to notice, study and apply these guidelines in the
programs that you will be writing in the future.
A variable is a value that can change. A variable has a memory location to
store the value, a type of data stored in the memory location, and a name
used to refer to the memory location. The type of data allowing to store in a
variable is referred to as a data type. There are eight primitive data types in
Java. byte, short, int and long are used to store integers. float and double are
used to store floating point values. char data type is used to store characters
and boolean is used to store two logic values true and false. First a variable
25
Session 2 : Data Types and Variables in Java
should be declared, so that the memory for the variable will be allocated,
then a value can be assigned to these variables. The value stored in the
variable can be accessed as when required by referring to the name given for
the variable. If a new value is assigned to the variable, the existing value
will be replaced with the new value.
This session discussed the fundamentals of Java programming language
such as distinguishing syntax with semantics, introducing the terms
identifier, variable and data types, the importance of using naming
guidelines when declaring variables. Finally, the process of declaring a
variable, assigning values to declared variables were discussed.
Learning Outcomes
Now you will be able to
▪ Distinguish syntax with semantics of Java programming
language.
▪ Explain what a strongly typed language is
▪ Identify primitive data types in Java programming language
▪ Select appropriate data types to hold ranges of values in data
▪ Create variables and assign values to use later in a simple
program.
Review Questions
1. Where do you define local variables?
26