0% found this document useful (0 votes)
7 views30 pages

Introduction to Computer Programming

The document provides an introduction to computer programming, defining it as a sequence of instructions written in a programming language to perform specific tasks. It outlines the programming process, which includes defining the problem, planning the solution, coding, testing, and documenting the program. Additionally, it discusses programming languages, their paradigms, and provides examples of algorithms for temperature conversion and solving quadratic equations.

Uploaded by

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

Introduction to Computer Programming

The document provides an introduction to computer programming, defining it as a sequence of instructions written in a programming language to perform specific tasks. It outlines the programming process, which includes defining the problem, planning the solution, coding, testing, and documenting the program. Additionally, it discusses programming languages, their paradigms, and provides examples of algorithms for temperature conversion and solving quadratic equations.

Uploaded by

Tijjani Aminu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

FEDERAL UNIVERSITY GUSAU

DEPARTMENT OF COMPUTING

COS 201 COMPUTER PROGRAMMING I

Prepared by
Dr Samaila Musa Mafara

PART 1

INTRODUCTION TO COMPUTER PROGRAMMING


What is computer programs and what they do? A computer program is a sequence of
instructions written using a Computer Programming Language to perform a specified task by
the computer. The two important terms used in the above definition are:
• Sequence of instructions
• Computer Programming Language
To understand these terms, consider a situation when someone asks you about how to go to a
Federal University Gusau. What exactly do you do to tell him the way to go to Federal
University Gusau? You will use Human Language to tell the way to go to Federal
University Gusau, something as follows:

First go straight, after half kilometer, take left from the red light and then drive around one
kilometer and you will find Federal University Gusau at the right. Here, you have used
English Language to give several steps to be taken to reach Federal University Gusau. If
they are followed in the following sequence, then you will reach Federal University Gusau:

1. Go straight
2. Drive half kilometer
3. Take left
4. Drive around one kilometer
5. Search for Federal University Gusau at your right side

Now, try to map the situation with a computer program. The above sequence of instructions
is actually a Human Program written in English Language, which instructs on how to reach
Federal University Gusau from a given starting point. This same sequence could have been
given in Spanish, Hindi, Arabic, or any other human language, provided the person seeking
direction knows any of these languages. Now, let's go back and try to understand a computer
program, which is a sequence of instructions written in a Computer Language to perform a
specified task by the computer. Following is a simple program written in Python
Programming Language –
print "Hello, World!"
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 1
The above computer program instructs the computer to print "Hello, World!" on the
computer screen. A computer program is also called a computer software, which can range
from two lines to millions of lines of instructions.

• Computer program instructions are also called program source code and computer
programming is also called program coding.
• A computer without a computer program is just a dump box; it is programs that make
computers active.

Computer programming is the process that professionals use to write code that instructs how
a computer, application or software program performs. At its most basic, computer
programming is a set of instructions to facilitate specific actions. A programming
language is a computer language that is used by programmers (developers) to communicate
with computers. It is a set of instructions written in any specific language to perform a
specific task. It is made up of a series of symbols that serves as a bridge that allow humans to
translate our thoughts into instructions computers can understand. Human and machines
process information differently, and programming languages are the key to bridging the gap
between people and computers therefore the first computer programming language was
created.

Programming Language
A programming language is a language designed to communicate instructions to a computer.
They are used to create programs that control the behavior of a machine. A programming
language is a notation for writing programs, which are specifications of a computation or
algorithm. However, some authors restrict the term "programming language" to those
languages that can express all possible algorithms. Thus, Programming language is a set of
commands, strings or characters readable by programmers but easily translatable to machine
code. It has syntax, grammar, and semantics.
• Syntax is a set of rules that define how the commands have to be arranged to make
sense and to be correctly translatable to the machine code.
• Grammar is a set of rules of using different punctuation, quotation marks,
semicolons, and other symbols to divide and clarify the syntax of a particular
language.
• Semantics is a set of meanings assigned to every command of the language and is
used to properly translate the programme to machine code.

The Programming Process


Developing a program involves steps similar to any problem-solving task. There are five
main ingredients in the programming process:
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 2
1. Defining the problem
2. Planning the solution
3. Coding the program
4. Testing the program
5. Documenting the program

Defining the Problem


