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

Lecture 2 2024

Uploaded by

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

Lecture 2 2024

Uploaded by

Lucia Motlhagodi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

ISS112

Introduction to programming

Lecture 2: Introduction to Programming


Outline

1. Introduction
2. Your first Java Program
• Compiling your program
• Executing your program
3. Modifying your first program
4. Displaying text
Introduction
 Program:
A set of instructions written using a programming language for a
computer to follow
 Programming:
 The art & science of writing computer programs.

 Programming Language:
A formal language used to write computer programs / algorithm
 Executing a program:
 the act of carrying out program instructions (AKA running the
program)
 Java application programming
 Use tools from the JDK to compile and run programs.
Executing a Computer Program

• A computer usually processes input data using a set of


rules (a program) to produce output.

Program

Input Data Computer Output


Elements of a Language

English Language Java Programming Language

• Alphabet (letters, ◼ Alphabet (ASCII)


punctuation, digits)

◼ Syntax: statements, class


• Syntax (grammar) and method definitions, etc
• Expression rules

• Semantics (meaning) ◼ Semantics: computation


◼ What Java statements do
Machine Language
Machine Language:
Known as a low-level language. Instructions in machine
language can be executed directly by the computer.
• Program instructions are given in bits (0s &1s)

Drawbacks?
• Programmer has to know the following:
• Operation codes
• Address of data in memory
• The architecture of the CPU
• Writing programs this way is prone to errors
• Different CPUs have different operation codes!
• Programs are difficult to read and modify.
Assembly Language
Assembly language:
Still a low-level language. And is machine dependent.
• Uses mnemonics to represent instructions and
memory cells
• MUST be translated into machine language.
Drawbacks
• Programmer still needs to think in terms of individual
machine instructions
But note that
• Program is more readable & "somewhat“ more
understandable

Assembler:
Program that translates a program written in assembly
language into an equivalent program in machine language.
High-level Language
• Developed to make programming even more easier
• Closer to English and Secondary School Algebra
• Easier to read and understand
• Machine independent
• Examples: C, C++, Java, Python, Pascal, Ada, COBOL, etc

Note
• Program is readable
• Programmer does not have to know the individual
machine instructions: components have been abstracted
away.
High-level Language Continued
• High-level languages allow us to write portable
programs (machine independent)

BUT,
• MUST be translated (compiled) into machine
language
• Compiled program can usually be executed on the
computer it was compiled on (or a similar one).
Compiler:
A program that translates a program written using
a high-level language into an equivalent machine
language program.
A Typical Java Development Environment

Integrated development environment (IDE) :


A software that contains the following facilities:
- An editor to create the program
- A compiler
- An interpreter
• IDEs are user friendly
 provide tools that support software development process, such as
the editors, compiler would also suggest how to correct syntax errors
 debuggers for locating logic errors that cause programs to
