[go: up one dir, main page]

0% found this document useful (0 votes)
4 views14 pages

EEI3262 Unit 1 Session 2

Session 2 covers the fundamentals of data types and variables in Java, including syntax, semantics, naming guidelines, and the eight primitive data types. It emphasizes the importance of writing syntactically and semantically correct code, as well as understanding how to use variables and their types effectively. The session also explains the concept of variables as memory locations that can hold data and the rules governing their assignment and usage.

Uploaded by

udarasenu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

EEI3262 Unit 1 Session 2

Session 2 covers the fundamentals of data types and variables in Java, including syntax, semantics, naming guidelines, and the eight primitive data types. It emphasizes the importance of writing syntactically and semantically correct code, as well as understanding how to use variables and their types effectively. The session also explains the concept of variables as memory locations that can hold data and the rules governing their assignment and usage.

Uploaded by

udarasenu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Session 2 : Data Types and Variables in Java

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.

2.1 Syntax and Semantics in Java


A program can be syntactically and semantically correct but still be not a
good program. Using the language correctly is not the same as using it well.
For example, a good program has "style". It is written in a way that will

13
Session 2 : Data Types and Variables in Java

make it easier for programmers to read and understand. It follows


conventions that will be familiar to other programmers, and it has an overall
design that will make sense to human readers.
Whenever a new language feature is explained the syntax, the semantics and
some of the pragmatics of that feature will be discussed. You should
memorize the syntax. Then you should get a feeling for the semantics by
following the examples given, making sure that you understand how they
work, and, ideally, writing short programs of your own to test your
understanding.

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.

2.2 Naming guidelines in Java


In programs, names are used to refer different sorts of things. To use those
things, a programmer must understand the rules for giving names to them
and the rules for using the names to work with them. That is, the
programmer must understand the syntax and the semantics of names.

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 '_'.)

For example, here are some legal identifiers:


N nrate x15 quite_a_long_name HelloWorld
No spaces are allowed in identifiers; HelloWorldis a legal identifier, but
"Hello World" is not. Upper case and lower case letters are considered to be
different, so that HelloWorld,
helloworld,HELLOWORLDand hElloWorLD are all distinct names.
Certain words are reserved for special uses in Java, and cannot be used as
identifiers.
These reserved words include:
class, public, static, if, else, whileand several other words.

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();

Semicolon (;) represents the end of an expression or a statement. You will


be using this statement later in this course material to display or print a
given set of characters on the screen. The idea here is that, things in Java
can contain other things. A compound name is a kind of path to an item
15
Session 2 : Data Types and Variables in Java

through one or more levels of containment. The


name System.out.println indicates that something called "System"
contains something called "out" which in turn contains something called
"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

Figure 2.1 : Variable is a memory location holds data

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

Figure 2.2 : Assigning values to variables rate and principal

The variable in the first assignment statement is rate, and


the expression or data is the number 0.07. Similarly the variable in the
second assignment statement is principaland the data assigning to the
variable is 1000.This is illustrated in Fig. 2.2. The computer executes this
assignment statement by putting the number 0.07 in the variable rate,
replacing whatever was there before.
Now, consider the following more complicated assignment statement, which
might come later in the same program:
interest = rate * principal;
Here, the value of the expression "rate * principal" is being
assigned to the variable interest. In the expression, the * is a
"multiplication operator" that tells the computer to multiply rate times
principal. The names rate and principal are themselves
variables, and it is really the values stored in those variables that are to be
multiplied as shown in Fig. 2.3.

0.07 * 1000
interest

Figure 2.3 : Assigning rate * principal in to variable interest

We see that when a variable is used in an expression, it is the value stored in


the variable that matters; in this case, the variable seems to refer to the data
in the box, rather than to the box itself. When the computer executes this
assignment statement, it takes the value of rate, multiplies it by
the value of principal, and stores the answer in the box referred to
by interest. When a variable is used on the left hand side of an
assignment statement, it refers to the box that is named by the variable.
Within our program we can assign different values in to the variables
rateand principal.
rate = 14.4
principal = 500

17
Session 2 : Data Types and Variables in Java

when the computer executes the interest=rate * principal,


the value 70 will get replaced with value 7200, which is the multiplication
of the value in rate,14.4 and principal,500 as shown in Fig. 2.4.

Figure 2.4 : Values in rate, principal and interest get replaced


with new values.
When we assign values into variables we should ensure that we assign the
same type of values to the declared variables. To do that we should be aware
of the data types support by Java, this is explained in the next section.

2.4 Data Types


There are eight primitive types of data built into Java. A variable in Java is
designed to hold only one particular type of data. It can legally hold that
type of data and no other. The compiler will consider it to be a syntax error
if you try to violate this rule by assigning a variable of the wrong type to a
variable. We say that Java is a strongly typed language because it enforces
this rule.
The primitive types of data are named as given below .
byte float char boolean
short double
int
long

18
Session 2 : Data Types and Variables in Java

Seven primitive data types hold numeric values including characters,


integers and floating point values and Boolean data type holds boolean type
of values as shown in Fig. 2.5.

Figure 2.1: Primitive data types supported in Java Programming Language


 The first four types, byte, short, int and long hold integers. The
