L01 Programming & Introduction To Java
L01 Programming & Introduction To Java
Lecture 1
Programming & Introduction to Java
2
What Is Programming?
3
Problem Solving & Algorithm
Analyzing Developing
Coding Testing
Problem Algorithm
Flowchart Symbols
5
Problem Solving & Algorithm (cont.)
6
Problem Solving & Algorithm (cont.)
Step2: Implement the algorithm
• Implement the algorithm in code (coding)
• Verify that the algorithm works (testing)
Step3: Maintenance
• Use and modify the program if the problem domain changes. (any
changes required)
• Note: If the problem is complex, divide it into sub problems and then
analyze each sub-problem as above
7
Problem Solving & Algorithm (cont.)
Example 1:
• Write a Pseudocode and draw a flowchart to convert the length from
feet to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by multiplying LFT with 30
• Print length in cm (Lcm)
8
Problem Solving & Algorithm (cont.)
Example 1 Flowchart:
9
Problem Solving & Algorithm (cont.)
Example 2:
• Write a Pseudocode and draw a flowchart to determine a student’s final
grade and indicate whether it is passing or failing. The final grade is
calculated as the average of four marks
Pseudocode:
• Input a set of 4 marks
• Calculate their average by summing and dividing by 4
• if average is below 50, Print “FAIL”
Else Print “PASS”
10
Problem Solving & Algorithm (cont.)
Example 2 Flowchart:
START
Input
M1,M2,M3,M4
GRADE(M1+M2+M3+M4)/4
N IS Y
GRADE<5
0
PRINT PRINT
“PASS” “FAIL”
STOP
11
Programming Paradigms
• Procedural/Functional paradigm:
in which programs consist of a collection of procedures and functions that
operate on data.
12
Programs
• A program is a set of instructions for a computer to follow that directs the
computer to do the tasks you want it to do and produce the results you
want.
• We use programs almost daily (email, word processors, video games, bank
ATMs, etc.).
13
Programs (Cont.)
• We use programs almost daily (email, word processors, video games, bank
ATMs, etc.).
14
Running a Program
• Normally, a computer receives two kinds of input:
• The program
• The data needed by the program.
15
Programming Languages
• Programming languages are a set of instructions written in a way that
a computer could understand
17
Basic instructions in programming
languages
• input: Get data from the keyboard, a file, a sensor, or some other
device.
•
• output: Display data on the screen or send data to a file or other
device.
18
Programming Languages Categories
• Low-level languages (machine Assembly
High-level
language):
they are close to the machine
language e.g. assembly language
• High-level languages:
they are closer to the programmers'
language (more friendly!) e.g. Java
19
Levels of Programming Languages
• Business Cobol
21
Translating/Converting High-level to Low-
level
• A source program must be translated into a machine code.
• The program is run by loading machine code into main memory. The
processor directly executes these machine language instructions
22
Compilers
23
Interpreters
• An interpreter reads through a source program written in a high-level
language and performs the instructions that the source program asks
for one by one.
• Once a given instruction has been translated and executed, the next
one then will follow, and so on
24
Java History
• Java is a high-level object-oriented programming
language developed by James Gosling at Sun
Microsystems in the early 1990s.
• He was unhappy using c++ programming language so
he developed java.
• Java Old name was “Oak”
• 1995 “Oak” was renamed as Java as a core
components of Sun microsystems java platform
• Java is a consolidation language, designed to absorb
the strengths of earlier languages and ignore their
weakness
• According to sun, 3 billions devices run java.
25
Java Features
• Simple
Java syntax is based on C++ (greatly simplified and improved).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
• Platform-Independent (portable)
Write once run anywhere
Java is completely portable; the same Java code will run identically on
different platforms, regardless of hardware compatibility or operating
systems.
• Object oriented
OOP is a popular programming approach that is replacing traditional
procedural programming which offers great flexibility, modularity, clarity,
and reusability
26
All coding and data reside within objects and classes
Java Features (Cont.)
• Robust and secure
Exception handling built-in strong type checking
automatic garbage collection so all memory corruptions or unauthorized
memory accesses are impossible
strong memory management (no-pointers).
Programs run inside the virtual machine sandbox
• Distributed
Creating applications on networks.
Multiple programmers can work together on a single project from multiple
remote locations and share data and programs.
27
Java Features (Cont.)
• Multithreaded
It allows to handle multiple tasks simultaneously (run multiple threads )
• Architecture-Neutral
no implementation dependent features e.g. size of primitive types is fixed.
• High-performance
The new JVM uses the technology known as just-in-time (JIT) compilation.
With JIT complier the interpreted code gives almost the native code speed.
28
Java Applications
• Stand alone applications
Also known as desktop applications
They are traditional software i.e., we need to install to every machine
Examples: Acrobat reader, Media player, Antivirus, etc.
• Web applications
These applications that runs on the server side and creates a dynamic pages.
Technologies such as JSP, Servlet, spring, etc. are used for creating web applications
in java.
Example: [Link], [Link] (student information system (SIS))
• Enterprise applications
An application that is distributed in nature, such as Banking applications.
It has advantages of high-level security, load balancing, and clustering.
• Mobile applications
An application which is created for mobile devices
Currently, Android and java Me are used for creating mobile applications.
• Other applications such as robotics, games, etc.
29
[Link]
Java Development Environment Phases
30
[Link]
Java Development Environment Phases (Cont.)
• Step1: Creating and Editing Programs
This step involves using an editor to type a Java program (source code), then save it
on a secondary storage device, such as hard drive.
All Java source code files are ending with the .java extension.
31
Java Development Environment Phases (Cont.)
• Step2: Compiling a Java Program into Byte-codes
The Java compiler does not translate a Java program into machine language for a
particular computer.
Byte-code:
is the machine language for a hypothetical computer (or interpreter) called the Java
Virtual Machine.
The byte-code file has a .class file extension
byte-code represents the tasks to execute in the execution phase
Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the
foundation of the Java platform
Bytecodes are platform independent
They do not depend on a particular hardware platform
Bytecodes are portable
The same bytecodes can execute on any platform containing a JVM that understands the
version of Java in which the bytecodes were compiled
Bytecode can be sent over the Internet and used anywhere in the world. This makes Java
suitable for Internet applications. 32
Java Development Environment Phases (Cont.)
• Step3: Loading a Program into Memory
The Java Virtual Machine (JVM) places the program in memory to execute it—this
process is known as loading
The JVM’s class loader (also called the linker ) takes the .class files containing the
program’s byte-codes and transfers them to main memory.
33
Java Development Environment Phases (Cont.)
• Step 4: Bytecode Verification
As the classes are loaded, the bytecode verifier checks their bytecodes to ensures
that they’re valid and don’t violate Java’s security restrictions
Java enforces strong security to make sure that Java programs arriving over the
network do not damage your files or your system (as computer viruses and worms
might)
34
Java Development Environment Phases (Cont.)
• Step5: Interpreting and Execution
The Java Virtual Machine (JVM) translates each byte-code instruction
and executes the resulting machine-language instructions before translating the
next byte-code instruction.
Most Java programs today are executed using a Just-In-Time or JIT compiler. JIT
compilers interact with the Java Virtual Machine (JVM) at run time and compile
suitable bytecode sequences into native machine code that can be sent directly to a
computer's processor (CPU).
35
Recap
• Java code is usually compiled into platform independent bytecode (class
files).
• The JVM is able to load the class files and execute the java bytecode via
the java interpreter.
• Unlike the normal compiler, the JIT compiler compiles the code
(bytecode) only when required.
37
Core Concepts in Java (Cont.)
It is used to:
read bytecode
run the same bytecode on any machine with a JVM (run any java program)
38
Core Concepts in Java (Cont.)
39
Recap
40
Programming Basics
41
41
Reserved Keywords
• Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other purposes in
the program. Reserved words are always spelled withall lowercase
letters.
44
Compiling and Running a Java Program or
Class (Cont.)
• The name of the file should be the same as the name of the class.
• The class will contain the statement below (only ONE class must include the
main method)
45
Testing and Debugging
• Test your program with appropriate test cases (some where the answer
is known), discover and fix any errors, then retest.
46
Programming Errors
• A mistake in a program is called a bug.
47
Programming Errors (Cont.)
• Syntax Errors:
The syntax of a programming language is the set of grammatical rules for
the correct way to write a program.
48
Programming Errors (Cont.)
• Runtime Errors:
Errors that are detected when your program is running, but not during
compilation
When the computer detects an error, it terminates the program and prints
an error message.
The error message might not be easy to understand, but at least you will
know that something is wrong!
49
Programming Errors (Cont.)
• Logic Errors:
Errors that are not detected during compilation or while running, but which
cause the program to produce incorrect results.
Logic errors will not give you any error messages. For this reason, logic
errors are the hardest kind of error to locate.
50
Basic Java Program Structure
• There are 5 components that we usually include in a Java program,
which are:
[ Documentation Statement(s) ]
[ Package Statement ]
[ Import Statement(s) ]
public class className {
public static void main(String[] args) {
51
Basic Java Program Structure (Cont.)
• Documentation Statement(s):
It includes "comments" lines that we use to describe the whole idea
behind the program and its methods
52
Basic Java Program Structure (Cont.)
• Documentation Statement(s):
There are three types of comments that Java supports:-
They are optional and used to declare classes in a collection called package
Package statements must be at the beginning of the code before any class
or interface declaration!
Example: package people; Note, this statement declares that all the
classes and interfaces defined in this source
file are a part of the people package
54
Basic Java Program Structure (Cont.)
• Import Statement(s):
They are used to refer to set of classes that are located in other packages
Always write the import statements after the package statement and before
the class declaration.
55
Basic Java Program Structure (Cont.)
• Class Definition(s):
A class is a collection of variables and methods that operate on the
attributes or fields.
Syntax:
the public keyword means this class is accessible by any other classes
The curly brackets are used to make sure that the statements belong to
one class
56
Basic Java Program Structure (Cont.)
• Class Definition(s):
Class declaration (header)
Every Java program consists of at least one class that you define
class keyword introduces a class declaration and is immediately followed by the
class name
Java class declaration normally contain one or more methods.
One of these classes must have the main method
Class name
By convention, begin with a capital letter
Camel Case is a style used to capitalizing the initial letter of each word and omitting
spaces (e.g., SampleClassName).
A class name is an identifier—a series of characters consisting of letters, digits,
underscores (_) and dollar signs ($) that does not begin with a digit and does not
contain spaces
Java is case sensitive—uppercase and lowercase letters are distinct
57
Basic Java Program Structure (Cont.)
• Main Method:
The main method is the place where the program execution starts. Meaning the
computer follows the order specified by the Java statements.
The main method is an essential part of any program in Java and where the JVM
starts running the program
Where:
public means that this method can be used outside of this class
static means that there is no need to create an object to access this a method
void means that this method does not return any value
String[] args is an array named as args where each element is a string. We use it
to pass the input to the program when we run the Java code through a console
Declaring main as static allows the JVM to invoke main without creating an
instance of the class 58
Basic Java Program Structure (Cont.)
• Main Method:
Syntax:
59
Basic Java Program Structure (Cont.)
• Block:
It is a pair of curly braces in a program forms a block that groups components
of a program
Example:
60
Basic Java Program Structure (Cont.)
• Block:
You may use next-line or end-of-line style for braces
61
Basic Java Program Structure (Cont.)
• Block:
Which code do you think it is more readable?
62
Basic Java Program Structure (Cont.)
• Statement:
Is a command for the computer to do something.
63
Basic Java Program Structure (Cont.)
• Statement:
Example Explanation:
statement
Instructs the computer to display a string of characters contained between the
double quotation marks on the screen
Positions the output cursor at the beginning of the next line on the screen
(command window)
64
Basic Java Program Structure (Cont.)
• Statement:
Example Explanation:
Strings cannot span multiple lines of code
65
A First Java Application
66
A First Java Application (Cont.)
Sample
screen
output
67
A First Java Application (Cont.)
• Tracing the Program:
68
A First Java Application (Cont.)
• Tracing the Program:
69
A First Java Application (Cont.)
• Tracing the Program:
70
Recap
• Proper Indentation and Spacing:
Use blank lines to separate segments of the code .
For example:
[Link]("Hello World!"); // print a string
71
Recap (Cont.)
• Appropriate Comments:
Starts your program with a comment that states the purpose of the program,
the author, time and date of the last program modifications
Write a comment before each class, documenting the purpose of the class
Write an end of line (single line) comment, documenting the purpose of the
statement
72
Recap (Cont.)
• In every Java source file, you might see the following 5 components:
//comments
package name;
import className;
73
Techniques of Decomposition and
Abstraction
74
Decomposition
• Decomposition is breaking a complex problem down into smaller
problems and solving each one individually
75
Decomposition (Cont.)
• Advantages
Different people can work on different subproblems
Parallelization may be possible
Maintenance is easier
• Disadvantages
Solutions to the subproblems might not combine to solve the original
problem
Poorly understood problems are hard to decompose
Information hiding
having modules keep their data private
provide limited access procedures
77
Abstraction
• Abstraction is the process of removing unnecessary details so that only
the important points remain
• In programming, abstraction is the process of naming compound objects
and dealing with them as single entities
• Abstraction can help with decomposition (e.g. to manage the economy, try
focusing on some abstracted features such as inflation)
• Abstraction doesn’t solve problems, but it allows us to simplify them
The abstraction:
int squares (int x, int y) {
return(x * x - y * y);
}
describes a set of computations which act on any two (integer) variables to compute
the difference of their squares.
Note: locally the variables are called x and y for convenience
The code below uses the abstraction squares on two specific variables
(‘big’ and ‘small’)
result = squares(big, small);
79
Abstraction (Cont.)
2) Abstraction by Specification
Abstraction by parameterization allows us to express computations but does
not tell us about the intention of those computations
80
Abstraction (Cont.)
• Unfortunately only abstraction by parameterization is built into our
programming languages as function (procedure) definitions
• We can overcome this using comments
81