execute incorrectly and more.
 The most popular Java IDEs are:
 Drjava (http://www.drjava.org)
 Eclipse (http://www.eclipse.org)
 IntelliJ IDEA (http://www.jetbrains.com)
10
 NetBeans (http://www.netbeans.org)
A Typical Java Development Environment

 Many freeware and shareware editors are also available


online, including
◦ Notepad++ (http://notepad-plus-plus.org)
◦ EditPlus (http://www.editplus.com)
◦ TextPad (http://www.textpad.com)
◦ jEdit (http://www.jedit.org) and more.
A Typical Java Development Environment

Compiler 1
(IBM)
Editor
Compiler 2
Java Source Code File (Sun) Java Bytecode
(HelloWorld.java) (HelloWorld.class)
Compiler 3
(Apple)

Input Data Bytecode Interpreter


(java)

Machine Instructions
Output Data
(Execution)
A Typical Java Development Environment

◦ Normally there are five phases


◦ Edit, compile, load, verify, execute.
 Phase 1 consists of editing a file with an editor
program
◦ Using the editor, you type a Java program (source
code).
◦ Make any necessary corrections.
◦ Save the program.
◦ Java source code files are given a name ending with
the .java extension indicating that the file contains
Java source code.
A Typical Java Development Environment

 Phase 2: Compiling a Java Program into Bytecodes


• A Java program is compiled into machine language called
bytecode that represent the tasks to execute.
• Bytecode: machine language of a hypothetical computer
called the Java Virtual Machine (JVM)
• The Java Virtual Machine (JVM)—a part of the JDK and the
foundation of the Java platform—executes bytecodes.
• Bytecode is executed by a program called bytecode
interpreter
• If the HelloWorld.java program compiles, the compiler
produces a .class file called HelloWorld.class that contains the
compiled version.
A Typical Java Development Environment

 Phase 3: Loading a Program into Memory


◦ The JVM places the program in memory to execute it—this is
known as loading.
◦ Class loader takes the .class files containing the program’s
bytecodes and transfers them to primary memory.
◦ Also loads any of the .class files provided by Java that your
program uses.
 Phase 4: Bytecode Verification
◦ As the classes are loaded, the bytecode verifier examines their
bytecodes
◦ Ensures that they’re valid and do not 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).
A Typical Java Development Environment

 Phase 5: Execution
◦ The JVM executes the program’s bytecodes.
◦ JVMs typically execute bytecodes using a
combination of interpretation and so-called just-in-
time (JIT) compilation.
◦ Analyzes the bytecodes as they’re interpreted
◦ A just-in-time (JIT) compiler—such as Oracle’s Java
HotSpot compiler—translates the bytecodes into
the underlying computer’s machine language.
The Programming Process
• Systematic steps involved in solving a programming
problem.
Define
Problem

Program Bugs Analysis/


Maintenance
Algorithm Design

Coding
17
Programming Process Cont.
1. Defining the problem
• State the problem concisely
• A lot of software systems fail due to vague problem
definition.
• Usually specified by Management and Systems Analyst.
2. Analysis / Algorithm Design
• Understand the problem completely.
• The requirements (input, output, processing)
• Data representation for data to be processed
• Design an algorithm to solve the problem (specify it using
pseudocode)
• Check the algorithm for correctness (test data and/or
mathematical analysis) 18
Programming Process Cont.
3. Coding
• Implement your algorithm using an appropriate language
• Fix all syntax errors
• Properly document your source code

4. Maintenance
• Use the program
• Execute the program
• Fix all logical and run-time errors
• If requirements change, adapt the program

19
Java Programming Process

Problem Analysis Algorithm


Design

Execute Compile
(Interpreter) (Compiler) Coding

Syntax errors
Results
Logic and runtime errors
Java Programming Basics
a) Structure of a Java Application
public class HelloWorld
{
public static void main (String[] args)
{
<statements>; // Java statement(s) goes here
}
}
• HelloWorld: the class identifier, AKA class name
• Has to match the file name (with a .java extension)
• Program should be saved in a file called HelloWorld.java
• Java statements end with a semi-colon (‘;’)
• Omitting these would result in syntax errors.
- Be warned! 21
Java Program Structure

(Source: Java For Everyone, pg 13)


22
Syntax vs. Style

• Syntax: The rules of a language. If any of the rules


are broken, we get what we call a syntax error. This
normally occurs during compilation. Also known as
compile-time error

• Style: Good programming practices. Includes proper


➢ indentation,
➢comments,
➢ spaces etc to make your program more readable.
Types Of Errors
• Syntax error – It is a grammatical mistake in a program. Can be
picked up by the compiler. Your program will not compile and the
compiler will try to communicate the location of the error to you.
e.g. if you write something like
• prntln(“my java program”); instead of
• println(“my java program”); you get a syntax error.
• Logical error – Error introduced by using faulty logic in a program
• Program produces incorrect results.
• The compiler cannot pick up error because program is
perfectly legal Java. However, program does not run as
intended.
• Runtime error - Error issued by the computer when program is
executed. Program usually crashes with some sort of an error
message
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Your First Program in Java
Commenting Your Programs
 One line Comment
// Fig. 2.1: Welcome1.java
◦ // indicates that the line is a comment.
◦ Used to document programs and improve their readability.
◦ Compiler ignores comments.
◦ A comment that begins with // is an end-of-line comment—it
terminates at the end of the line on which it appears.
 Traditional comment, can be spread over several lines as in
/* This is a traditional comment. It
can be split over multiple lines */
◦ This type of comment begins with /* and ends with */.
◦ All text between the delimiters is ignored by the compiler
Commenting Your Programs
cont.
 Javadoccomments
◦ Delimited by /** and */.
◦ All text between the Javadoc comment delimiters is
ignored by the compiler.
◦ Enable you to embed program documentation
directly in your programs.
◦ The javadoc utility program reads Javadoc
comments and uses them to prepare program
documentation in HTML5 format.
Declaring a class

 Class declaration
public class Welcome1
◦ 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.
◦ Keywords (Appendix C) are reserved for use by Java and are
always spelled with all lowercase letters.
Filename for a public Class
 A public class must be placed in a file that has a filename of the
form ClassName.java, so class Welcome1 is stored in the file
Welcome1.java.
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Class Names and Identifiers

 By convention, begin with a capital letter and capitalize the first


letter of each word they include (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—so a1 and A1 are different (but both valid) identifiers.
Underscore (_) in Java 9
 As of Java 9, you can no longer use an underscore (_) by itself as
an identifier.
Class Body
 A left brace, {, begins the body of every class declaration.
 A corresponding right brace, }, must end each class declaration.
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Declaring a Method

public static void main(String[] args) {


 Starting point of every Java application.
 Parentheses after the identifier main indicate that it’s a program
building block called a method.
 Java class declarations normally contain one or more methods.
 main must be defined as shown; otherwise, the JVM will not
execute the application.
 Methods perform tasks and can return information when they
complete their tasks.
 Keyword void indicates that this method will not return any
information.
Body of the method declaration

 Body of the method declaration


◦ Enclosed in left and right braces.
 Statement
System.out.println("Welcome to Java
Programming!");
◦ Instructs the computer to perform an action
 Display the characters contained between the double
quotation marks.
◦ Together, the quotation marks and the characters between
them are a string—also known as a character string or a string
literal.
◦ White-space characters in strings are not ignored by the
compiler.
◦ Strings cannot span multiple lines of code.
Body of the method declaration

 System.out object
◦ Standard output object.
◦ Allows a Java application to display information in the
command window from which it executes.
 System.out.println method
◦ Displays (or prints) a line of text in the command window.
◦ The string in the parentheses is the argument to the method.
◦ Positions the output cursor at the beginning of the next line in
the command window.
 Most statements end with a semicolon.
Compiling Your First Java Application

 To compile the program,


click Compile or type javac Welcome1.java if
using commandline interface
• If the program contains no compilation errors, a.class
file (known as the class file) is created, containing the
platform-independent Java bytecodes that represent the
application.
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Executing the Welcome1 Application

 To execute this program in a click Run


 This launches the JVM, which loads the Welcome1.class
file.
 The JVM calls class Welcome1’s main method.
Modifying Your First Java Program

 Class Welcome2, shown in Fig. 2.3, uses two


statements to produce the same output as that
shown in Fig. 2.1.
 New and key features in each code listing are
highlighted.
 System.out’s method print displays a string.
 Unlike println, print does not position the
output cursor at the beginning of the next line in
the command window.
◦ The next character the program displays will
appear immediately after the last character that
print displays.
Modifying Your First Java Program
Modifying Your First Java Program
(Cont.)
 Newline characters indicate to System.out’s print and
println methods when to position the output cursor at the
beginning of the next line in the command window.
 Newline characters are whitespace characters.
 The backslash (\) is called an escape character.
◦ Indicates a “special character”
 Backslash is combined with the next character to form an
escape sequence—\n represents the newline character.
 Complete list of escape sequences
http://docs.oracle.com/javase/specs/jls/se7/h
tml/jls-3.html#jls-3.10.6.
Modifying Your First Java Program
(Cont.)
Escape Sequences
Displaying Text with printf
 System.out.printf method
◦ f means “formatted”
◦ displays formatted data
 Multiple method arguments are placed in a comma-separated
list.
 Calling a method is also referred to as invoking a method.
 Java allows large statements to be split over many lines.
◦ Cannot split a statement in the middle of an identifier or string.
 Method printf’s first argument is a format string
◦ May consist of fixed text and format specifiers.
◦ Fixed text is output as it would be by print or println.
◦ Each format specifier is a placeholder for a value and specifies
the type of data to output.
 Format specifiers begin with a percent sign (%) and are followed
by a character that represents the data type.
 Format specifier %s is a placeholder for a string.
Displaying Text with printf
Computing Skills 48

You might also like