four integer types are distinguished by the ranges of integers they
can hold.
E.g. if we want to represent number of students, we can use int as the data
type
 The float and double typeshold real numbers such as 3.6
and -145.99. The two real types are distinguished by their
range and accuracy.
 A variable of type char holds a single character from the
Unicode character set.
E.g. if we want to assign grades as A, B, C, D, we can declare variables with
the data type char and assign values as given below.
char grade = ‘A’
 A variable of type boolean holds one of the two logical
valuetrueor false.

19
Session 2 : Data Types and Variables in Java

 Instructions and data need processing are stored in memory.


kAny data value stored in the computer's memory must be
represented as a binary number, that is as a string of zeros and
ones. A single zero or one is called a bit. A string of eight bits
is called a byte. Memory is usually measured in terms of bytes.
Not surprisingly, the byte data type refers to a single byte of
memory. A variable of type byte holds a string of eight bits,
which can represent any of the integers between -128 and 127,
inclusive.
 As for the other integer types, short corresponds to two bytes
(16 bits). Variables of type short have values in the range -
32768 to 32767.
 int corresponds to four bytes (32 bits). Variables of
type int have values in the range -2147483648 to 2147483647,
long correspond to eight bytes (64 bits). Variables of
type long have values in the range -9223372036854775808 to
9223372036854775807.
You don't have to remember these numbers, but they do give you
some idea of the size of integers that you can work with. Usually, for
representing integer data you should just stick to the int data type,
which is good enough for most purposes.
 The float data type is represented in four bytes of memory,
using a standard method for encoding real numbers. The
maximum value for a float is about 10 raised to the power 38.
A float can have about 7 significant digits (So that
32.3989231134 and 32.3989234399 would both have to be
rounded off to about 32.398923 in order to be stored in a
variableof type float). A double takes up 8 bytes, can range up to
about 10 to the power 308, and has about 15 significant digits.
Ordinarily, you should stick to the double type for real values.
 A variable of type char occupies two bytes in memory. The
value of a char variable is a single character such as A, *, x,
or a space character. The value can also be a special character
such a tab or a carriage return or one of the many Unicode
characters that come from different languages. Values of
type char are closely related to integer values, since a character
is actually stored as a 16-bit integer code number. In fact, we will
see that char in Java can actually be used like integers in
certain situations.
The details given above are summarized in the Table 2.1.

20
Session 2 : Data Types and Variables in Java

Table 2.1: Primitive data types supported in Java programming language

Type Bits Bytes Min Max Default

byte 8 1 -28-1 28-1-1 0

short 16 2 -216-1 216-1-1 0

int 32 4 -232-1 232-1-1 0

long 64 8 -264-1 264-1-1 0

float 32 4 >NA NA 0.0f

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.

Activity 2.1: Identify Data Types

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

Signedness is a property of data types. A numeric variable is signed if it can represent


bothpositive and negative numbers, and unsigned if it can only
represent nonnegative numbers.

Activity 2.2: Identify Data Types

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.

2.6 Variables in a Java program


You learnt how to name the variables in the section 2.3. A variable can be
used in a program only if it has first been declared. A variable declaration
statement is used to declare one or more variables and to give them names.
When the computer executes a variable declaration, it sets aside memory for
the variable and associates the variable's name with that memory. A simple
variable declaration takes the form of:
type-name variable-name-or-names;

The variable-name-or-names can be a single variable name or a list of


variable names separated by commas. Good programming style is to declare
only one variable in a declaration statement, unless the variables are closely
related in some way.
For example:
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;
It is encouraged to use descriptive variable names, instead of using, x, y, i
etc. so that it is not required you to type lengthy comments explaining why
the variable is for.
We will only use variables declared inside the main() subroutine of a
program in this section. The main() subroutine will be further discussed in
a later session. Variables declared inside a subroutine are called local
variables for that subroutine. They exist only inside the subroutine,
while it is running, and are completely inaccessible from outside. Variable
declarations can occur anywhere inside the subroutine, as long as each
variable is declared before it is used in any way. Some people like to declare
all the variables at the beginning of the subroutine. Others like to wait to
declare a variable until it is needed. Here in this example declaring of
23
Session 2 : Data Types and Variables in Java

variables are done at the beginning of the subroutine. Declare "utility


variables" which are not important to the overall logic of the subroutine at
the point in the subroutine where they are first used. Here is a simple
program using some variables and assignment statements:

/**
* 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

This program uses several subroutines call statements to display information


to the user of the program. At this point you will not be able to compile and
execute the program. We expect you to notice how the variables are
declared, values are assigned and how the assigned values are being used.

24
Session 2 : Data Types and Variables in Java

Activity 2.2: Declaring and Assigning Values to Variables

Declare an integer sum


Declare a character letter
Declare a variable money which can be used to hold currency
Declare a variable arctan which will hold scientific notation values (+e)
Declare an integer variable called total and initialize it to zero.
Declare a variable loop, which can hold an integer value.

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?

2. Complete the Java program written below as given in the comments.

3. State the differences of the following:


a. syntax and semantics
b. strongly typed language and weakly
typed language
c. float and double

26

You might also like