Suppose that, as a programmer, you are contacted because your services are needed. You
meet with users from the client organization to analyze the problem, or you meet with a
systems analyst who outlines the project. Specifically, the task of defining the problem
consists of identifying what it is you know (input-given data), and what it is you want to
obtain (output-the result). Eventually, you produce a written agreement that, among other
things, specifies the kind of input, processing, and output required.
Planning the solution
There are two (2) common ways of planning the solution to a problem which are drawing a
flowchart and writing pseudocode, or possibly both. A flowchart is a pictorial
representation of a step-by-step solution to a problem. It consists of arrows representing the
direction the program takes and boxes and other symbols representing actions. It is a map of
what your program is going to do and how it is going to do it. The American National
Standards Institute (ANSI) has developed a standard set of flowchart symbols. The Figure
below shows the symbols and how they might be used in a simple flowchart of a common
everyday problem that involves preparing a letter for mailing.

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 3


Figure 1: Sample Flowchart

A Pseudocode is an English-like nonstandard language that lets you state your solution with
more precision than you can in plain English but with less precision than is required when
using a formal programming language. Pseudocode permits you to focus on the program
logic without having to be concerned just yet about the precise syntax of a particular
programming language. However, pseudocode is not executable on the computer. We will
illustrate these later in this course, when we focus on language examples.

Coding the Program


As a programmer, your next step is to code the program-that is, to express your solution in a
programming language. You will translate the logic from the flowchart or pseudocode-or
some other tool-to a programming language. As we have already noted, a programming
language is a set of rules that provides a way of instructing the computer what operations to
perform. There are many programming languages: BASIC, COBOL, Pascal, FORTRAN, C,
Java, C++ and C are some examples.

Testing the Program


COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 4
Some experts insist that a well-designed program can be written correctly the first time. In
fact, they assert that there are mathematical ways to prove that a program is correct.
However, the imperfections of the world are still with us, so most programmers get used to
the idea that their newly written programs probably have a few errors. This is a bit
discouraging at first, since programmers tend to be precise, careful, detail-oriented people
who take pride in their work. Still, there are many opportunities to introduce mistakes into
programs, and you, just as those who have gone before you, will probably find several of
them. Eventually, after coding the program, you must prepare to test it on the computer.

Documenting the Program


Documenting is an ongoing, necessary process, although, as many programmers are, you
may be eager to pursue more exciting computer-centered activities. Documentation is a
written detailed description of the programming cycle and specific facts about the program.
Typical program documentation materials include the origin and nature of the problem, a
brief narrative description of the program, logic tools such as flowcharts and pseudocode,
data-record descriptions, program listings, and testing results. Comments in the program
itself are also considered an essential part of documentation. Many programmers document
as they code. In a broader sense, program documentation can be part of the documentation
for an entire system.

Example 1: Temperature conversion


Celsius (or centigrade) to Fahrenheit
Problem Statement: Write an algorithm of a program that converts temperature from
Celsius (or centigrade) to Fahrenheit. The program also output the equivalent temperature.
Problem Analysis: Given a temperature in one degree, the algorithm should convert it to
another degree by using the formula : F=(C * 5/9) +32.
Input: A temperature in Celsius (or centigrade).
Output: Equivalent temperature in Fahrenheit

The algorithm
1. Read the temperature given in degree Celsius.
2. Convert the temperature in Celsius to Fahrenheit using the formula: F=(C * 5/9) +32
3. Print the Fahrenheit value of the temperature.
4. End

Example 2: Fahrenheit to Celsius


Problem Statement: Write an algorithm of a program that converts temperature from
Fahrenheit to Celsius (or centigrade) to Fahrenheit. The program also output the equivalent
temperature.
Problem Analysis: Given a temperature in Fahrenheit degree, the algorithm should convert
it to Celsius degree by using the formula: C=5/9*(F-32).
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 5
Input: A temperature in Fahrenheit (or centigrade).
Output: Equivalent temperature in Celsius
The algorithm
1. Read the temperature given in degree Fahrenheit.
2. Convert the temperature in Fahrenheit into Celsius using the formula: C=5/9*(F-32)
3. Print the Celsius value of the temperature.
4. End

Try the following questions:


a. Calculating area of rectangle
Write an algorithm of a program that calculates area of a given the length and breadthof the
rectangle. The program output the area.

b. Calculating area of circle


