CSE102 - Week2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

Federal University Dutse

Faculty of Computing
Department of Computer Science

CSE 102
PRINCIPLES OF PROGRAMMING

Week 2 Lecture Slides2023/2024


INTRODUCTION
 At the foundation of any programming
language are its data types and operators, and
Java is no exception.

 Theseelements define the limits of a language


and determine the kind of tasks to which it can
be applied.

 Javasupports a rich assortment of both data


types and operators, making it suitable for any
Java’s Primitive Type
 Java contains two general categories of built-
in data types
 Object-Oriented: object-oriented types are

defined by classes
 Non-Object oriented: eight primitive (also

called elemental or simple) types of data

 The term primitive is used here to indicate


that these types are not objects in an object-
oriented sense, but rather, normal binary
 Allof Java’s other data types are constructed
from these primitive types.

 Java strictly specifies a range and behavior for


each primitive type, which all implementations of
the Java Virtual Machine must support

 For example, an int is the same in all execution


environments.
 This allows programs to be fully portable. There

is no need to rewrite code to fit a specific


platform.
Type Meaning
Boolean Represent true/false values
Byte 8-bit of integer
Char Character
double Double- precision floating point
Float Single-precision floating point
int Integer
long Long integer
Short Short integer
Integer
 Java defines four integer types: byte,
short, int, and long, which are shown
here:
Type Width in bits ranges

Byte 8 –128 to 127

Short 16 –32,768 to 32,767

int 32 –2,147,483,648 to
2,147,483,647
Long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
 The most commonly used integer type is
int.
 Variables of type int are often employed to

control loops, to index arrays, and to


perform general-purpose integer math.
 When you need an integer that has a range

greater than int, use long.


 For example, here is a program that

computes the number of cubic inches


contained in a cube that is one mile by one
mile, by one mile:
/*
Compute the number of cubic inches
in 1 cubic mile.
*/
class Inches {
public static void main(String args[]) {
long ci;
long im;
im = 5280 * 12;
ci = im * im * im;
System.out.println("There are " + ci +
" cubic inches in cubic mile.");
}
}
 Clearly, the result could not have been held
in an int variable.
 The smallest integer type is byte.

 Variables of type byte are especially useful


when working with raw binary data that
may not be directly compatible with Java’s
other built-in types.

 The short type creates a short integer that


has its high-order byte first.
Floating-Point Types
 the floating-point types can represent numbers
that have fractional components.
 There are two kinds of floating-point types, float and
double, which represent single-precision and double-
precision numbers, respectively.
 Type float is 32 bits wide and type double is 64 bits

wide.
 double is the most commonly used because all of the

math functions in Java’s class library use double values


.For example, the sqrt( ) method (which is
defined by the standard Math class) returns
a double value that is the square root of its
double argument.

 Here,sqrt( ) is used to compute Square root


of a number supplied as argument.
/*
Use the Pythagorean theorem to
find the length of the hypotenuse
given the lengths of the two opposing
sides.
*/
class Hypot {
public static void main(String args[]) {
double x, y, z;
x = 3;
y = 4;
z = Math.sqrt(x*x + y*y);
System.out.println("Hypotenuse is " +z);
}
Characters
A character variable can be assigned a value by
enclosing the character in single quotes.
 For example, this assigns the variable ch the
letter X:
 char ch;
 ch = 'X';

 You can output a char value using a println( )


statement. For example, this line outputs the
value in ch:
 System.out.println("This is ch: " + ch);
consider the following program:
// Character variables can be handled like
integers.
class CharArithDemo {
public static void main(String args[]) {
char ch;
ch = 'X';
System.out.println("ch contains " + ch);
ch++; // increment ch
System.out.println("ch is now " + ch);
ch = 90; // give ch the value Z
System.out.println("ch is now " + ch);
}
}
The Boolean Type
 The boolean type represents true/false values.
 Java defines the values true and false using

the reserved words true and false.


 Thus, a variable or expression of type boolean

will be one of these two values.


 Here is a program that demonstrates the boolean
type:
// Demonstrate boolean values.
class BoolDemo {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
 There are three interesting things to notice about
this program. First, as you can see, when a
boolean value is output by println( ), “true” or
“false” is displayed.

 Second, the value of a boolean variable is


sufficient, by itself, to control the if statement.
There is no need to write an if statement like this:
 if(b == true) ...

 Third,the outcome of a relational operator, such


as <, is a boolean value. This is why the
expression 10 > 9 displays the value “true.
Literals
 In Java, literals refer to fixed values that are
represented in their human-readable form.
 For example, the number 100 is a literal. Literals

are also commonly called constants


