4 Programming Fundamentals
4 Programming Fundamentals
IV. Programming Fundamentals
Objectives:
In this chapter, the basic parts of the Java program shall be discussed. We will also be discussing
about some coding guidelines or conventions as well as fundamental items in Java
programming.
At the end of this lesson, the student should be able to:
Identify the basic parts of a Java program
Differentiate among Java literals, primitive data types, variable types, identifiers, and
operators.
Develop a simple valid Java program.
Dissecting My First Java Program
public class MyFirstJavaProgram
{
public static void main(String[] args)
{
System.out.println(“Welcome to ICT!”);
}
}
The first line of code,
public class MyFirstJavaProgram
indicates the name of the Java program which is MyFirstJavaProgram. The next line which
contains a curly brace { indicates the start of a block, which will be discussed later in this
chapter.
The next line,
public static void main(String[] args)
indicates the main method of our MyFirsJavaProgram class. The main method is the starting
point of a Java program. All Java programs except applets start with the main method. The next
line which is a curly brace { indicates the start of the block of the main method.
The next line,
System.out.println(“Welcome to ICT!”);
displays the text Welcome to ICT! to the screen. The command System.out.println(), prints the
text enclosed by the quotations to the screen.
The last two lines which contain the two curly braces are used to close the main method and
the class MyFirstJavaProgram 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 MyFirstJavaProgram, you should save it in a file called MyFirstJavaProgram.java.
3. You should write comments in your code explaining what a certain class does, or what a
certain method do.
Java Comments
To comprehend any programming language, there are several kinds of comments which
are used. Comments are notes written to a code for documentation purposes. Those texts are
not part of the program and do not affect the flow of the program. Java supports three types of
comments: C++‐style single line comments, C‐style multi‐line comments and special javadoc
comments.
C++ ‐ style Comment
C++ Style comments starts with //. All the text after // are treated as comments. We can
write only a single line comment use these slashes. Example:
// This is a single‐line comment in a java program.
C‐style Comment
C‐style comments or also called multi‐line comments starts with a /* and ends with a */.
All texts in between the two delimiters are treated as comments. Unlike C++ style comments, it
can span multiple lines. Example:
/* This is a multiple line
comment in a java program */
Special Javadoc Comment
Special Javadoc comments are used for generating an HTML documentation for your
Java programs. You can create javadoc comments by starting the line with /** and ending it
with */. Like C‐style comments, it can also span lines. It can also contain certain tags to add
more information to your comments.
Training-workshop on Object-oriented Programming using Java
22 | P a g e
/**
This is an example of special java doc comment used for
generating an html documentation.
@Charles Jaranilla
@version 64.6
*/
Java Statements and Blocks
A statement is one or more lines of code terminated by a semicolon.
Example:
System.out.println(“Welcome to ICT!”);
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.
public static void main( String[] args ){
System.out.println("Welcome ");
System.out.println("to ICT!");
}
Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the statement.
Example:
public static void main( String[] args ){
Or you can place the curly brace on the next line. Example:
public static void main( String[] args )
{
2. You should indent the next statements after the start of a block. Example:
public static void main( String[] args ){
System.out.println("Welcome ");
System.out.println("to ICT!");
}
Java Identifiers
Identifiers are tokens that represent names of variables, methods, classes, etc.
Naming Guidelines:
Identifiers must begin with a letter (A‐Z, a‐z), an underscore “_”, or a dollar sign
“$”.
Letters may be lowercase or uppercase. Java identifiers are case sensitive. This
means that Identifier1 is not the same as identifier1.
Training-workshop on Object-oriented Programming using Java
23 | P a g e
Subsequent characters may use number 0 to 9.
Example of identifiers:
Hello, main, System, out, public
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.
Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot
use keywords as names for your variables, classes, methods …etc.
Here is a list of the Java Keywords:
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
Const* float native super while
* not used
** added in 1.2
*** added in 1.4
**** added in 5.0
Note: true, false, and null are not keywords but they are reserved words, so you cannot use
them as names in your programs either.
Training-workshop on Object-oriented Programming using Java
24 | P a g e
Primitive Data Types
A data type is a set of values together with a set of operations. The Java programming
language defines eight primitive data types. The following are: boolean (for logical), char (for
textual), byte, short, int, long (integral), double and float (floating point).
Logical – boolean
It is a data type that deals with logical values. A boolean data type represents two
states: true and false.
Example:
boolean result = true;
The example shown above, declares a variable named result as boolean type and
assigns it a value of true.
Textual – char
A character data type (char), represents a single Unicode character. It must have its
literal enclosed in single quotes (’ ’). Example:
‘a’ //The letter a
‘\t’ //A tab
To represent special characters like ' (single quotes) or " (double quotes), use the escape
character \. Example:
'\'' //for single quotes
'\"' //for double quotes
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(“”). Example:
String message=“Hello world!”
Integral – byte, short, int and long
It is a data type that deals with integers, or numbers without a decimal part. Integral
data types in Java uses three forms – decimal, octal or hexadecimal.
Example:
2 //The decimal value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hexadecimal value
Integral types have int as default data type. You can define its long value by appending
the letter l or L.
Integer Length Name or Type Range
be needed at several places in the program. It is critical to know whether the data must remain
fixed throughout the program execution or whether it should change.
Named Constants
A named constant is a memory location whose content is not allowed to change during
program execution. To allocate memory, we use Java’s declaration statement.
Syntax:
static final dataType IDENTIFIER = value;
In Java, static and final are reserved words. The reserved word final specifies that the
value stored in the identifier is fixed and cannot be changed. The reserved word static may or
may not appear when a named constant is declared.
Coding Guidelines:
Notice that the identifier for a named constant is in upper case letters. This is because
Java programmers typically use upper case letters to name a named constant. If the name of
the named constant is more than one word, called a run‐together‐word, then the words are
separated by an underscore.
Example:
final int RATE = 800;
final double CENTIMETERS_PER_INCH = 2.54;
Variables
A variable is an item of data used to store state of objects. It is a memory location
whose content may change during program execution. It 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.
Syntax for declaration:
dataType identifier1, identifier2, … , identifierN;
Example:
double amountDue;
int counter;
char ch;
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 store 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.
Example:
int num = 10;
String name = “Christi”;
Training-workshop on Object-oriented Programming using Java
27 | P a g e
Memory Address Variable Name Data
System.out.print("Remainder ");
System.out.println("a % b = " + (a % b));
System.out.println("c % d = " + (c % d));
System.out.print("Mixing types ");
System.out.println("a + b = " + (a + b));
System.out.println("c * d = " + (c * d));
}
}
Increment and Decrement Operators
Java includes unary increment operator (++) and unary decrement operator (‐‐).
Increment and decrement operators increase and decrease a value stored in a number variable
by 1.
Operator Use Description
Increments op by 1; Evaluates to
++ op++ the value of op before it was
incremented
Relational Operators
Relational operators compare two values and determine the relationship between those
values. The outputs of evaluation are boolean values true or false.
Operator Use Description
> op1>op2 op1 is greater than op2
>= op1>=op2 op1 is greater than or equal to op2
< op1<op2 op1 is less than op2
<= op1<=op2 op1 is less than or equal to op2
== op1==op2 op1 is equal to op2
!= op1!=op2 op1 is not equal to op2
Table 4.4: Relational operators and their uses
Example:
public class RelationalOperatorsSample
{
public static void main(String[] args)
{
int a = 3;
int b = 5;
int c = 5;
System.out.print("Variable values: ");
System.out.println(" a = " + a);
Training-workshop on Object-oriented Programming using Java
29 | P a g e
Example:
public class ANDsample
{
public static void main( String[] args )
{
int a = 0;
int b = 10;
boolean test= false;
test = (a > 10) && (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
test = (a > 10) & (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
}
}
Truth table for Logical OR || and Boolean Logical OR |:
op1 op2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 4.6: Truth table for Logical OR and Boolean Logical OR
The basic difference between || and | operators is that || supports short‐circuit
evaluations (or partial evaluations), while | doesn't.
Example:
public class ORsample
{
public static void main( String[] args )
{
int a = 0;
int b = 10;
boolean test= false;
test = (a < 10) || (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
test = (a < 10) | (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
}
}
Truth table for Boolean Logical Exclusive OR ^:
op1 op2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 4.7: Truth table for Boolean Logical Exclusive OR
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.
Example:
public class XORsample
{
public static void main( String[] args )
{
boolean bol1 = true;
boolean bol2 = true;
System.out.println(bol1 ^ bol2);
bol1 = false;
bol2 = true;
System.out.println(bol1 ^ bol2);
bol1 = false;
bol2 = false;
System.out.println(bol1 ^ bol2);
bol1 = true;
bol2 = false;
System.out.println(bol1 ^ bol2);
}
}
Truth table for Logical NOT !:
op1 Result
TRUE FALSE
FALSE TRUE
Table 4.8: Truth table for Logical NOT
The logical NOT takes in one argument, wherein that argument can be an expression,
variable or constant.
Example:
public class NOTsample
{
public static void main( String[] args )
{
boolean bol1 = true;
Training-workshop on Object-oriented Programming using Java
32 | P a g e
9 && Logical AND
10 || Logical OR
11 ?: Conditional Operator
12 = Assignment
Table 4.9: Java Operators operator precedence.
Given a complicated expression:
20%2*3+6/2+155‐11;
we can re‐write the expression and place some parenthesis base on operator
precedence:
((20%2)*3)+(6/2)+155‐10;
Test Yourself
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.
Variable name Data Type Initial value
number integer 10
letter character a
result boolean true
str String hello
The following should be the expected screen output,
Number = 10
letter = a
result = true
str = hello
Getting the average of three numbers
Create a program that outputs the average of three numbers. Let the values of the three
numbers be, 10, 20 and 45. The expected screen output is,
number 1 = 10
number 2 = 20
number 3 = 45
Average is = 25
Training-workshop on Object-oriented Programming using Java
34 | P a g e
Output greatest value
Given three numbers, write a program that outputs the number with the greatest value
among the three. Use the conditional ?: operator that we have studied so far (HINT: You will
need to use two sets of ?: to solve this). For example, given the numbers 10, 23 and 5, your
program should output,
number 1 = 10
number 2 = 23
number 3 = 5
The highest number is = 23
Operator precedence
Given the following expressions, re‐write them by writing some parenthesis based on
the sequence on how they will be evaluated.
1. a / b ^ c ^ d – e + f – g * h + i
2. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2
3. r ^ s * t / u – v + w ^ x – y++
**(Exercise items were taken from JEDI Introduction to Programming I Student’s Manual)