Write an algorithm of a program that calculates area of a circle given the radius. The program
output the area

Example 3. Let’s consider a problem of writing a simple program that can solve quadratic
equation using general formulae i.e.

Defining the problem phase


We will start by breaking the problem into simpler sub problems. Solving quadratic equation
using general formulae can be broken into two by first calculating determinant (D) as
, then use it to determine the values of where if D = 0, then
have the same value which is , also if D > 0, then and
, and if D < 0 then have no solution because square root of
negative number result to a complex number.
We then identify input data, output and computations involves as follows:
Input data: Values of .
Output: Values of
Computations: , and
Planning the solution

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 6


We plan the solution first by drawing the flowchart as follows:

Figure 2: Flowchart solution of example 1.

Then we write the pseudocode (Algorithm) as follows:


Step 1: Input a, b & c
Step 2: Compute D (Determinant)
Step 3: if D is 0 then,
Compute X =
Print “X1 & X2 have the same solution” X
Else if D > 0 then,
Compute and .
Print x1 and x2
Else
Print “There is no solution”.

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 7


Example 4: Consider a problem of designing a program that receives C.A and Exam scores
of the students and determines whether students pass or fail base on their total score. The
total score is calculated as the sum of C.A and Exam scores.

Solution: We design the program by drawing a flowchart and write a pseudo code of the
problem solution as follows:

Figure 2: Flowchart solution of example 2.

Pseudocode:
Step 1: Input C.A & Exam
Step 2: Calculate the Total by summing C.A and Exam
Step 3: if Total is below 40
Print “FAIL”
else
Print “PASS”

Exercises
1. Write a pseudo code and draw a flowchart that will receives C.A and Exam scores of
the student and determines the grade of the student.
2. Write an algorithm and draw a flowchart that will read the two sides of a rectangle and
calculate its area

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 8


Overview of Main Programming Paradigm
There are four main programming paradigms which are imperative paradigm functional
paradigm, logical paradigm and object-oriented paradigm.
Imperative Paradigm
The imperative, also called the procedural programming paradigm expresses computation by
fully specified and controlled manipulation of named data in a stepwise fashion. In other
words, data or values are initially stored in variables (memory locations), taken out of (read
from) memory, manipulated in ALU (arithmetic logic unit), and then stored back in the same
or different variables (memory locations). Finally, the values of variables are sent to the I/O
devices as output. The foundation of imperative languages is the stored program concept-
based computer hardware organization and architecture (von Neumann machine). The stored
program concept will be further explained in the next chapter. Typical imperative
programming languages include all assembly languages and earlier high-level languages like
Fortran, Algol, Ada, Pascal, and C.
Object-Oriented Paradigm
The object-oriented programming paradigm is basically the same as the imperative paradigm,
except that related variables and operations on variables are organized into classes of objects.
The access privileges of variables and methods (operations) in objects can be defined to
reduce (simplify) the interaction among objects. Objects are considered the main building
blocks of programs, which support language features like inheritance, class hierarchy, and
polymorphism.
Typical object-oriented programming languages include Smalltalk, C++, Python, Java, and
C#.
Functional (Application) Paradigm
The functional, also called the applicative, programming paradigm expresses computation in
terms of mathematical functions. Since we express computation in mathematical functions in
many of the mathematics courses, functional programming is supposed to be easy to
understand and simple to use. However, programmers find it difficult to switch because they
are already familiar with the functional programming. The main difference is that there is no
concept of memory locations in functional programming languages. Each function will take a
number of values as input (parameters) and produce a single return value (output of the
function). The return value cannot be stored for later use. It has to be used either as the final
output or immediately as the parameter value of another function. Functional programming is
about defining functions and organizing the return values of one or more functions as the
parameters of another function. Functional programming languages are mainly based on the
lambda calculus that will be discussed in Chapter 4. Typical functional programming
Languages include ML, SML, and Lisp/Scheme. Python and C# support direct applications
of lambda calculus and many functional programming features.
Logic Paradigm
The logic, also called the declarative, programming paradigm expresses computation in terms
of logic predicates. A logic program is a set of facts, rules, and questions. The execution
process of a logic program is to compare a question to each fact and rule in the given fact and
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 9
rulebase. If the question finds a match, we receive a yes answer to the question. Otherwise,
we receive a no answer to the question. Logic programming is about finding facts, defining
rules based on the facts, and writing questions to express the problems we wish to solve.
Prolog is the only significant logic programming language.