 Java literals can be of any of the primitive data

types.
 The way each literal is represented depends upon

its type.
 As explained earlier, character constants are

enclosed in single quotes. For example, 'a' and ' %'


are both character constants.
 Integerconstants are specified as
numbers without fractional
components.

 Forexample, 10 and –100 are integer


constants.

 Floating-pointconstants require the


use of the decimal point followed by
the number’s fractional component.

 For
example, 11.123 is a floating-point
constant.
 By default, integer literals are of type
int.

 If
you want to specify a long literal,
append an l or an L.

 Forexample, 12 is an int, but 12L is a


long. By default, floating-point literals
are of type double.

 To specify a float literal, append an F or


f to the constant.
 Although integer literals create an int
value by default

 they can still be assigned to variables


of type char, byte, or short as long as
the value being assigned can be
represented by the target type.

 An integer literal can always be


assigned to a long variable.
String Literals
 Javasupports one other type of literal:
the string.

A string is a set of characters enclosed


by double quotes. For example,
 "this is a test“
 is a string. You have seen examples of

strings in many of the println( )


statements in the preceding sample
programs.
 In addition to normal characters, a
string literal can also contain one or
more of the escape sequences just
described.

 Forexample, consider the following


program. It uses the \n and \t escape
sequences.
// Demonstrate escape sequences in strings.
class StrDemo {
public static void main(String args[]) {
System.out.println("First line\nSecond line");
System.out.println("A\tB\tC");
System.out.println("D\tE\tF") ;
}
}
 Notice how the \n escape sequence is used to

generate a new line. You don’t need to use multiple


println( ) statements to get multiline output. Just
embed \n within a longer string at the points where
you want the new lines to occur.
 Table below shows the escape sequence
character in java.
Escape Description
sequence
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n Newline
\f Form feed
\t Horizontal tab
\b Backspace
Dynamic Initialization
 Although the preceding examples have used only
constants as initializers, Java allows variables to be
initialized dynamically, using any expression valid at
the time the variable is declared.

 For example, here is a short program that computes


the volume of a cylinder given the radius of its base
and its height:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double radius = 4, height = 5;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
System.out.println("Volume is " + volume);
}
}
 Here, three local variables—radius, height,
and volume—are declared.

 The first two, radius and height, are initialized


by constants.

 However, volume is initialized dynamically to


the volume of the cylinder.

 The key point here is that the initialization


expression can use any element valid at the
time of the initialization, including calls to
methods, other variables, or literals.
The Scope and Lifetime of
Variables
 So far, all of the variables that we have been
using were declared at the start of the main( )
method.

 However, Java allows variables to be declared


within any block.

 As explained in week 1, a block is begun with


an opening curly brace and ended by a closing
curly brace.

 A block defines a scope. Thus, each time you


start a new block, you are creating a new
 A scope determines what objects are visible to
other parts of your program.

 It also determines the lifetime of those objects.


Most other computer languages define two
general categories of scopes: global and local.

 Although supported by Java, these are not the


best ways to categorize Java’s scopes.

 The most important scopes in Java are those
defined by a class and those defined by a
method.
 The scope defined by a method begins with its
opening curly brace.

 However, if that method has parameters, they too


are included within the method’s scope.

 As a general rule, variables declared inside a scope


are not visible (that is, accessible) to code that is
defined outside that scope.

 Thus, when you declare a variable within a scope,


you are localizing that variable and protecting it
from unauthorized access and/or modification.

 Indeed, the scope rules provide the foundation for


encapsulation.
 Scopes can be nested. For example, each time
you create a block of code, you are creating a
new, nested scope.
 When this occurs, the outer scope encloses the

inner scope.

 This means that objects declared in the outer


scope will be visible to code within the inner
scope.

 However, the reverse is not true. Objects


declared within the inner scope will not be
visible outside it.
To understand the effect of nested scopes, consider the
following program:
// Demonstrate block scope.
class ScopeDemo {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Lab Exercises
 Q1. Write four different Java statements that each
add 1 to integer variable x.
 Q2. Write Java statements to accomplish each of
the following tasks:
 a) Assign the sum of x and y to z, and increment
the value of x by 1 after the calculation. Use only
one statement.
 b) Test if the value of the variable count is greater
than 10. If it is, print "Count is greater than 10".
 c) Decrement the variable x by 1, and then
subtract it from the variable total. Use only one
statement.
 d) Calculate the remainder after q is divided by
divisor, and assign the result to q. Write this
statement in two different ways.
 Q3. Write a Java statement to accomplish
each of the following tasks:
 a) Declare variables sum and x to be of

type int.
 b) Assign 1 to variable x.
 c) Assign 0 to variable sum.
 d) Add variable x to variable sum, and

assign the result to variable sum.


 e) Print "The sum is: ", followed by the

value of variable sum.

You might also like