0% found this document useful (0 votes)
646 views

Csc201 Introduction To Programming Csc201 Futo 2020

Uploaded by

Joy Sunday
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
646 views

Csc201 Introduction To Programming Csc201 Futo 2020

Uploaded by

Joy Sunday
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

CHAPTER TEN

INTRODUCTION TO PROGRAMMING
Programming Errors
1. Syntax Error: Grammatical error or the set of rules that governs the structure and
meaning of statements in a program.
2. Semantic error: Meaningless program e.g division by zero or incorrect use of
brackets
3. Logic error: incorrect use of a token or keyword or operator e.g using = instead of
==
4. Compile time error: syntax and semantic error during compilation
5. Run time error: error during execution of program

Variable: A variable is a named location in memory used to hold data items of a


particular type. You can declare a variable by specifying the data type and a name that
serves as a unique identifier for the variable. Once a variable is declared, you need to
assign a value to it; if you do not assign a value, the variable will receive a default value
based on its data type.

Example: Given the code,


int salary = 2000;

Types of Variables: Java provides you with three types of variables.


1. Local Variables that are declared inside a method, block, or constructor. They are
available for use only within the method, block, or constructor in which they are defined.
2. Instance Variables that are unique to each instance of a class. Instance variables
are declared inside a class, but outside any methods. Instance variables are initialized
only when the class is instantiated
3. Class Variables that are associated with a class. These variables are also referred
to as static variables. They are declared using the static keyword.

Constants: A constant is a named location in memory that stores a fixed value. Unlike a
variable, the value of a constant cannot be changed during program execution. In Java,
you use the final keyword to declare a constant. Although you can use a variable instead
of a constant, the compiler will not permit you to inadvertently change the value of a
constant. For instance, given the code,

Operators: Operators refer to symbols that have a specific meaning. They are used to
define the kind of mathematical or logical operation performed on one or more operands.

The most common operators used to create expressions are arithmetic, relational, and
logical.

Download more at Learnclax.com


1. Arithmetic operators are symbols used to perform basic arithmetic operations.
They are also called binary operators. Arithmetic operators can be applied to both
numbers and characters.

Java provides various arithmetic operators (+, -, *, /, %)

2. Relational operators are symbols used to make comparisons between operands and
return a boolean value depending on the result of the comparison. Expressions that are
created using these operators are called relational expressions. Only numeric values are
compared using these operators. Relational operators have lower precedence than
arithmetic operators.

Java provides several relational operators.


1. < Less than
2. <= Less than or equal to
3. > Greater than
4. >= Greater than or equal to
5. == Equal to
6. != Not equal to

3. Logical Operators: Logical operators are operators used to combine expressions


that return a Boolean value and to determine whether the resulting expression is true or
false. Example
1. The AND operator
2. The OR operator
3. The NOT operator

Install the Java Runtime Environment


1. Download the Java Runtime Environment (JRE) from http://www.oracle.com/
technetwork/java/javase/downloads/index.html

2. Run the executable file for JRE 7.

3. In the Open File - Security Warning dialog box, click Run.

4. On the Java Setup - Welcome page, click Install.

5. After the installation is complete, in the Java Setup - Complete dialog box, click
Close.

Install Java™ SE Development Kit 7


1. Download the Java™ SE Development Kit 7 from
http://www.oracle.com/technetwork/java/javase/downloads/index.html

Download more at Learnclax.com


2. Run the executable file for JDK 1.7.

3. In the Open File - Security Warning dialog box, click Run.

4. On the Java (TM) SE Development Kit 7 Update 1 (64-bit) – Setup page, click
Next.

5. On the Java (TM) SE Development Kit 7 Update 1 (64-bit) – Custom Setup


page, verify that the Development Tools option is selected and click Next.

6. After the installation is complete, on the Java (TM) SE Development Kit 7


Update 1 (64-bit) – Complete page, click Finish.to complete the wizard.

