Java
Java
Basics of java
Hardware – the physical, tangible pieces that support the computing effort
Program – a series of instructions that the hardware executes one after another
Compiling: translating the program into a form that the computer can execute
Debugging: investigating and fixing various types of errors that can occur
Syntax: programming language that employs set of rules that dictate how the words and symbols can be
put together
Bytecode: it is the machine code for an imaginary machine called the Java Virtual Machine or JVM (part
of the JRE-Java Runtime Environment)
Note: Software tools can be used to help with all parts of this process including SDKs, and IDEs
Language levels:
1. Machine language
2. Assembly language ( low level language)
3. High – level language ( c, c++, java)
4. Fourth generation languages
CPU is the brains of a computer – it fetches an instruction, tries to makes sense of it, then executes it.
Some of paradigms:
1. The user will tell the machine to compile the source code
2. Java will use the bytecode (half cooked code)
3. Java is not tied to any particular machine
4. , it is the machine code for an imaginary machine called the Java Virtual Machine or JVM
(part of the JRE-Java Runtime Environment)
5. The transformation called just in time (JIT) compilation
Types of errors:
Syntax error: Syntax errors are mistakes in using the language. Examples of syntax errors are missing a
comma or a quotation mark, or misspelling a word.
Run-time error: an error that occurs while the program is running after being successfully compiled.
Logic (semantic) error error is text which is grammatically correct but doesn't make any sense.
1. Classes
2. Methods
3. Statements
The process of translating a program into a form that the computer can execute is ________.
Compiling
Translating the program into a form that the computer can execute is called _________
Compiling
True
Each type of Central Processing Unit (CPU) has its own specific
machine language
class
A program is made up of a Blank 1 Question 5 which includes one or more Blank 2
bytecode statements
Question 5 that contain programming .
A ______ is a software tool which translates source code into a specific target language
Compiler
Investigating and fixing various types of errors that can occur is called ___________
Debugging
The set of rules followed by programming languages to create valid programs is called
Answer: syntax
What commenting style would you use for the following comments?
Answer 1 Question 9
This method greets the user with their name
//
coding
Unit 2
It decribes how a computer or a human may do a task, it cannot be excuted by a computer, its for human
read, must be coded to make program, computers can only excute programs.
Components of algorithms:
1. Instruction (also known as primitive): it must be simple and the system must be capable of
performing.
2. Sequence (of instructions): a series of instructions to be carried out
3. Selection: used to decide which instructions to execute
4. Repetition
Common types::
Variables: are containers for values, a specific type of values can hold only one value at a time
Note: a variable must be decleard by specifying the variables identifier and the type of information
Constant: A constant is an identifier that is similar to a variable except that it holds the same value
during its entire existence.
Identifiers: special identifiers called reserved words that already have a predefined meaning in the
language, a reserved word cannot be used in any other way.
White space: Spaces, blank lines, and tabs are called white space, is used to separate words and symbols
in a program, Extra white space is ignored.
Expressions:
An expression is a combination of one or more operators and operands, Arithmetic expressions compute
numeric results and make use of the following arithmetic operators:
Examples:
- Addition +
- Subtraction –
- Multiplication *
- Division /
- Remainder %
Note: If either or both operands used by an arithmetic operator are floating point, then the result is a
floating point
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is
discarded)
Ex:
14/3 = 4
The remainder operator (%) returns the remainder after dividing the second operand into the first
Operator precedence: operators are combines into complex expressions
The order:
note: assignment operator has the lower precedence that the arithmetic operates
the right and left hand sides of an assignment statement can contain the same variable.
- Widening conversions are safest because they tend to go from a small data type to a larger one
(such as a short to an int)
- Narrowing conversions can lose information because they tend to go from a large data type to a
smaller one
Three ways to occur data conversions:
- Assignmet conversion
- Promotion
- Casting
Assignment conversion:
Assignment conversion occurs when a value of one type is assigned to a variable of another
float money;
int dollars = 3;
money = dollars;
Note: the value or type of dollars did not change, Only widening conversions can happen via assignment
Promotion:
Note: if sum is a float and count is an int, the value of count is converted to a floating point value to
perform the calculation
False
Select the right data type for each of the given values:
true boolean
Answer 1 Question 3
1.5 double
Answer 2 Question 3
'F' char
Answer 3 Question 3
500 int
Answer 4 Question 3
96.5f float
Answer 5 Question 3
False
Select the right conversion type for each of the provided definitions:
Answer 1 Question 6
...treat a value temporarily as another type. Casting
b.12
double score;
int points = 10;
score = points;
The code above is an example of what type of conversion?
a.A widening conversion
Which of the following choices is NOT a programming convention?
Object oriented programming: Java is object oriented program language, object is fundamental entity in
java program.
Why?
- It helps you break up your program into all its different components
- You begin to think about what data you will have in your program and what things you can do to
that data
- It helps you to reuse your code by creating “templates” for things
State: descriptive characterstics , behaviors: what it can do and what it can be done
Note: The state of a bank account includes its account number and its current balance The behaviors
associated with a bank account include the ability to make deposits and withdrawals, the behavior of an
object might change its state
A class represents a concept, and an object represents the embodiment of that concept
An object is said to be an instance of a class, We can create multiple objects from the same class, the
class that contains the main method of a Java program represents the entire program
Creating objects:
Packages: The Java standard class library is organized into packages containing ready-made classes.
• When you want to use a class from a package, you could use its fully qualified name
java.util.Scanner
• Or you can import the class, and then use just the class name
import java.util.Scanner;
• To import all classes in a particular package, you can use the * wildcard character
import java.util.*;
• All classes of the java.lang package are imported automatically into all programs
import java.lang.*;
• That's why we didn't have to import the System or String classes explicitly in earlier programs
• The Scanner class, on the other hand, is part of the java.util package, and therefore must be
imported
Basic input:
• The Scanner class which is part of the standard Java class library, provides methods that we can
use to read input from the keyboard
• import java.util.Scanner;”
• or “import java.util.*;”
(NOTE the “*” indicates that you are importing all the classes from the Java util package)
• In order to use the Scanner functionality, we need to explicitly specify the classes that will be
used in our program
• We do this by including an import statement at the very top of our code, above our class
import java.util.*;
...
• We now have the ability to use the Scanner class but first we have to declare a new Scanner
object to use:
import java.util.*;
• We have to specify what type of data we are going to read in, using the following commands:
• Each of these commands will read the next piece of data up until a space, tab, or newline. These
characters that separate elements of the input on both sides are called delimiters.
The string class:
• int, char, double, boolean etc. are examples of primitive data types
• These are built-in to Java and are the basis of other types.
• However, as an exception, for the String class, we do not need to use the new operator to create
a String object.
• For example:
• Each string literal - delimited by double quotation marks - represents a String object.
• The index position specifies a particular position within a String and starts from the first
character in the String, beginning with 0.
• E.g. for a String “Jack Sparrow”, the character ‘S’ is at index 5, the character ‘w’ is at index 11
String methods:
name.length()
name.charAt(5)
name.toUpperCase()
name.toLowerCase()
returns a new String identical to this string except all uppercase characters are
converted to its lowercase equivalent
name.subString(2)
returns a new String that is a subset of name starting at index 2 and extending
name.indexOf(“a”)
Sometimes we might need to break down a long string entered by a user into
its separated strings, e.g. the words in a sentence. We can do this by creating
another Scanner object from the input string and calling the useDelimiter
method of the second Scanner. The next method of the second Scanner
returns each String which is separated by the Delimiter, which can be a space
or other character.
In this example, if a user enters a name which is made up of 3 names, e.g. Ali
System.out.println("Enter Name");
• The Math class provides a number of mathematical functions that can easily be used
• There is no need to import any package to use the Math class as it is available by default
• All the methods in the Math class are static methods (which will be covered in a later lecture),
which means they can be invoked without having to instantiate an object
double x = Math.sqrt(25);
double p = Math.pow(2,3);
returns the value of the first parameter(2) raised to the specified power of the second
double pi = Math.PI;
Returns the value of (the ratio between the circumference of a circle and its diameter)
• The Java standard class library contains classes that provide formatting capabilities to allow us to
format output according to certain requirements
• The DecimalFormat class allows you to format values based on a pattern. It is commonly used to
specify the number of decimal places in a floating point result
import java.text.DecimalFormat;
• The number of decimal places required is specified in the constructor when a DecimalFormat
object is created (2 decimal places in this example)
• The format method of the DecimalFormat class is used to apply the format to
the expression:
System.out.println(fmt.format(44.0/3));
Summary quiz – 3:
False
Unit 4A:
Flowcharts:
• Important Terms :
• Terminator
• Data Block
• Process (Action)
• Decision (Question)
• The flow of control in a running program refers to the order in which the statements are executed
• The statements within a program are usually executed in a linear fashion unless specified otherwise
• Control Structure : Instructions or statements in a programming language which determine the sequence of execution
of other instructions or statements (the control flow).
• To control the program flow and to make decisions, we use control structures combined with conditional operators
and logical operators.
- Sequence
- Selection (branch)
- Repetition (Loop)
Selection:
- One way
- Two way
- Multiple selectons- cascaded ifs, nested ifs
if (x % 2 == 1)
System.out.println("x is odd");
or
if (x % 2 == 1)
System.out.println("x is odd");
• Be careful with
if (x % 2 == 1)
System.out.println("x is odd");
System.out.println("x is a number");
if (x % 2 == 1)
System.out.println("x is odd");
System.out.println("x is a number");
It oocur after an if statement, one or the other will be executed but not both.
The following piece of code is taken from the previous “IF statement” example. It has been modified to handle the case of
the user not winning the prize
number = input.nextInt();
if (number == 7)
else
which help to make your code readable and maintainable. In addition omission
of braces may generate a syntax error in some cases. For example the code below would
cause a syntax error if braces were not used in the first branch of the if
if (number == 7)
System.out.println(“Well done!");
else
choice = in.next();
if(choice.equalsIgnoreCase(“yes”)
Comparing Booleans:
When checking the value of a boolean variable in an if statement we can use == true, or
• Because floating point values are usually stored as an approximation, you should rarely use the equality operator (==)
when making comparison when two floating point values
• The two values will only be considered equal only if their underlying binary representations match exactly
• In many situations, you might consider two floating point numbers to be “close enough” even if they aren't exactly
equal.
• E.g.
{System.out.println("Considered equal");}
• To make decisions we must be able to express conditions and make comparisons
• These expressions are known as boolean or logical expressions and will evaluate to either true or false
• The result of an expression will determine which particular statement will be executed next
• Relational/Comparison Operators:
• Equality (==)
• Inequality (!=)
• Logical Operators:
• And (&&)
• Or (||)
• Not (!)
• Highest to lowest:
• Brackets
• Not (!)
• And (&&)
• Or (||)
Note: The assignment operator (=) is lower in order of precedence than all Boolean operators.
Syntax:
if(condition 1)
if(condition 2) {
statement
Switch statements:
• The variable evaluated can only be of type char, byte, short, or int
• A switch statement can only be used to determine equality (==) and not to determine relational operator
(less than, greater than, etc)
Unit 4B:
- Module: is any unit which is both small enough and large enough to be useful and self-contained
- Breaking a program into smaller modules is called modularisation
Two levels:
- Methods
- Classes and objects
- Method: is a group of code statements which are given a name, Intended to achieve some specific goal or task in the
program, Can be used in various places in your program, Allows for a form of abstraction
- Processing
- Output
- Coordination
Syntax of a method:
• The header describes features about the method. For now, the key thing it specifies is the name of the
method
• The body is the set of instructions that tell the computer how to do the task that this method is designed to
do.
• The order in which statements are performed is called the flow of control
• The caller (who had control) will be paused while the called method is handed control.
• After the called method concludes, it gives control back to the caller method
Local variables:
• The variables in one method are not accessible by code in any other methods
• Scope refers to the parts of the code in which an identifier (i.e. variable name) has meaning to the compiler.
• It will be the area from declaration to the end of the method’s code
• Lifetime refers to how long the variable exists in memory, at run time
• When the method finishes, all local variables are deleted from memory.
The void keyword:
in the case of a method which returns data we cannot call the method by itself in isolation from other code. This is because the
method call evaluates to a value when the method is executed. The code below would not display the value returned by the
method:
introduction();
String myName;
myName= scan.next();
return myName;
}
Retuning data:
As well as returning data from a method we can also send data to a method.
When a method is called, the values of the parameters in the method call are
return sum;
System.out.println(displayAreaOfRectangle(width, height));
double area;
return area;
}
Persisting data:
Combining the use of parameters to send data to a method and returning data from a method means we no longer need to rely
on class level variables to persist data. The BMI example can be rewritten in this way:
• Method overloading is the process of giving a single method name multiple definitions
• If a method is overloaded, the method name by itself is no longer sufficient to determine which method is being called
• The compiler determines which method is being invoked by analysing the parameters
println (String s)
println (int i)
System.out.println (total);
Decision block
Data block
To control the program flow and to make decisions, we
use control structures combined with conditional
operators and logical operators
True
False
Repetitions
Selections
Sequences
The if control structure in Java could be:
One-way selection
Multiple selection
Two-way selection
Match operator with its description
Logical OR Answer 1 Question 6
||
||
&&
Which of the following is the correct syntax for checking
the value of a boolean variable isStudent
if(isStudent)
Order the operators by precedence from lowest to highest
1. Answer 1 Question 9 Assignment
Header
A keyword describing a method that does not return a
value is:
Void
What is the output of this program?
public class Test {
public static void main(String[] args) {
int nb = 4;
incrementByTwo(nb);
System.out.println("nb = " + nb);
}
public static void incrementByTwo(int num) {
num = num + 2;
}
}
nb = 4
What is the output of this program?
public class Test {
public static void main(String[] args) {
int nb = 4;
nb = incrementByTwo(nb);
System.out.println("nb = " + nb);
}
public static int incrementByTwo(int num) {
num = num + 2;
return num;
}
}
nb = 6