OBJECT-ORIENTED LANGUAGE (JAVA)


Let's begin with a simple analogy to help you understand classes and their contents. Suppose
you want to drive a car and make it go faster by pressing down on its accelerator pedal. What
must happen before you can do this? Well, before you can drive a car, someone has to design
the car. A car typically begins as engineering drawings, similar to the blueprints used to
design a house.
These engineering drawings include the design for an accelerator pedal to make the car go
faster. The pedal "hides" the complex mechanisms that actually make the car go faster, just as
the brake pedal "hides" the mechanisms that slow the car and the steering wheel "hides" the
mechanisms that turn the car. This enables people with little or no knowledge of how engines
work to drive a car easily.
Unfortunately, you cannot drive the engineering drawings of a car. Before you can drive a
car, the car must be built from the engineering drawings that describe it. A completed car
will have an actual accelerator pedal to make the car go faster, but even that's not enough the
car will not accelerate on its own, so the driver must press the accelerator pedal.
Now let's use our car example to introduce the key programming concepts of this section.
Performing a task in a program requires a method. The method describes the mechanisms
that actually perform its tasks. The method hides from its user the complex tasks that it
performs, just as the accelerator pedal of a car hides from the driver the complex mechanisms
of making the car go faster. In Java, we begin by creating a program unit called a class to
house a method, just as a car's engineering drawings house the design of an accelerator pedal.
In a class, you provide one or more methods that are designed to perform the class's tasks.
For example, a class that represents a bank account might contain one method to deposit
money to an account, another to withdraw money from an account and a third to inquire what
the current balance is.
Just as you cannot drive an engineering drawing of a car, you cannot "drive" a class. Just as
someone has to build a car from its engineering drawings before you can actually drive a car,
you must build an object of a class before you can get a program to perform the tasks the
class describes how to do. That is one reason Java is known as an object-oriented
programming language.
When you drive a car, pressing its gas pedal sends a message to the car to perform a task that
is, make the car go faster. Similarly, you send messages to an object each message is known
as a method call and tells a method of the object to perform its task.
Thus far, we have used the car analogy to introduce classes, objects and methods. In addition
to the capabilities a car provides, it also has many attributes, such as its color, the number of
doors, the amount of gas in its tank, its current speed and its total miles driven (i.e., its
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 10
odometer reading). Like the car's capabilities, these attributes are represented as part of a
car's design in its engineering diagrams. As you drive a car, these attributes are always
associated with the car.
Every car maintains its own attributes. For example, each car knows how much gas is in its
own gas tank, but not how much is in the tanks of other cars. Similarly, an object has
attributes that are carried with the object as it is used in a program. These attributes are
specified as part of the object's class. For example, a bank account object has a balance
attribute that represents the amount of money in the account. Each bank account object
knows the balance in the account it represents, but not the balances of the other accounts in
the bank. Attributes are specified by the class's instance variables.

Object
An object is a real-world element in an object–oriented environment that may have a
physical or a conceptual existence. Each object has −
 Identity that distinguishes it from other objects in the system.
 State that determines characteristic properties of an object as well as values of
properties that the object holds.
 Behavior that represents externally visible activities performed by an object in terms
of changes in its state.
Objects can be modeled according to the needs of the application. An object may have a
physical existence, like a customer, a car, etc.; or an intangible conceptual existence, like a
project, a process, etc.
Class
A class represents a collection of objects having same characteristic properties that exhibit
common behavior. It gives the blueprint or the description of the objects that can be created
from it. Creation of an object as a member of a class is called instantiation. Thus, an object
is an instance of a class.
The constituents of a class are −
 A set of attributes for the objects that are to be instantiated from the class. Generally,
different objects of a class have some difference in the values of the attributes.
Attributes are often referred as class data.
 A set of operations that portray the behavior of the objects of the class. Operations are
also referred as functions or methods.
Example
Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–
dimensional space. The attributes of this class can be identified as follows −
 x–coord, to denote x–coordinate of the center
 y–coord, to denote y–coordinate of the center
 r, to denote the radius of the circle
Some of its operations can be defined as follows −
 findArea(), a method to calculate area
 findCircumference(), a method to calculate circumference
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 11
 scale(), a method to increase or decrease the radius