Overview of Programming:
1. Program: is a collection of ordered instructions that directs a computer to perform
a specific task. The instructions in a program are written using a programming language
and are later converted into a machine language that can be processed by a computer.

2. Programming Languages: A programming language is a mode of


communication used to communicate with a computer. It is used to write a set of
instructions understandable by the computer that enables users to achieve the desired
output.

3 Types of Flow Controls / Control Statements


The flow of program execution in structured programming is governed by three types of
flow controls.
i. Sequential Instructions are executed in sequence from top to bottom of the
program. ie Line by line program execution
ii. Conditional: Statement blocks are executed depending on the result of the
conditions specified. ie it alters the flow of a program based on certain
condition. The conditions are specified using conditional statements such as
if...else and switch...case.
iii. Iterative: A block of code is executed repetitively until the specified condition
is true. The condition is specified using keywords such as for, while, and
do...while.

The Java Platform Process


All programs developed using the Java programming language go through the Java
platform process. The Java platform process consists of five phases: edit, compile, load,
verify, and interpret.
1. In the edit phase: programmers use a text editor to write, edit, and save their
source code.

Download more at Learnclax.com


2. In the compile phase: the Java source code is translated into an intermediate Java
bytecode using the Java compiler.
3. In the load phase: the class loader uses the compiled file and transfers the bytecode
into the computer’s primary memory.
4. In the verify phase: the bytecode contained within the compiled file is validated.
5. In the interpret phase: the Java Virtual Machine interprets the bytecode and
executes the program.

The Java Virtual Machine


The Java Virtual Machine (JVM) is an application that simulates a virtual machine
environment for interpreting Java bytecode files. The Java bytecode is standardized
across all machines, so that compiled Java programs can be run on any machine that has
the JVM installed. This feature of Java is known as portability.

