Programming Techniques
Ishara Fernando
Objective
The objective of this is to enable to
apply high level language for
solution of simple scientific
problems.
Learning Outcomes
Understand the basic principles in programming
Understand the problem-solving strategies
Understand the process of creation of computer
program, and the different approaches
Use high level language to write code. Compile,
link and execute a program with emphasis, on
scientific application
Language Hierarchy
Java , Python ,C
Assembly (ⅹ89)
Binary Code
Introduction to
Programming
Computer Program (Software)
Set of instructions used to operate a computer to
produce a specific result
Programming Language
A programming language is a set of commands,
instructions, and other syntax use to create a software
program.
Programmer
A computer programmer, developer, or software
engineer is a person who writes computer programs
(software programs)
Programming
A process of writing a program, or software
Software Engineering
Software engineering is a branch of computer
science which includes the development and
building of computer systems software and
applications software.
Computer systems software is composed of
programs that include computing utilities and
operations systems. (Windows)
Applications software consists of user-focused
programs that include web browsers, database
programs, etc. (Banking System)
Software engineer
Software engineers have good knowledge of
programming languages, software development,
and computer operating systems, and they apply
engineering principles to software creation.
By applying these engineering principles to every
stage of the development process, from
requirements analysis to the software process,
they can create customized systems for individual
clients.
Rules for Beginners - Java
Rule 1:Every Java Program that we write will have to have the following form:
public class NAME {
public static void main(String[] args) {
YOUR CODE HERE
}
}
When you save your program, the file name must match the class name
In the above example file name should be NAME.java
Java is case-sensitive – it does distinguish between uppercase and lowercase
public is different from Public
To print text to the screen:
System.out.println(“Text To PRINT”);
Your first Java program
Here is an example program that will print out
“I Love Java!” 3 times
public class helloworld {
public static void main(String[] args) {
System.out.println(“ I Love Java!”);
System.out.println(“I Love Java!”);
System.out.println(“ I Love Java!”);
}
}
So the output of this program will be:
I Love Java
I Love Java
I Love Java
Editing, Compiling and Executing
a Java Program
• Create your program using Notepad and save with .java extension
• Compile your program using: javac Hello.java
• Execute your java class file using: java Hello
Edit – Use Notepad
public class helloworld {
public static void main(String[] args) {
Public class System.out.println(“1 I Love Java”)
/* }
}
Text Editor
helloworld.java
Compile - (javac helloworld.java)
Compiler
Errors and Warnings
-------------------
Error : The method print(
String) is undefined for
Type System
Compile - Success (Helloworld.class file created)
Public class Adven
/*
This program is an Arit
*/
public static void main
/* Program statements g
System.out.print(“Wel
Compiler }
}
Adventure.java
001011010001011101
1011010001011101110
101000101110111010110100
010111011101011010001011
101110101101000101110111
010110100010111011100010
111011101011010001011101
110010111011101011010001
011101110010111011101011
010001011101110010111011
101011010001011101110010
111011101011010001011101
1100101110
Helloworld.class
Load and Run Step 2 – Java Helloworld
Welcome to the Arithm
Fred The date is Sunday Ap
What is your name?Fred
1 Well Fred, after a day
The cube appears to be
Adventure You find a Green door,
The door closes behind
There is a feel of mat
Variables
Variables are the names you give to computer memory
locations which are used to store values in a computer
program.
For example, assume you want to store two values 10
and 20 in your program and at a later stage, you want
to use these two values to calculate sum.
Here are the three simple steps −
1. Create variables with appropriate names and
types.
2. Store your values in those two variables.
3. Retrieve and use the stored values from the
variables.
Variables
The term variable is used because the value stored in the variable can
change
int num1, num2 , total //1. Create variables
num1 =45 // 2. Store values in a variable
num2 =12
total = num1 +num2 // 3. Retrieve stored values
Variable Declaration Statements
Every variable in a Java program must be declared before it is
used
A variable declaration tells the compiler what kind of data
(type) will be stored in the variable
The type of the variable is followed by one or more variable
names separated by commas, and terminated with a
semicolon
Variables are typically declared just before they are used or
at the start of a block (indicated by an opening brace )
Example: int n1,n2;
double weight, length
Basic types in Java are called primitive types
ICS102: Expressions & Assignment 17 September 4, 2025
Variable Declaration in detail
Variable declaration statement has the general form:
Data Type variable Name
Data Type is a valid Java data type and variable Name
is a user-selected variable name (valid identifier)
E.g. int sum;
declarations are typically grouped together and
placed immediately after the method’s opening brace
or are placed at the point where the variable is first
used public class ClassName
{
public static void main(String[] args) //Method’s opening
{
declaration statements; // int i, double x;
……..
other statements;
} // Method’s closing
}
Multiple Variables Declaration
Multiple declaration: Variables with the same type can
always be grouped together and declared using a single
declaration statement.
dataType variable list;
For example:
double grade1;
double grade2;
can be replace by a single declaration statement:
double grade1, grade2;
Variable Data Types
Each variable has a data type, name and a value.
In Java ,variables can be of reference type or primitive type
Primitive Data Types
Reference Types
Identifiers
Identifiers are names of variables, methods,
classes, packages
Examples of Identifiers and
Conventions
Valid Identifiers
degToDes
Slope
Validation
Invalid Identifiers
2lab3 (Begins with a number, which violates rule 1
E*6 (contains a special character, which violates rule 2)
While (is a keyword, which violates rule 3)
Rules of Identifiers - Java
Should be single word. That is spaces are not allowed.
Example: mangoprice is valid but
mango price is not valid
Should start with a letter (alphabet) or underscore or $
symbol
Example: price, _price and $price are valid identifiers.
Should not be a keyword of Java as keyword
Example: class or void etc.
Should not start with a digit but digit.
Example: 5mangoescost is not valid and mangocost5 is
valid.
Length of an identifier in Java can be of 65,535 characters
Identifiers are case-sensitive. mango and Mango are
treated differently.
Java Identifiers …
Predefined identifiers:
Identifiers that are defined in libraries required by the
Java language standard
Although they can be redefined, this could be confusing
and dangerous if doing so would change their standard
meaning
System String println
ICS102: Expressions & Assignment 25 September 4, 2025
Literals
Literals are items in a program whose values do not
change.
“Hello World” (string literal means word Hello
World
34 (is an integer literal and its means the
number 34)
1.5 (is a double literal
True and false (are boolean literals and it means true and
false)
Keywords
Keywords are reserved for their intended use and
cannot be used by the programmer for variable or
method names (as a identifier)
Keywords like static, public and class have a special
meaning (out side comments and strings )
There are about fifty reserved keywords in Java
abstract break byte case catch char class const
continue do double else extends final finally float
for goto if implements import instantsof int interface
long native new null package private protected public
return short static super switch synchronized this throw
transient try void volatile while
Comments
Comments are notes in plain English inserted
in the source code.
Comments are used to:
document the program’s purpose, author, revision
history, copyright notices, etc.
describe fields, constructors, and methods
explain unclear or unusual places in the code
temporarily “comment out” fragments of code
Formats for Comments
A single-line comment goes from // to the end of the
line:
wt *= 2.2046; // Convert to kilograms
A “block” comment is placed between /* and */
marks:
/* Exercise for Java Methods
Author: Aruna Lorensuhewa
Date: 3/5/2015
Rev. 1.0 */
Documentation Comments
Used by the special utility program
javadoc to automatically generate
documentation in HTML format from the
source code
/**
This is the Java doc
Comments
*/
Exercise 1
public class Example
{
public static void main(String [] args)
{
int x;
double y, z;
String s;
x = 4;
y = 6.5;
z = x + y;
s = “ICS”;
System.out.println(s + z);
}
}
ICS102: Expressions & Assignment 31 September 4, 2025
… - Identifiers …
public class Example
{
public static void main(String [] args)
{
int x;
Identifiers
double y, z;
String s;
x = 4;
y = 6.5;
z = x + y;
s = “ICS”;
System.out.println(s + z);
}
}
ICS102: Expressions & Assignment 32 September 4, 2025
… - Identifiers
public class Example
{
public static void main(String [] args)
{
int x;
double y, z; Keywords (Reserved identifiers)
String s;
x = 4;
y = 6.5;
z = x + y; Predefined identifiers
s = “ICS”
System.out.println(s + w);
}
}
ICS102: Expressions & Assignment 33 September 4, 2025
Java Primitive Data Types
Character data type: Character values in Java must be stored as 16-bit
unsigned values using Unicode
Boolena data type: Boolean data types are restricted to one of two values (true
and false)
Java Arithmetic Operators
An operator is a symbol that operates on
one or more arguments to produce result
Java Statement
Statements are similar to sentences in the English
language. A sentence forms a complete idea
which can include one or more clauses. Likewise,
a statement in Java forms a complete command to
be executed and can include one or more
expressions.
Java Statements
A statement is an instruction in a high-level programming
language that tells the computer what operations need to be
performed.
In Java, every statement must be terminated by a semi-colon (;)
Some statements are given below.
Expressions
Statements are often made up of expressions
The symbols that combine to form expressions are
called operands and operators.
In the first expression example of example
Fahrenheit and 32 are operands, and - is an operator.
Assignment Statements
In Java, the assignment statement is used to change
the value of a variable
The equal sign (=) is used as the assignment
operator
An assignment statement consists of a variable on
the left side of the operator, and an expression on
the right side of the operator
Variable = Expression;
An expression consists of a variable, number, or
mix of variables, numbers, operators, and/or method
invocations
temperature = 98.6;
count = numberOfStudents;
dis = Math.sqrt(b * b – 4 * a * c);
ICS102: Expressions & Assignment 39 September 4, 2025
Initialize Variables
The declaration of a variable can be combined
with its initialization via an assignment statement
int count = 0;
double distance = 55 * .5;
char grade = 'A';
Note that some variables can be initialized and
others can remain uninitialized in the same
declaration
int initialCount = 50, finalCount;
ICS102: Expressions & Assignment 40 September 4, 2025
Assignment Statements Cont..
When an assignment statement is executed,
the expression is first evaluated, and then the
variable on the left-hand side of the equal sign
is set equal to the value of the expression
distance = rate * time;
Note that a variable can occur on both sides of
the assignment operator
count = count + 2;
41 September 4, 2025
Shorthand Assignment
Statements
e.g. x += 3;
Shorthand assignment notation combines the
assignment operator (=) and an arithmetic operator
The general form is
Variable Op = Expression
x + = 3
which is equivalent to
Variable = Variable Op (Expression)
x = x + 3
The Expression can be another variable, a constant,
or a more complicated expression
Some examples of what Op can be are +, -, *, /, or %
ICS102: Expressions & Assignment 42 September 4, 2025
Shorthand Assignment Statements
Example: Equivalent To:
count += 2; count = count + 2;
sum -= discount; ?
bonus *= 2; ?
time /= rushFactor; ?
change %= 100; ?
amount *= count1 + count2; ?
September 4, 2025 ICS102: Expressions & Assignment 43
Shorthand Assignment Statements
Example: Equivalent To:
count += 2; count = count + 2;
sum -= discount; sum = sum – discount;
bonus *= 2; bonus = bonus * 2;
time /= rushFactor; time = time / rushFactor;
change %= 100; change = change % 100;
amount *= count1 + count2; amount = amount * (count1 + count2);
September 4, 2025 ICS102: Expressions & Assignment 44
Assignment Compatibility
In general, the value of one type cannot be stored
in a variable of another type
int x = 2.99; //Illegal
The above example results in a type mismatch
because a double value cannot be stored in an int
variable
However, there are exceptions to this
double variable = 2;
An int value can be stored in a double type
variable
ICS102: Expressions & Assignment 45 September 4, 2025
Exercise
Identify the following:
num1, num2 , sum
23
HelloWorld
int
int num1;
(num1 + num2) / 2
sum = num1 + num2;
Java Arithmetic Operators
An operator is a symbol that operates on
one or more arguments to produce result
Relational Operators for Primitive Data
Types
For example, the relation 3<4 is always true, and the relation 2.0 < 3.3 is always
false.
The value of a relational expression such as age < 30 depends on the value
stored in the variable age. If age = 20, then age < 30 is true
In a Java program, a relational expression such as this is typically part of a
selection statement (if, if-else, etc) or repetition statement (while, for, etc).
Examples
Integer Division
5 / 2 2 (The fractional portion of the
answer is simply dropped )
9 % 5 4 (Remainder)
9 / 5 1
18 / 3 + 4 10
18 % 3 * 4 0
18 / 3 * 4 24
8 / (2 + 6) 1
15 + 9/3 + 1 19