Inheritance
It is a mechanism that permits new classes to be created out of existing classes by extending
and refining its capabilities. The existing classes are called the base classes/parent
classes/super-classes, and the new classes are called the derived classes/child
classes/subclasses.
The subclass can inherit or derive the attributes and methods of the super-class (es) provided
that the super-class allows so. Besides, the subclass may add its own attributes and methods
and may modify any of the super-class methods. Inheritance defines a “is – a” relationship.
Example
From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow,
etc. Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In
addition, each has its own particular characteristics. It can be said that a cow “is – a”
mammal.

Polymorphism
Polymorphism is originally a Greek word that means the ability to take multiple forms. In
object-oriented paradigm, polymorphism implies using operations in different ways,
depending upon the instances they are operating upon. Polymorphism allows objects with
different internal structures to have a common external interface. Polymorphism is
particularly effective while implementing inheritance.
Example
Let us consider two classes, Circle and Square, each with a method findArea(). Though the
name and purpose of the methods in the classes are same, the internal implementation, i.e.,
the procedure of calculating an area is different for each class. When an object of class
Circle invokes its findArea() method, the operation finds the area of the circle without any
conflict with the findArea() method of the Square class.

Tools for developing, Compiling, interpreting and debugging,


Software Development is a step-by-step structured process of creating, designing, building,
deploying, and maintaining a software application or product.
A Software Development Tool is an application or program which helps developers to create,
maintain, test, build, debug, fix and support a software application or product. Software
development tools also allow users to streamline and automate different software
development tasks in order to improve efficiency and performance.
Software Development Tools can be categorized into the following types:
• IDE (Integrated Development Environment) - Helps to edit, debug and run the
source code. Eg. NetBeans, Cloud9 IDE, Zend Studio, Atom, Spiralogics Application
Architecture, CodeCharge Studio

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 12


• Frameworks - Provides a platform to develop software applications. Eg. Bootstrap,
Expression Studio, HTML5 Builder, Visual Online
• Cloud Tools – Offers various software development services to build software
applications quickly and easily, eg. Kwatee, Azure
• Data Science Tools - Provides detailed analytics to improve software application
product. Eg. Data studio
• Source Control Tools - Offers easy management of source code for software
development projects. Eg. Github, BitBucket
• Prototyping Tools - Allows creating software prototypes. Eg. Axure
• DevOps Tools - Helps to manage and automate the software deployment process. Eg.
Codenvy
• UML Tools – Helps in software documentation. Eg. Enterprise Architect

First Java Program


Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
[Link]("Hello World"); // prints Hello World
}
}
Output
Hello World
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class name.

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 13


