4 Programming Fundamentals
4 Programming Fundamentals
4 Programming Fundamentals
4.1 Objectives
In this section, we will be discussing the basic parts of a Java program. We will start by
trying to explain the basic parts of the Hello.java program introduced in the previous
section. We will also be discussing some coding guidelines or code conventions along the
way to help in effectively writing readable programs.
indicates the name of the class which is Hello. In Java, all code should be placed inside
a class declaration. We do this by using the class keyword. In addition, the class uses an
access specifier public, which indicates that our class in accessible to other classes from
other packages (packages are a collection of classes). We will be covering packages and
access specifiers later.
The next line which contains a curly brace { indicates the start of a block. In this code,
we placed the curly brace at the next line after the class declaration, however, we can
also place this next to the first line of our code. So, we could actually write our code as:
Introduction to Programming I 55
J.E.D.I
The next three lines indicates a Java comment. A comment is something used to
document a part of a code. It is not part of the program itself, but used for
documentation purposes. It is good programming practice to add comments to your
code.
/**
* My first java program
*/
A comment is indicated by the delimiters “/*” and “*/”. Anything within these delimiters
are ignored by the Java compiler, and are treated as comments.
The next line,
indicates the name of one method in Hello which is the main method. The main method
is the starting point of a Java program. All programs except Applets written in Java start
with the main method. Make sure to follow the exact signature.
Now, we learned two ways of creating comments. The first one is by placing the
comment inside /* and */, and the other one is by writing // at the start of the
comment.
System.out.println("Hello world!");
prints the text “Hello World!” on screen. The command System.out.println(), prints the
text enclosed by quotation on the screen.
The last two lines which contains the two curly braces is used to close the main method
and class respectively.
Coding Guidelines:
1. Your Java programs should always end with the .java extension.
2. Filenames should match the name of your public class. So for example, if the name
of your public class is Hello, you should save it in a file called Hello.java.
3. You should write comments in your code explaining what a certain class does, or
what a certain method do.
Introduction to Programming I 56
J.E.D.I
Java supports three types of comments: C++-style single line comments, C-style
multiline comments and special javadoc comments.
/* this is an exmaple of a
C style or multiline comments */
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/
Introduction to Programming I 57
J.E.D.I
System.out.println(“Hello world”);
A block is one or more statements bounded by an opening and closing curly braces that
groups the statements as one unit. Block statements can be nested indefinitely. Any
amount of white space is allowed. An example of a block is,
Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the statement,
like for example,
or you can place the curly brace on the next line, like,
2. You should indent the next statements after the start of a block,for example,
Introduction to Programming I 58
J.E.D.I
Java identifiers are case-sensitive. This means that the identifier: Hello is not the same
as hello. Identifiers must begin with either a letter, an underscore “_”, or a dollar sign
“$”. Letters may be lower or upper case. Subsequent characters may use numbers 0 to
9.
Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more
about Java keywords later.
Coding Guidelines:
1. For names of classes, capitalize the first letter of the class name. For names of
methods and variables, the first letter of the word should start with a small letter.For
example:
ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName
2. In case of multi-word identifiers, use capital letters to indicate the start of the word
except the first word. For example, charArray, fileNumber, ClassName.
3. Avoid using underscores at the start of the identifier such as _read or _write.
Introduction to Programming I 59
J.E.D.I
We will try to discuss all the meanings of these keywords and how they are used in our
Java programs as we go along the way.
Note: true, false, and null are not keywords but they are reserved words, so you
cannot use them as names in your programs either
Introduction to Programming I 60
J.E.D.I
For decimal numbers, we have no special notations. We just write a decimal number as it
is. For hexadecimal numbers, it should be preceeded by “0x” or “0X”. For octals, they are
preceeded by “0”.
For example, consider the number 12. It's decimal representation is 12, while in
hexadecimal, it is 0xC, and in octal, it is equivalent to 014.
Integer literals default to the data type int. An int is a signed 32-bit value. In some
cases, you may wish to force integer literal to the data type long by appending the “l” or
“L” character. A long is a signed 64-bit value. We will cover more on data types later.
Floating point literals default to the data type double which is a 64-bit value. To use a
smaller precision (32-bit) float, just append the “f” or “F” character.
Introduction to Programming I 61
J.E.D.I
To use a character literal, enclose the character in single quote delimiters. For example,
the letter a, is represented as ‘a’.
Introduction to Programming I 62
J.E.D.I
The example shown above, declares a variable named result as boolean type and
assigns it a value of true.
To represent special characters like ' (single quotes) or " (double quotes), use the escape
character \. For example,
Although, String is not a primitive data type (it is a Class), we will just introduce String
in this section. A String represents a data type that contains multiple characters. It is
not a primitive data type, it is a class. It has it’s literal enclosed in double quotes(“”).
For example,
Introduction to Programming I 63
J.E.D.I
Integral types has int as default data type. You can define its long value by appending
the letter l or L. Integral data type have the following ranges:
Integer
Name or Type Range
Length
Coding Guidelines:
In defining a long value, a lowercase L is not recommended because it is hard to
distinguish from the digit 1.
Introduction to Programming I 64
J.E.D.I
Examples are,
In the example shown above, the 23 after the E in the second example is implicitly
positive. That example is equivalent to 6.02E+23. Floating-point data types have the
following ranges:
Introduction to Programming I 65
J.E.D.I
4.9 Variables
A variable is an item of data used to store state of objects.
A variable has a data type and a name. The data type indicates the type of value that
the variable can hold. The variable name must follow rules for identifiers.
Note: Values enclosed in <> are required values, while those values enclosed in [] are
optional.
Coding Guidelines:
1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if you want to have a
variable that contains a grade for a student, name it as, grade and not just some
random letters you choose.
3. Declare one variable per line of code. For example, the variable declarations,
double exam=0;
double quiz=10;
double grade = 0;
is preferred over the declaration,
double exam=0, quiz=10, grade=0;
Introduction to Programming I 66
J.E.D.I
System.out.println()
System.out.print()
System.out.println( value );
System.out.println( “The value of x=“ + x );
}
}
10
The value of x=A
System.out.print("Hello ");
System.out.print("world!");
Hello world!
System.out.println("Hello ");
System.out.println("world!");
Hello
world!
Introduction to Programming I 67
J.E.D.I
Primitive variables are variables with primitive data types. They store data in the
actual memory location of where the variable is.
Reference variables are variables that stores the address in the memory location. It
points to another memory location of where the actual data is. When you declare a
variable of a certain class, you are actually declaring a reference variable to the object
with that certain class.
For example, suppose we have two variables with data types int and String.
Suppose, the illustration shown below is the actual memory of your computer, wherein
you have the address of the memory cells, the variable name and the data they hold.
As you can see, for the primitive variable num, the data is on the actual location of
where the variable is. For the reference variable name, the variable just holds the
address of where the actual data is.
Introduction to Programming I 68
J.E.D.I
4.10 Operators
In Java, there are different types of operators. There are arithmetic operators, relational
operators, logical operators and conditional operators. These operators follow a certain
kind of precedence so that the compiler will know which operator to evaluate first in case
multiple operators are used in one statement.
Introduction to Programming I 69
J.E.D.I
//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));
//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}
Introduction to Programming I 70
J.E.D.I
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i / j = 0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58
Note: When an integer and a floating-point number are used as operands to a single
arithmetic operation, the result is a floating point. The integer is implicitly converted to a
floating-point number before the operation takes place.
Introduction to Programming I 71
J.E.D.I
is equivalent to,
count++;
The increment and decrement operators can be placed before or after an operand.
int i = 10,
int j = 3;
int k = 0;
Introduction to Programming I 72
J.E.D.I
When the increment and decrement operators are placed after the operand, the old value
of the variable will be used in the expression where it appears. For example,
int i = 10,
int j = 3;
int k = 0;
Coding Guideline:
Always keep expressions containing increment and decrement operators simple and
easy to understand.
Introduction to Programming I 73
J.E.D.I
Introduction to Programming I 74
J.E.D.I
//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false
//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true
//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}
Introduction to Programming I 75
J.E.D.I
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = true
k > j = false
Greater than or equal to...
i >= j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Less than or equal to...
i <= j = true
j <= i = false
k <= j = true
Equal to...
i == j = false
k == j = true
Not equal to...
i != j = true
k != j = false
Introduction to Programming I 76
J.E.D.I
x1 op x2
where x1, x2 can be boolean expressions, variables or constants, and op is either &&, &,
||, | or ^ operator. The truth tables that will be shown next, summarize the result of
each operation for all possible combinations of x1 and x2.
Introduction to Programming I 77
J.E.D.I
x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Table 13: Truth table for & and &&
The basic difference between && and & operators is that && supports short-circuit
evaluations (or partial evaluations), while & doesn't. What does this mean?
Given an expression,
&& will evaluate the expression exp1, and immediately return a false value is exp1 is
false. If exp1 is false, the operator never evaluates exp2 because the result of the
operator will be false regardless of the value of exp2. In contrast, the & operator always
evaluates both exp1 and exp2 before returning an answer.
Here's a sample source code that uses logical and boolean AND,
int i = 0;
int j = 10;
boolean test= false;
//demonstrate &&
test = (i > 10) && (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
//demonstrate &
test = (i > 10) & (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
Introduction to Programming I 78
J.E.D.I
0
10
false
0
11
false
Note, that the j++ on the line containing the && operator is not evaluated since the first
expression (i>10) is already equal to false.
Introduction to Programming I 79
J.E.D.I
x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 14: Truth table for | and ||
Given an expression,
exp1 || exp2
|| will evaluate the expression exp1, and immediately return a true value is exp1 is true.
If exp1 is true, the operator never evaluates exp2 because the result of the operator will
be true regardless of the value of exp2. In contrast, the | operator always evaluates both
exp1 and exp2 before returning an answer.
Here's a sample source code that uses logical and boolean OR,
int i = 0;
int j = 10;
boolean test= false;
//demonstrate ||
test = (i < 10) || (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
//demonstrate |
test = (i < 10) | (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
Introduction to Programming I 80
J.E.D.I
0
10
true
0
11
true
Note, that the j++ on the line containing the || operator is not evaluated since the first
expression (i<10) is already equal to true.
Introduction to Programming I 81
J.E.D.I
x1 x2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 15: Truth table for ^
The result of an exclusive OR operation is TRUE, if and only if one operand is true and
the other is false. Note that both operands must always be evaluated in order to
calculate the result of an exclusive OR.
Here's a sample source code that uses the logical exclusive OR operator,
val1 = false;
val2 = true;
System.out.println(val1 ^ val2);
val1 = false;
val2 = false;
System.out.println(val1 ^ val2);
val1 = true;
val2 = false;
System.out.println(val1 ^ val2);
}
}
false
true
false
true
Introduction to Programming I 82
J.E.D.I
x1 Result
TRUE FALSE
FALSE TRUE
Table 16: Truth table for !
Here's a sample source code that uses the logical NOT operator,
false
true
Introduction to Programming I 83
J.E.D.I
exp1?exp2:exp3
wherein exp1 is a boolean expression whose result must either be true or false.
If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.
//print status
System.out.println( status );
}
}
Passed
Introduction to Programming I 84
J.E.D.I
class ConditionalOperator
{
public static void main( String[] args ){
int score = 0;
char answer = 'a';
Score = 10
Introduction to Programming I 85
J.E.D.I
6%2*5+4/2+88-10
we can re-write the expression and place some parenthesis base on operator precedence,
((6%2)*5)+(4/2)+88-10;
Coding Guidelines
To avoid confusion in evaluating mathematical operations, keep your expressions simple
and use parenthesis.
Introduction to Programming I 86
J.E.D.I
4.11 Exercises
4.11.1 Declaring and printing variables
Given the table below, declare the following variables with the corresponding data types
and initialization values. Output to the screen the variable names together with the
values.
Number = 10
letter = a
result = true
str = hello
number 1 = 10
number 2 = 20
number 3 = 45
Average is = 25
number 1 = 10
number 2 = 23
number 3 = 5
The highest number is = 23
Introduction to Programming I 87