You are on page 1of 66

COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Prayer Before Study


by St. Thomas Aquinas
Lord, true source of light and wisdom, give me a
keen sense of understanding, a retentive memory
and the capacity to grasp things correctly. Grant
me the grace to be accurate in my expositions
and the skill to express myself with thoroughness
and clarity. Be with me at the start of my work,
guide its progress and bring it to completion.
Grant this through Christ our Lord, Amen.

St. Vincent Ferrer , Pray for us.


St. Thomas Aquinas, Intercede for us.
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Module 3:
Sequential Java
Programming

ICS2602
Computer
Programming I
(Imperative)
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Objectives
Objectives
After studying Module 3, students should
be able to:
Learn about the language of a computer

Learn about the evolution of programming languages

Examine high-level programming languages


COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Objectives
Objectives
Discover what a compiler is and what it does

Compare procedural and object-oriented programming

Describe the features of the Java programming language

Examine how a Java program is processed

Become familiar with the basic components of a Java program,


including methods, classes, identifiers, variables and constant
declaration
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Objectives
Objectives
Discover how to input data into memory by using input
statements

Examine ways to output results using output statements

Learn how to import packages and why they are necessary

Learn what an assignment statement is and what it


does
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Objectives
Objectives
Explore how to properly structure a program,
including using comments to document a program

Compile a Java class and correct syntax


errors

Run a Java application and correct logic


errors
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Introduction
Introduction

• Computers have greatly affected our daily


lives – helping us complete many tasks
• Computer programs (software) are
designed specifically for each task
• Software is created with programming
languages
• Java is an example of a programming
language
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Language
Language of
of aa Computer
Computer
• Machine language: the most basic language
of a computer
• A sequence of 0s and 1s
• Every computer directly understands its own
machine language
• A bit is a binary digit, 0 or 1
• A byte is a sequence of eight bits
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Evolution
Evolution of
of Programming
Programming Languages
Languages

• Early computers programmed in machine


language
• Assembly languages were developed to make
programmer’s job easier
• In assembly language, an instruction is an
easy-to-remember form called a mnemonic
• Assembler: translates assembly language
instructions into machine language
INSTITUTE OF INFORMATION AND COMPUTING
SCIENCES

Evolution
Evolution of
of Programming
Programming Languages
Languages

• To run a Java program

1.Java instructions need to be translated into an


intermediate language called bytecode

2. Then the bytecode is interpreted into a


particular machine language
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Evolution
Evolution of
of Programming
Programming Languages
Languages
• Compiler: a program that translates a program
written in a high-level language into the
equivalent machine language
In the case of Java, this machine language is the
bytecode

• Java Virtual Machine (JVM): hypothetical


computer developed to make Java programs
machine independent
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Programming
Programming Methodologies
Methodologies

• Two basic approaches to


programming design

• Structured design
• Object-oriented design
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Structured
Structured Design
Design

• A problem is divided into smaller


subproblems
• Each subproblem is solved
• The solutions of all subproblems are then
combined to solve the problem
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Object-Oriented
Object-Oriented Design
Design (OOD)
(OOD)

• In OOD, a program is a collection of


interacting objects
• An object consists of data and operations

• Steps in OOD
1. Identify objects
2. Form the basis of the solution
3. Determine how these objects interact
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

The
The Basics
Basics of
of aa Java
Java Program
Program

• Java program: collection of


classes
• There is a main method in every
Java application program
• Token: smallest individual unit of
a program
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Features
Features of
of the
the Java
Java Programming
Programming
Language
Language
• Java
• Developed by Sun Microsystems
• An object-oriented language
• General-purpose
• Advantages
• Security features
• Architecturally neutral
• Can be run on a wide variety of computers
• Does not execute instructions on the computer directly
• Runs on a hypothetical computer known as a Java Virtual Machine
(JVM)
• Source code
• Programming statements written in high-level programming language
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Features
Features of
of the
the Java
Java Programming
Programming
Language
Language
• Development environment
• A set of tools used to write programs
• Bytecode
• Statements saved in a file
• A binary program into which the Java
compiler converts source code
• Java interpreter
• Checks bytecode and communicates with the
operating system
• Executes bytecode instructions line by line
within the Java Virtual Machine

The JAVA Environment


COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Features
Features of
of the
the Java
Java Programming
Programming
Language
Language
• WORA
Write once, run anywhere

• Console applications
Support character output

• Windowed applications
Menus
Toolbars
Dialog boxes
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