When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class
name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file
then file name can be different than class name. It is also not mandatory to have a
public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as '[Link]'
 public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers −
 Access Modifiers − default, public , protected, private
 Non-access Modifiers − final, abstract, strictfp

Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters
available inside any comment are ignored by Java compiler.
Example
public class MyFirstJavaProgram {
/* This is my first java program. This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
[Link]("Hello World");
}
}

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 14


Output
Hello World

Using Blank Lines


A line containing only white space, possibly with a comment, is known as a blank line, and
Java totally ignores it.

Java - Data Types


Data types define the type and value range of the data for the different types of variables,
constants, method parameters, returns type, etc. The data type tells the compiler about the
type of data to be stored and the required memory. To store and manipulate different types of
data, all variables must have specified data types.
Java data types are categorized into two parts −
 Primitive Data Types
 Reference/Object Data Types
Java Primitive Data Types
Primitive data types are predefined by the language and named by a keyword. There are eight
primitive data types supported by Java. Below is the list of the primitive data types:
 byte
 short
 int
 long
 float
 double
 boolean
Java byte Data Type
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an integer.
 Example − byte a = 100, byte b = -50
Java short Data Type
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
 Default value is 0.
 Example − short s = 10000, short r = -20000
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 15
Java int Data Type
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0
 Example − int a = 100000, int b = -200000
Java long Data Type
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example − long a = 100000L, long b = -200000L
Java float Data Type
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example − float f1 = 234.5f
Java double Data Type
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values, generally
the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example − double d1 = 123.4
Java boolean Data Type
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example − boolean one = true
Java char Data Type
 char data type is a single 16-bit Unicode character
 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example − char letterA = 'A'

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 16


Example: Demonstrating Different Primitive Data Types
Following examples shows the usage of variour primitive data types we've discussed above.
We've used add operations on numeric data types whereas boolean and char variables are
printed as such.
Open Compiler
public class JavaTester {
public static void main(String args[]) {

byte byteValue1 = 2;
byte byteValue2 = 4;
byte byteResult = (byte)(byteValue1 + byteValue2);

[Link]("Byte: " + byteResult);

short shortValue1 = 2;
short shortValue2 = 4;
short shortResult = (short)(shortValue1 + shortValue2);

[Link]("Short: " + shortResult);

int intValue1 = 2;
int intValue2 = 4;
int intResult = intValue1 + intValue2;

[Link]("Int: " + intResult);

long longValue1 = 2L;


long longValue2 = 4L;
long longResult = longValue1 + longValue2;

[Link]("Long: " + longResult);

float floatValue1 = 2.0f;


float floatValue2 = 4.0f;
float floatResult = floatValue1 + floatValue2;

[Link]("Float: " + floatResult);

double doubleValue1 = 2.0;


double doubleValue2 = 4.0;
double doubleResult = doubleValue1 + doubleValue2;

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 17


[Link]("Double: " + doubleResult);

boolean booleanValue = true;

[Link]("Boolean: " + booleanValue);

char charValue = 'A';

[Link]("Char: " + charValue);


}
}
Output
Byte: 6
Short: 6
Int: 6
Long: 6
Float: 6.0
Double: 6.0
Boolean: true
Char: A

Java Reference/Object Data Type


The reference data types are created using defined constructors of the classes. They are used
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
Class objects and various types of array variables come under reference datatype. The default
value of any reference variable is null. A reference variable can be used to refer to any object
of the declared type or any compatible type.
Example
The following example demonstrates the reference (or, object) data types.
// Creating an object of 'Animal' class
Animal animal = new Animal("giraffe");

// Creating an object of 'String' class


String myString = new String("Hello, World!");

What is a Java Variable?


A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 18
Variable Declaration and Initialization
You must declare all variables before they can be used. Following is the basic form of a
variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's data types and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Example of Valid Variables Declarations and Initializations
Following are valid examples of variable declaration and initialization in Java −
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
Java Variables Types
The following are the three types of Java variables:
 Local variables
 Instance variables
 Class/Static variables
1. Java Local Variables
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
Example 1: Variable's local scope with initialization
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to only this method.
Open Compiler
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 19
}
}
Output
Puppy age is: 7
Example 2: Variable's local scope without initialization
Following example uses age without initializing it, so it would give an error at the time of
compilation.
Open Compiler
public class Test {
public void pupAge() {
int age;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Output
[Link]:variable number might not have been initialized
age = age + 7;
^
1 error

2. Java Instance Variables


 Instance variables are declared in a class, but outside a method, constructor or any
block.
 When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
 Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 20
 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned during
the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name. [Link].
Example of Java Instance Variables
Open Compiler
import [Link].*;

public class Employee {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
[Link]("name : " + name );
[Link]("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Samaila");
[Link](1000);
[Link]();
}
}
Output
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 21
name : Samaila
salary :1000.0

3. Java Class/Static Variables


 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally, values can be assigned in
special static initializer blocks.
 Static variables can be accessed by calling with the class
name [Link].
 When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.

Example of Java Class/Static Variables


Open Compiler
import [Link].*;

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 22
}
}
Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be accessed as
[Link]

Arithmetic Expressions
An assignment statement or expression changes the value that is held in a variable. Here is a
program that uses an assignment statement:

class example
{
public static void main ( String[] args )
{
long x ; //a declaration without an initial value

x = 123; //an assignment statement


[Link]("The variable x contains: " + x );
}
}

Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %. The %


operator is the remainder or modulo operator. Arithmetic expressions are used to assign
arithmetic values to variables. An expression is a combination of literals, operators, variables,
and parentheses used to calculate a value.

The following code describes the use of different arithmetic expressions.

int x, y, z; // Three integer variables declared at the same time.

x = 10;
y = 12;
z = y / x; // z is assigned the value of y divided by x.
// Here z will have value 1.

z = x + y; // z is assigned the value of x+y // Here z will have value 22.

z = y % x // z is assigned the value of remainder when y // is divided by x. Here z will have


value 2.

Java Boolean expressions are expressions which are either true or false. The different
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 23
boolean operators are < (less than), > (greater than), == (equal to), >= (greater or equal to),
<= (less or equal), != (not equal to).

Example:

int x = 10;
int y = 4;
int z = 5;

(x < 10) // This expression checks if x is less than 10.

(y > 1) // This expression checks if y is greater than 1.

((x - y) == (z + 1)); // This expression checks


// if (x - y) equals (z + 1).

A boolean expression can also be a combination of other boolean expressions. Two or more
boolean expressions can be connected using &&
(logical AND) and || (logical OR) operators.

The && operator represents logical AND. The expression is true only if both boolean
expressions are true. The || operator represents logical
OR. This expression would be true if any one of the associated expressions is true.

Example:

int x = 10; int y = 4; int z = 5;

(x <= 10) && (y > 1) // This expression checks if x is less


// than 10 AND y is greater than 1.
// This expression is TRUE.

(x*y == 41) || (z == 5) // This expression checks if x*y is equal


// to 40 OR if z is equal to 5.
// This expression is FALSE

Java - Basic Operators


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
 Arithmetic Operators
 Relational Operators
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 24
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −

Operator Description Example


+ (Addition) Adds values on either side of the operator. A + B will give 30
- (Subtraction) Subtracts right-hand operand from left-hand A - B will give -10
operand.
* Multiplies values on either side of the operator.
A * B will give
(Multiplication) 200
/ (Division) Divides left-hand operand by right-hand B / A will give 2
operand.
% (Modulus) Divides left-hand operand by right-hand B % A will give 0
operand and returns remainder.
++ (Increment) Increases the value of operand by 1. B++ gives 21
-- (Decrement) Decreases the value of operand by 1. B-- gives 19
The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example


== (equal to) Checks if the values of two operands are equal (A == B) is not
or not, if yes then condition becomes true. true.
!= (not equal Checks if the values of two operands are equal (A != B) is true.
to) or not, if values are not equal then condition
becomes true.
> (greater Checks if the value of left operand is greater (A > B) is not true.
than) than the value of right operand, if yes then
condition becomes true.
< (less than) Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= (greater Checks if the value of left operand is greater (A >= B) is not
than or equal than or equal to the value of right operand, if yes true.
to) then condition becomes true.
<= (less than Checks if the value of left operand is less than or (A <= B) is true.
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 25
or equal to) equal to the value of right operand, if yes then
condition becomes true.
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example


& (bitwise Binary AND Operator copies a bit to the (A & B) will give 12
and) result if it exists in both operands. which is 0000 1100
| (bitwise or)
Binary OR Operator copies a bit if it exists (A | B) will give 61
in either operand. which is 0011 1101
^ (bitwise Binary XOR Operator copies the bit if it is (A ^ B) will give 49
XOR) set in one operand but not both. which is 0011 0001
~ (bitwise Binary Ones Complement Operator is unary (~A ) will give -61 which
compliment) and has the effect of 'flipping' bits. is 1100 0011 in 2's
complement form due to
a signed binary number.
<< (left Binary Left Shift Operator. The left A << 2 will give 240
shift) operands value is moved left by the number which is 1111 0000
of bits specified by the right operand.
>> (right Binary Right Shift Operator. The left A >> 2 will give 15
shift) operands value is moved right by the which is 1111
number of bits specified by the right
operand.
>>> (zero Shift right zero fill operator. The left A >>>2 will give 15
fill right operands value is moved right by the which is 0000 1111
shift) number of bits specified by the right
operand and shifted values are filled up
with zeros.

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 26


The Logical Operators
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example


&& (logical and) Called Logical AND operator. If both the (A && B) is false
operands are non-zero, then the condition
becomes true.
|| (logical or) Called Logical OR Operator. If any of the two (A || B) is true
operands are non-zero, then the condition
becomes true.
! (logical not) Called Logical NOT Operator. Use to reverses !(A && B) is true
the logical state of its operand. If a condition is
true then Logical NOT operator will make
false.
The Assignment Operators
Following are the assignment operators supported by Java language −

Operator Description Example


= Simple assignment operator. Assigns values from C = A + B will
right side operands to left side operand. assign value of A
+ B into C
+= Add AND assignment operator. It adds right operand C += A is
to the left operand and assign the result to left equivalent to C =
operand. C+A
-= Subtract AND assignment operator. It subtracts right C -= A is
operand from the left operand and assign the result to equivalent to C =
left operand. C–A
*= Multiply AND assignment operator. It multiplies right C *= A is
operand with the left operand and assign the result to equivalent to C =
left operand. C*A
/= Divide AND assignment operator. It divides left C /= A is
operand with the right operand and assign the result to equivalent to C =
left operand. C/A
%= Modulus AND assignment operator. It takes modulus C %= A is
using two operands and assign the result to left equivalent to C =
operand. C%A
<<= Left shift AND assignment operator. C <<= 2 is same
as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same
as C = C >> 2
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 27
&= Bitwise AND assignment operator. C &= 2 is same
as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as
C=C^2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as
C=C|2
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Following is an example −
Example
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
[Link]( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
[Link]( "Value of b is : " + b );
}
}
This will produce the following result −
Output
Value of b is : 30
Value of b is : 20
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check
for the class/interface type on the right side, then the result will be true. Following is an
example −
Example
public class Test {
public static void main(String args[]) {

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 28


String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
[Link]( result );
}
}
This will produce the following result −
Output
true
This operator will still return true, if the object being compared is the assignment compatible
with the type on the right. Following is one more example −
Example
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]) {
Vehicle a = new Car();
boolean result = a instanceof Car;
[Link]( result );
}
}
This will produce the following result −
Output
true
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix expression++ expression-- Left to right
Unary ++expression –-expression +expression –expression Right to left
~!
Multiplicative * / % Left to right
Additive +- Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 29
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left

COS 201 Computer Programming I Part 1 of 3. FEDERAL UNIVERSITY GUSAU Page 30

Common questions

Powered by AI

Documentation provides a complete and structured overview of the program’s cycle, including problem origin, program logic, and testing results, which facilitates future maintenance and troubleshooting. Written details help other programmers understand functionality and design, ensuring continuity in development and ease in the implementation of updates .

Flowcharts provide a visual representation of the sequence and flow of operations needed to solve a problem, using symbols to denote actions and direction. Pseudocode, on the other hand, uses an English-like syntax to describe the logic of the program without worrying about the precise syntax of programming languages. Both tools allow programmers to conceptualize and plan the structure of the program before translating it into code .

Understanding object-oriented concepts allows developers to create modular, reusable, and extensible code. Classes act as blueprints for objects, encapsulating data and behavior, which supports complex interactions while maintaining simplicity and ease of updates, ensuring scalable software development .

Testing a program involves executing it to find errors or discrepancies against the intended functionality or requirements. Despite claims that a well-designed program can be correct initially, testing validates the code by revealing potential undetected errors, thus ensuring it performs as expected and meets user requirements .

Boolean expressions evaluate to true or false, enabling the control of program flow. Logical operators such as AND (&&) and OR (||) combine or evaluate multiple conditions to dictate branching and execution paths, thereby facilitating complex decision-making vital for dynamic program responses .

Programming languages translate human logic and problem-solving strategies into a form that computers can execute. The syntax, semantics, and grammar of programming languages enable this translation, bridging the gap between human conceptual thought processes and the binary logic of computers, allowing efficient and effective communication .

Defining the problem is crucial as it involves identifying the input data and specifying the required output, forming a foundation upon which the entire program will be developed. This stage helps in ensuring that the programmer and the client have a mutual understanding of the purpose and scope of the software. A written agreement is created to detail inputs, processing, and output, ultimately guiding the coding process .

Syntax defines the arrangement of commands to ensure they are interpretable by the machine; grammar involves rules for proper punctuation and symbol use, which clarifies syntax; semantics assigns meaning to commands, enabling accurate translation to machine code. Together, they ensure programming languages are comprehensible and effective in creating executable programs .

Operator precedence determines the order in which operations are evaluated in an expression. For example, multiplication has higher precedence and is computed before addition. This affects the final outcome of expressions; understanding it ensures correct and expected results in program execution .

Transitioning can be challenging because procedural programming focuses on sequences and state changes with memory locations, whereas functional programming is centered around mathematical functions without concepts of memory locations. Functions in functional programming take inputs and produce a return value, which must immediately be used in a function's execution, requiring a different thought process and application method .

You might also like