You are on page 1of 32

Programming Fundamentals

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 MyFirstJavaProgram 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.
1. 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.
2. 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 */

3. 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.
Example:
/**
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.
Example:
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.
 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*** synchronized goto* package default
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.
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.

Range
Integer Length Name or Type

8 bits byte ‐27 to 27‐1

16 bits short ‐215 to 215‐1

32bits int ‐231 to 231‐1

64 bits long ‐263 to 263‐1

Table 4.1: Integral types and their ranges


Floating point – float and double
It is a data type which deals with decimal numbers. Floating point types has
double as default data type. Floating‐point literal includes either a decimal point or
one of the following:
E or e //(add exponential value)
F or f //(float)
D or d //(double)
Example:
3.14 //A simple floating‐point value (a double)
6.02E23 //A large floating‐point value
2.718F //A simple float size value
123.4E+306D //A large double value with redundant D
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.
Integer Length Name or Type Range
32 bits Float ‐231 to 231‐1
64 bits Double ‐263 to 263‐1
Table 4.2: Floating point types and their ranges
Allocating Memory
When you instruct the computer to allocate memory, you tell it what
names to use for each memory location, and what type of data to be stored into
those memory locations. Knowing the location of the data is essential because
data stored in one memory location might 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”;

Memory Address Variable Name Data


10
1001 num
:
:
Address(2000)
1563 name
:
: :
: “Christi”
2000
Java 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.
Arithmetic Operators
One of the most important features of a computer is its ability to
compute. We can use the standard arithmetic operators to manipulate
integral and floating‐point data types in a Java program.
There are five arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulus (division remainder)
Example: System.out.print("Subtracting ");
System.out.println("a - b = " + (a - b));
public class ArithmeticOperatorsSample System.out.println("c - d = " + (c - d));
{ System.out.print("Multiplying ");
public static void main(String[] args) System.out.println("a * b = " + (a * b));
{ System.out.println("c * d = " + (c * d));
int a = 38;
int b = 47; System.out.print("Dividing ");
double c = 23.745; System.out.println("a / b = " + (a / b));
double d = 8.19; System.out.println("c / d = " + (c / d));
System.out.println("Variable values: "); System.out.print("Remainder ");
System.out.println(" a = " + a); System.out.println("a % b = " + (a % b));
System.out.println(" b = " + b); System.out.println("c % d = " + (c %
System.out.println(" c = " + c); d));
System.out.println(" d = " + d); System.out.print("Mixing types ");
System.out.print("\nAdding: "); System.out.println("a + b = " + (a + b));
System.out.println("a + b = " + (a + b)); System.out.println("c * d = " + (c * d));
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
++ op++ Increments op by 1; Evaluates to
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
Example: System.out.println("\n is Less than: ");
System.out.println(" a < b = " + (a < b));
public class RelationalOperatorsSample System.out.println(" b < a = " + (b < a));
{ System.out.println(" c < b = " + (c < b));
public static void main(String[] args) System.out.println("\n is Less than or equal
{ to: ");
int a = 3; System.out.println(" a <= b = " + (a <= b));
int b = 5; System.out.println(" b <= a = " + (b <= a));
int c = 5; System.out.println(" c <= b = " + (c <= b));
System.out.print("Variable values: ");
System.out.println("\n is Equal to: ");
System.out.println(" a = " + a);
System.out.println(" a == b = " + (a == b));
System.out.println(" b = " + b);
System.out.println(" b == c = " + (b == c));
System.out.println(" c = " + c);
System.out.println("\n is Not equal to: ");
System.out.println("\n is Greater than: ");
System.out.println(" a != b = " + (a != b))
System.out.println(" a > b = " + (a > b));
System.out.println(" b != c = " + (b != c));
System.out.println(" b > a = " + (b > a));
}
System.out.println(" c > b = " + (c > b));
}
System.out.println("\n is Greater than or Equal to: ");
System.out.println(" a >= b = " + (a >= b));
System.out.println(" b >= a = " + (b >= a));
System.out.println(" c >= b = " + (c >= b));
Logical Operators
Logical operators have one or two boolean operands that yield a
boolean result. There are six logical operators: && (logical AND), &
(boolean logical AND), || (logical OR), | (boolean logical inclusive
OR), ^ (boolean logical exclusive OR), and ! (logical NOT).
Truth table for Logical AND && and Boolean Logical AND &:
op1 op2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
The basic difference between && and & operators is that &&
supports short‐circuit evaluations (or partial evaluations), while &
doesn't.
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);
}
}
Example:
Truth table for Logical OR || and public class ORsample
Boolean Logical OR |: {
public static void main( String[]
op1 op2 Result args )
TRUE TRUE TRUE {
TRUE FALSE TRUE int a = 0;
FALSE TRUE TRUE int b = 10;
FALSE FALSE FALSE boolean test= false;
test = (a < 10) || (b++ > 9);
The basic difference between || and | System.out.println(a);
operators is that || supports short‐ System.out.println(b);
circuit evaluations (or partial System.out.println(test);
evaluations), while | doesn't. test = (a < 10) | (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
}
}
Truth table for Boolean Logical Example:
Exclusive OR ^: public class XORsample
{
op1 op2 Result public static void main( String[] args )
TRUE TRUE FALSE {
TRUE FALSE TRUE boolean bol1 = true;
boolean bol2 = true;
FALSE TRUE TRUE
System.out.println(bol1 ^ bol2);
FALSE FALSE FALSE
bol1 = false;
bol2 = true;
The result of an exclusive OR System.out.println(bol1 ^ bol2);
operation is TRUE, if and only if one bol1 = false;
operand is true and the other is false. bol2 = false;
Note that both operands must always System.out.println(bol1 ^ bol2);
be evaluated in order to calculate the bol1 = true;
result of an exclusive OR. bol2 = false;
System.out.println(bol1 ^ bol2);
}
}
Truth table for Logical NOT !: Example:
public class NOTsample
op1 Result {
public static void main( String[]
TRUE FALSE args )
FALSE TRUE {
boolean bol1 = true;
The logical NOT takes in one boolean bol2 = false;
argument, wherein that System.out.println(!bol1);
System.out.println(!bol2);
argument can be an expression, }
variable or constant. }
Conditional Operator
Example:
The conditional operator ?: is a public class ConditionalOperatorSample
ternary operator. This means that it takes {
in three arguments that together form a public static void main( String[] args )
conditional expression. The structure of an {
expression using a conditional operator is, String status = "";
int grade = 80;
status = (grade >= 60)?"Passed":"Failed";
op1?op2:op3;
System.out.println(status);
}
wherein op1 is a boolean expression
}
whose result must either be true or false. If
op1 is true, op2 is the value returned. If it
is false, then op3 is returned.
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 Getting the average of three numbers
Declaring and printing variables
Create a program that outputs the average of
Given the table below, declare the following three numbers. Let the values of the three
variables with the corresponding data types and numbers be, 10, 20 and 45. The expected
initialization values. Output to the screen the screen output is,
variable names together with the values.
number 1 = 10
Variable name Data Type Initial value number 2 = 20
number integer 10 number 3 = 45
letter character a
Average is = 25
result boolean true
str String hello
Output greatest value
The following should be the expected screen Given three numbers, write a program that
output, outputs the number with the greatest value
Number = 10
among the three. Use the conditional ?:
letter = a
result = true
operator that we have studied so far
str = hello (HINT: You will need to use two sets of ?: to
solve this). For example, given the numbers 10,
Operator precedence 23 and 5, your program should output,
Given the following expressions, re‐write them
by writing some parenthesis based on the number 1 = 10
sequence on how they will be evaluated. number 2 = 23
number 3 = 5
1. a / b ^ c ^ d – e + f – g * h + i
2. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2
The highest number is = 23
3. r ^ s * t / u – v + w ^ x – y++

You might also like