A
A Java
Java Program
Program
public class ASimpleJavaProgram
{
public static void main(String[] args)
{
System.out.println("My first Java program.");
System.out.println("The sum of 5 and 3 = " + 8);
System.out.println(“9 + 8 = " + (9 + 8));
}
}
Sample Run:
My first Java program.
The sum of 5 and 3 = 8
9 + 8 = 17
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Processing
Processing aa Java
Java Program
Program
• Two types of Java programs:
applications and applets
• Source program: written in a high-
level language
• Loader: transfers the compiled code
(bytecode) into main memory
• Interpreter: reads and translates
each bytecode instruction into
machine language and then executes
it
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Problem-Solving
Problem-Solving Process
Process

1. Analyze the problem: outline solution


requirements and design an algorithm
2. Implement the algorithm in a
programming language (Java) and
verify that the algorithm works
3. Maintain the program: use and
modify if the problem domain changes
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

The
The Basics
Basics of
of aa Java
Java Program
Program

• Java program: collection of classes


• There is a main method in every Java
application program
• Token: smallest individual unit of a program
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

A
A Java
Java Program
Program
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Understanding
Understanding the
the First
First Class
Class

• Everything used within a Java program must be


part of a class
• Define a Java class using any name or identifier
Java Identifiers
• Names of things
• Consist of:
• Letters
• Digits
• The underscore character (_)
• The dollar sign ($)
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Rules
Rules in
in Naming
Naming Identifiers
Identifiers
•Requirements for identifiers
1. Must begin with one of the following:
• Letter of the English alphabet
• Non-English letter (such as α or π)
• Underscore
• Dollar sign
2. Cannot begin with a digit
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Rules
Rules in
in Naming
Naming Identifiers
Identifiers

3. Can only contain:


• Letters
• Digits
• Underscores
• Dollar signs
4. Cannot be a Java reserved keyword
5. Cannot be true, false, or null
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Identifiers
Identifiers

• Upper Camel casing (Pascal


casing)
• Each word of an identifier
begins with uppercase letter
• UnderGradStudent
• InventoryItem
• Access specifier
• Defines how a class can be
accessed
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

JAVA
JAVA Reserved
Reserved Words
Words
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Illegal
Illegal Identifiers
Identifiers

Illegal Identifier Description


employee Number There can no be space between employee and
Number.
Hello! The exclamation point can not be used in an identifier.
one+one The symbol + can not be used in an identifier.
2Prog An identifier must not begin with a digit
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Legal but unconventional and nonrecommended class names in Java


Class Name Description
Newstudent New words are not indicated with
initial uppercase letters, making this
identifier difficult to read
Inventory_List Underscore is not commonly used to
indicate new words
BUDGET2020 Using all uppercase letters for class
identifiers is not conventional
budget2020 Conventionally, class names do not
begin with a lowercase letter
celphone# The number symbol (#) is illegal in an
identifier
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Variables
Variables
• Variable (name, value, data type, size)
• Content may change during program execution
• Must be declared before it can be used
• May not be automatically initialized
• If new value is assigned, old one is destroyed
• Value can only be changed by an assignment
statement or an input (read) statement
• Example
double amountDue;
int counter;
char ch;
int num1, num2;
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Constant
Constant Declaration
Declaration
• Named constant
• Cannot be changed during program execution
• Declared by using the reserved word final
• Initialized when it is declared
• Example
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Creating
Creating aa Java
Java Program
Program
• Syntax of a class

• Syntax of the main method


COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Parts
Parts of
of aa Typical
Typical Class
Class
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

The main() Method


The main() Method

• static
• A reserved keyword
• Means the method is accessible and usable even though no
objects of the class exist
• void
• Use in the main() method header
• Does not indicate the main() method is empty
• Indicates the main() method does not return a value when
called
• Does not mean that main() doesn’t produce output
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

The main() Method


The main() Method
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Indent
Indent Style
Style

• Use whitespace to organize code and improve


readability
• For every opening curly brace ( { ) in a Java
program, there must be a corresponding closing
curly brace
(})
• Placement of the opening and closing curly braces
is not important to the compiler
• Allman style used in text
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Using
Using the Scanner Class
the Scanner Class to
to Accept
Accept Keyboard
Keyboard
Input
Input
• Standard input stream object: System.in
• System.in object
• Standard input device
• Normally the keyboard
• Access using the Scanner class
• Scanner object
• Breaks input into units called tokens
To read data:
1. Create an input stream object of the class
Scanner
2. Use the methods such as next, nextLine,
nextInt, and nextDouble
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Using
Using the Scanner Class
the Scanner Class to
to Accept
Accept Keyboard
Keyboard
Input
Input
static Scanner console = new Scanner(System.in);
• Example
static Scanner console = new Scanner(System.in);
int feet;
int inches;
Suppose the input is
23 7
feet = console.nextInt(); //Line 1
inches = console.nextInt(); //Line 2
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Using
Using the Scanner Class
the Scanner Class to
to Accept
Accept Keyboard
Keyboard
Input
Input
Scanner class methods
Method Description
nextDouble() Retrieves input as a double
nextInt() Retrieves input as an int
nextLine() Retrieves the next line of data and returns it as a String
next() Retrieves the next complete token as a String
nextShort() Retrieves input as a short
nextByte() Retrieves input as a byte
nextFloat() Retrieves input as a float. Note that when you enter an input value that will be
stored as a float, you do not type an F. The F is used only with constants coded
within a program.
nextLong() Retrieves input as a long. Note that when you enter an input value that will be
stored as a long, you do not type an L. The L is used only with constants coded
within a program.
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Output
Output

Standard output object: System.out


Methods
print
println
Syntax
System.out.print(stringExp);
System.out.println(stringExp)
; System.out.println();
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Output
Output
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Escape
Escape sequence
sequence

• Begins with a backslash followed by a character


• Represents a single nonprinting character
char aNewLine = '\n';
• To produce console output on multiple lines in the
command window, use one of these options:
• Use the newline escape sequence
• Use the println() method multiple times
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Escape
Escape sequence
sequence
Common escape sequences
Escape Description
Sequence
\b Backspace; moves the cursor one space to the left
\t Tab; moves the cursor to the next tab stop
\n Newline or linefeed; moves the cursor to the beginning of the
next line
\r Carriage return; moves the cursor to the beginning of the
current line
\" Double quotation mark; displays a double quotation mark
\’ Single quotation mark; displays a single quotation mark
\\ Backslash; displays a backslash character
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

import Statement
import Statement

• Used to import the components of a package into


a
program
• Reserved word
• import java.io.*
• Imports the (components of the) package
java.io into the program
• Primitive data types and the class String
• Part of the Java language
• Don’t need to be imported
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

The
The Assignment
Assignment
Statement
Statement

Syntax: variable = expression;

Example

num1 = 13;
num2 = 5 * 5 - 11;
sale = 0.05 * 1000;
first = ‘A';
str = "It is a rainy day.";
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Adding
Adding Comments
Comments

• Program comments
• Nonexecuting statements added to a
program for documentation
• Use to leave notes for yourself or others
• Include the author, date, and class’s
name or function
• Comment out a statement
• Turn it into a comment
• The compiler does not translate, and the
JVM does not execute its command
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Types
Types of
of Comments
Comments

• Line comments
• Start with two forward slashes (//)
• Continue to the end of the current line
• Do not require an ending symbol
• Block comments
• Start with a forward slash and an asterisk (/*)
• End with an asterisk and a forward slash (*/)
• Javadoc comments
• A special case of block comments
• Begin with a slash and two asterisks (/**)
• End with an asterisk and a forward slash (*/)
• Use to generate documentation
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Example
Example
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Indent
Indent Style
Style

• Use whitespace to organize code and improve readability


• For every opening curly brace ( { ) in a Java program,
there must be a corresponding closing curly brace
(})
• Placement of the opening and closing curly braces is not
important to the compiler
• Allman style used in text
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Saving
Saving aa Java
Java Class
Class

• Save the class in a file with


exactly the same name and
.java extension
• For public classes, class
name and filename must
match exactly
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Compiling
Compiling aa Java
Java
Class
Class
• Compile the source code into
bytecode
• Translate the bytecode into
executable statements
• Using a Java interpreter
• Type javac First.java
• Compilation outcomes
• javac is an unrecognized command
• Program language error messages
• No messages indicating successful
completion
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Errors
Errors in
in JAVA
JAVA Program
Program

• Reasons for error messages


• Misspelled the command
javac
• A misspelled filename
• Not within the correct
subfolder or subdirectory
on the command line
• Improper installation of
Java
COLLEGE OF INFORMATION AND COMPUTING SCIENCES
Correcting
Correcting Syntax
Syntax
Errors
Errors
• The first line of the error message displays:
• The name of the file where the error was
found
• The line number
• The nature of the error
• Next lines identify:
• The symbol
• The location
• Compile-time error
• The compiler detects a violation of language
rules
• Refuses to translate the class to machine
code
• Parsing
• Compiler divides source code into
meaningful portions
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Other
Other Types
Types of
of Errors
Errors

• Logic error
• The syntax is correct but
incorrect results were
produced when executed
• Run-time error
• Not detected until
execution
• Often difficult to find and
resolve
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Running
Running aa Java
Java
Application
Application

• Run the application from the command line

• Type java First

• Shows the application’s output in the command window


• The class is stored in a folder named Java on the C drive
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Sample
Sample Run
Run
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Finding
Finding Help
Help

• Java API
• Also called the Java class library
• Provides prewritten information about Java classes
• FAQs on the Java Web site
• Java Development Kit (JDK)
• A software development kit (SDK) of programming tools
• Free to download
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Don’t
Don’t Do
Do ItIt
• Don’t forget the file’s name must match the class name
• Don’t confuse these terms:
• Parentheses, braces, brackets, curly braces, square brackets,
and angle brackets
• Don’t forget to end a block comment
• Don’t forget that Java is case sensitive
• Don’t forget to end every statement with a semicolon
• Do not end class or method headers with a semicolon
• Don’t forgot to recompile when making changes
• Don’t panic when you see a lot of compiler error messages
• Don’t assume your program is perfect when all compiler
errors are eliminated.
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Any
Questions?
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Need
Need Further
Further Clarification?
Clarification?
Create a thread to BB Discussion Board in
the ICS2602 Course Site
4

IMPORTANT: The Blackboard Discussion Board is a learning space. Let us


use the BB Discussion Board for learning purposes for the benefit of the entire
class. Use decent words when you create a thread. Also, sending personal
message to your classmate is prohibited.
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Any
Any Concerns?
Concerns?
Send an email to:
DOMAIN EMAIL ADDRESS
UST Domain jogarcia@ust.edu.ph

Get in touch with the IICS Office


through
COLLEGE OF INFORMATION AND COMPUTING SCIENCES

Thank you and Keep


Safe!
INSTITUTE OF INFORMATION AND COMPUTING
SCIENCES
Image Citation:
Image Details
Agenda icon, www.okcareertech.org

Artist: Double-J Design (Available for custom work)


Iconset: Ravenna 3D Icons (90 icons)
License: CC Attribution 4.0
Commercial usage: Allowed (Backlink to http://www.doublejdesign.co.uk
 required)
Readme file: readme.txt
Artist: Hopstarter (Available for custom work)
Iconset: Soft Scraps Icons (150 icons)
License: CC Attribution-Noncommercial-No Derivate 4.0
Commercial usage: Allowed (Author Arrangement required -> Visit artist
website for details).
Artist: FixIcon
Iconset: The Lords Applications Icons (10 icons)
License: Free for personal desktop use only.
Commercial usage: Not allowed
Readme file: More_Icons.html
INSTITUTE OF INFORMATION AND COMPUTING
SCIENCES
Image Citation:
Image Details
Artist: Icons8
Iconset: iOS 7 Icons (1738 icons)
License: Linkware (Backlink to http://icons8.com required)
Commercial usage: Allowed
License URL: http://icons8.com/license/
Artist: Untergunter
Iconset: Leaf Mimes Icons (67 icons)
License: CC Attribution-Noncommercial-Share Alike 4.0
Commercial usage: Not allowed

Artist: Hopstarter (Available for custom work)


Iconset: Sleek XP Basic Icons (50 icons)
License: CC Attribution-Noncommercial-No Derivate 4.0
Commercial usage: Allowed (Author Arrangement required -> Visit artist
website for details).
Artist: Aroche
Iconset: Delta Icons (175 icons)
License: CC Attribution-Noncommercial-No Derivate 4.0
Commercial usage: Not allowed
INSTITUTE OF INFORMATION AND COMPUTING
SCIENCES
Image Citation:
Image Details
Artist: BlackVariant
Iconset: Button UI System Apps Icons (72 icons)
License: Free for non-commercial use.
Commercial usage: Not allowed

Artist: TpdkDesign.net
Iconset: Refresh Cl Icons (258 icons)
License: Free for non-commercial use.
Commercial usage: Not allowed
Readme file: readme_eng.txt

Image: www.pexels.com

Background: Computer Programming Wallpaper,


www.wallpaperaccess.com

You might also like