Create a source Code: Enter the following source codes using a programming text
editor (such as TextPad or NotePad++ for Windows

Example 1: Write your First Hello-world Java Program


1. /*
2. * First Java program, which says "Hello, world!"
3. */
4. public class Hello { // Save as "Hello.java"
5. public static void main(String[] args) {
6. System.out.println("Hello, world!"); // print message
7. }

8. }

Brief Explanation of the Program


/* ...... */
// ... until the end of the line
These are called comments. Comments are NOT executable and are ignored by the
compiler. But they provide useful explanation and documentation to your readers. There
are two kinds of comments:
1. Multi-line Comment: begins with /* and ends with */, and may span more than
one lines (as in Lines 1-3).
2. End-of-line Comment: begins with // and lasts until the end of the current line
(as in Lines 4 and 6).
public class Hello { ...... }

Download more at Learnclax.com


The basic unit of a Java program is a class. A class called "Hello" is defined via the
keyword "class" in Lines 4-8. The {...} is the body of the class. The keyword public will
be discussed later.

In Java, the name of the source file must be the same as the name of the public class with
a mandatory file extension of ".java". Hence, this file MUST be saved as "Hello.java".
public static void main(String[] args) { ...... }
Lines 5-7 defines the so-called main() method, which is the starting point, or entry point
for program execution. The {...} is the body of the method which contains programming
statements.
System.out.println("Hello, world!");
In Line 6, the statement System.out.println ("Hello, world!") is used to print the message
string "Hello, world!" to the display console. A string is surrounded by a pair of double
quotes and contain texts. The text will be printed as it is, without the double quotes

Do not enter the line numbers (on the left panel), which were added to help in the
explanation. Save the source file as "Hello.java". A Java source file should be saved with
a file extension of ".java". The filename shall be the same as the classname - in this case
"Hello".

Compile the Source file into class file:


To compile source code from a shell prompt, run the compiler with:
javac name.java
The Java compiler (javac) will create a byte-code file named:
name.class

If a Java development environment is being used, the program is compiled by invoking a menu
function rather than by running Java directly. The folder containing javac must be in the
programmer’s PATH environment variable.

Example 2:
To compile HelloWorld.java, type:
javac HelloWorld.java

This creates a file named HelloWorld.class.


If the source code file contains more than one class, the Java compiler will create a separate byte-
code file for each class

To Run the Program:


Run the program using Java Virtual Machine to run your application
java name

Download more at Learnclax.com


Example 3:
You run by issuing this command
prompt> java Hello
Hello, world!

Create a source file: This means to save.


public class Classname { // Choose a meaningful Classname. Save as "Classname.java"
public static void main(String[] args) {
// Your programming statements here!
}

System.out.println() vs. System.out.print()


The System.out.println() method displays an output and the cursor moves to a new line
before any other print statement is encountered.

The System.out.print() method displays an output and the cursor remains in the same line.
The output of the following print statement is displayed in the same line.

Example 4:
/* Test System.out.println() and System.out.print() */
public class PrintTest { // Save as "PrintTest.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // Advance the cursor to the beginning of next
line after printing
System.out.println(); // Print a empty line
System.out.print("Hello, world!"); // Cursor stayed after the printed string
System.out.println("Hello,");
System.out.print(" "); // Print a space
System.out.print("world!");
System.out.println("Hello, world!");
}
}

Output
Hello, world!
Hello, world! Hello,
world! Hello, world!

Download more at Learnclax.com


.
Example 5: Write a program to add five integers:
/*
* Sum five numbers and print the result
*/
public class FiveNumberSum { // Save as "FiveNumberSum.java"
public static void main(String[] args) {
int number1 = 11; // Declare 5 int variables to hold 5 integers
int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;
int sum; // Declare an int variable called sum to hold the sum
sum = number1 + number2 + number3 + number4 + number5;
System.out.print("The sum is "); // Print a descriptive string
System.out.println(sum); // Print the value stored in sum
}
}

Output
The sum is 165

int number1 = 11;


int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;

Example: Write a program that prints the area and circumference of a circle, given its
radius.
/*
* Print the area and circumference of a circle, given its radius.
*/
public class CircleComputation { // Saved as "CircleComputation.java"
public static void main(String[] args) {
// Declare variables
double radius, area, circumference;
final double PI = 3.14159265;

// Assign a value to radius


radius = 1.2;

Download more at Learnclax.com


// Compute area and circumference
area = radius * radius * PI;
circumference = 2.0 * radius * PI;

// Print results
System.out.print("The radius is "); // Print description
System.out.println(radius); // Print the value stored in the variable
System.out.print("The area is ");
System.out.println(area);
System.out.print("The circumference is ");
System.out.println(circumference);
}

Properties of the Java Language


Some of the most important properties of Java are its
1. Object orientation
2. Simplicity
3. Automatic garbage collection
4. Portability
5. Multi-threaded programming
6. Security
7. Internet awareness

Control Flow Statements


A control flow statement is a statement used to determine the flow of execution of code
based on specific conditions. It comprises two major types: conditional statements and
loops.

Conditional statements allow you to selectively execute different blocks of code


depending on the result of a test condition while Looping statements allow you to execute
a block of code repeatedly until a specified condition is true.

Example:
1. If Statement: If statement is a control flow statement that is used to execute a
block of code depending on the result of a test expression. You can create an if statement
using the if keyword followed by the test condition within parentheses. The statements to
be executed when the specified condition is true are enclosed within braces following the
if statement.

Download more at Learnclax.com


If the condition returns true, the action statements are executed. When the condition
returns false, the statements within the if block are skipped and the program execution is
passed to the statement following the if block.

Example: Syntax: (The if Statement) The syntax used to create an if statement is:
if (test expression) {
//...action statements
}
Class myclass {
Public static void main {string args[]} {
int salary = 3750
If {salary = 2500} {
System.out.printIn(“salary is greater than 2500”);
Salary = salary + (0.05*salary);
}
System.out.printIn(“salary;” +salary);
}
}

2. If...else Statement: If...else statement is a control flow statement that is used to


execute one of two blocks of code depending on the result of a test expression. If...else
block starts with an if keyword followed by the test expression in parentheses. The action
statements to be executed when the test expression returns true are enclosed in the if
block. The else block follows the if block and is created using the else keyword.

The action statements to be executed when the test expression returns false are enclosed
in the else block. If the test condition returns true, the statements in the if block are
executed. If the test condition returns false, the statements in the else block are executed.

Example: Syntax: (The if...else Statement)


The syntax used to create an if...else statements is:

if (test expression) {
//...action statements to execute when the test expression
returns true
} else
{
//...action statements to execute when the test expression
returns false
}

Class myclass {
Public static void main {string args[] {

Download more at Learnclax.com


Int salary = 1750
If (salary > 2500) {
System.out.printIn(“salary is greater than 2500”);
Salary = salary + (0.03*salary);
} else {
System.out.printIn(“salary is less than 2500”);
Salary = salary + (0.05*salary);
}
System.out.printin(“salary;” + salary);
{
{

3. The switch Statement: A switch statement is a program flow control statement


that uses a single test condition to determine one among multiple program paths based on
the outcome of the test expression. The switch block is declared using the switch
keyword followed by a test expression enclosed in parentheses. The constant values to be
compared with the result of the test condition are specified within the switch block using
a case statement each for a constant value.

The action statements to be executed when the result of the test condition matches the
constant value follow the case statements. Each case statement has an optional break
statement that moves the control of the program execution to the statement following the
switch block. The switch block also has a default statement that contains the code to be
executed when the result of the test condition does not match with any of the constant
values specified in the case statements.

Example: Syntax: (The switch Statement)


The syntax used to create a switch statement is
switch (test expression) {
case value1:
//...action statements
break;
case value2:
//...action statements
break;
case value3:
//...action statements
break;
.
.
.
default:
//...action statements

10

Download more at Learnclax.com


}

Class switch{
Public static void main (string[] args){
int day = 5
Switch (day) {
Case 1
System.out.printIn(“Monday”);
Break;
Case 2
System.out.printIn(“Tuesday”);
Break;
Case 3
System.out.printIn(“Wednesday”);
Break;
Case 4
System.out.printIn(“Thursday”);
Break;
Case 5
System.out.printIn(“Friday”);
Break;
Default;
System.out.printIn(“it is weekend”);
}
}
}

4. The while Loop


The while loop that executes a block of code repeatedly depending on the result of a test
condition. You can create a while loop using the while keyword followed by the test
condition in parentheses. The action statements to be executed when the test condition is
true are enclosed in braces following the while statement.

During program execution, the test condition in the while loop is evaluated before the
action statements are executed. If the test condition returns true, the statements enclosed
within the while loop are executed. After executing the action statements, the program
control returns to the while statement where the test condition is tested once again. If the
test condition is true, the action statements within the while block are executed again.
This process continues until the test condition is false, in which case, the program
execution continues from the program statement following the while block.

Example: Syntax: (The while Loop)


The syntax used to create a while loop is:

11

Download more at Learnclax.com


while (Boolean test expression) {
...// action statements
}

Class whileloop {
Public static void main {string args[] {
int counter = 10
int i = 1
while (i <= counter) {
system.out.printIn(“counter =” + i);
i++;
}
}
}

5. The do while Loop


The do...while loop is an iterative statement where the action statements within the loop
are executed once before the test condition is evaluated. The do...while loop starts with
the do keyword followed by action statements in braces. This is followed by the while
keyword with the test condition specified within parentheses.

During program execution, the statements within the do...while loop are executed once
before the test condition is evaluated. If the test condition is true, the action statements
within the do...while block are executed again. This process continues until the test
condition is false, in which case, the program execution continues from the program
statement following the do...while block.

Example: Syntax: (The do...while Loop)


The syntax used to create a do...while loop is:
do {
//...action statements
} while (test expression);

Class Dowhile
Public static void main (Strign args[]){
int counter = 10;
int i = 1
do{
system.out.printIn(“counter;”+i);
i++
while (i <= counter);
}
}

12

Download more at Learnclax.com

You might also like