Vous êtes sur la page 1sur 68

MODULE OF INSTRUCTION

4. Operators and Operator Precedence

In this module, we are going to discuss the different operators that can
be use in Java.

At the end of this lesson, you should be able to:

- Identify the different operators in Java.

- Enumerate the operator precedence.

- Develop a simple program using the concepts mentioned


above.

4.1 Operator

An operator is a symbol that is used to perform a specific


mathematical or logical operation. In Java, we use different types of
operators and these are the following:

 Arithmetic Operators
 Relation Operators
 Logical Operators
 Conditional Operator
 Bitwise and Bit Shift Operators
 Assignment Operators

4.1.1 The Arithmetic Operators

Arithmetic operators are used to perform a basic computation


in a program and it operates the same way that they are used in
algebra. The table below shows the list of arithmetic operators:

*Let us assume that the value of x = 15 and y = 5


Operator Example Result Description
+ (Addition) x+y 20 Adds the value of x and y

Computer Programming 2 1
Week 3-4 Operator and Operator Precedence

- (Subtraction) x-y 10 Subtracts the value of y from x


*
x*y 75 Multiplies the value of x by y
(Multiplication)
/ (Division) x/y 3 Divides the value of x by y.
Divides the value of x by y and get the
% (Modulus) x%y 0
remainder.
x++ (post) 15
++ (Increment) Increment the value of x by 1.
++x (pre) 16
x—(post) 15
-- (Decrement) Decrement the value of operand by 1.
--x (pre) 14

Below is the sample program that implements arithmetic operators:

public class ArithmeticOperatorsDemo {


public static void main(String[] args) {
int x = 13;
int y = 9;
double result = 0;

System.out.println("Variable values:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("result = " + result);

System.out.println(); //add a new line


System.out.println("Arithmetic Operation:");

result = x + y; //performs addition


System.out.println("Addition: x + y = " + result);

result = x - y; //performs subtraction


System.out.println("Subtraction: x - y = " + result);

result = x * y; //performs multiplication


System.out.println("Multiplication: x * y = " + result);

result = x / y; //performs division


System.out.println("Division: x / y = " + result);

result = x % y; //gets the remainder


System.out.println("Modulus: x % y = " + result);

2
MODULE OF INSTRUCTION

result = x++; //increment by 1


System.out.println("Increment: x++ = " + result);

result = x--; //decrement by 1


System.out.println("Decrement: x-- = " + result);
}
}

The output of the program above is:

The Relational Operators

Relational operator is an operator that compares two values.


When you use a relational operator in an operation the result is a
Boolean value (either true or false). The table below shows the list of
relational operators:

*Let us assume that the value of x and y is 5


Operator Example Result Description

Checks if the two values are equal,


== (equal to) x==y true if yes then the result is true,
otherwise false.

Checks if the two values are not


!= (not equal to) x!=y false equal, if yes then the result is true,
otherwise false.

Computer Programming 2 3
Week 3-4 Operator and Operator Precedence

Checks if the value of x is greater


> (greater than) x>y false than the value of y, if yes the result
is true, otherwise false.

Checks if the value of x is less than


< (less than) x<y false the value of y, if yes the result is
true, otherwise false.

Checks if the value of x is greater


>= (greater than than or equal to the value of y, if
x>=y true
or equal to) yes the result is true, otherwise
false.

Checks if the value of x is less than


<= (less than or
x<=y true or equal to the value of y, if yes the
equal to)
result is true, otherwise false.

Below is the sample program that implements relational operators:

public class RelationalOperatorsDemo {


public static void main(String[] args) {
int x = 5;
int y = 10;
int z = 5;
boolean result;

System.out.println(); //add a new line


System.out.println("Relational Operation:");

System.out.println(); //add a new line


System.out.println("Equal to:");
result = x == y; //checks if the two values are equal
System.out.println(x + " == " + y + " = " + result);
result = x == z; //checks if the two values are equal
System.out.println(x + " == " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Not equal to:");
result = x != y; //checks if the two values are not equal
System.out.println(x + " != " + y + " = " + result);
result = x == z; //checks if the two values are equal

4
MODULE OF INSTRUCTION

System.out.println(x + " != " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than:");
result = y > x; //checks if the two values are not equal
System.out.println(y + " > " + x + " = " + result);
result = x > z; //checks if the two values are equal
System.out.println(x + " > " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than:");
result = x < y; //checks if the two values are not equal
System.out.println(x + " < " + y + " = " + result);
result = x < z; //checks if the two values are equal
System.out.println(x + " < " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than or equal to:");
result = y >= x; //checks if the two values are not equal
System.out.println(y + " >= " + x + " = " + result);
result = x >= z; //checks if the two values are equal
System.out.println(x + " >= " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than or equal to:");
result = x <= y; //checks if the two values are not equal
System.out.println(x + " <= " + y + " = " + result);
result = x <= z; //checks if the two values are equal
System.out.println(x + " <= " + z + " = " + result);
}
}

The output of the program above is:

Computer Programming 2 5
Week 3-4 Operator and Operator Precedence

The Logical Operators

Logical operator is an operator that can only be use in an


operation with Boolean values. Like relational operator, it also returns
is a Boolean value. The table below shows the list of relational
operators:

*Let us assume that the value of x=true and y = false


Operator Example Result Description

6
MODULE OF INSTRUCTION

This operator is called Logical


AND operator. If the boolean
&& (logical
x && y False values of both operands are true,
and)
the result will be true, otherwise
false.

This operator is called Logical


OR operator. If there is one
|| (logical or) x || y True operand that has boolean values
of true, the result will be true,
otherwise false.

This operator is called Logical


NOT operator. It returns the
opposite value of its operand. If
! (logical not) !x False an operand to right is true, the
result will be false. And if the
operand to the right is false, the
result will be true.

Below is the sample program that implements logical operators:

public class LogicalOperatorsDemo {


public static void main(String[] args) {
boolean x = true;
boolean y = false;
boolean result;

System.out.println("Logical Expression:");

System.out.println(); //add a new line


System.out.println("Logical AND:");
result = x && x; //result here is true
System.out.println(x + " && " + x + " = " + result);
result = x && y; //result here is false
System.out.println(x + " && " + y + " = " + result);
result = y && x; //result here is false
System.out.println(y + " && " + x + " = " + result);
result = y && y; //result here is false

Computer Programming 2 7
Week 3-4 Operator and Operator Precedence

System.out.println(y + " && " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical OR:");
result = x || x; //result here is true
System.out.println(x + " || " + x + " = " + result);
result = x || y; //result here is true
System.out.println(x + " || " + y + " = " + result);
result = y || x; //result here is true
System.out.println(y + " || " + x + " = " + result);
result = y || y; //result here is false
System.out.println(y + " || " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical NOT:");
result = !x; //result here is false
System.out.println("!" + x + " = " + result);
result = !y; //result here is true
System.out.println("!" + y + " = " + result);
result = !(x && y); //result here is true
System.out.println("!("+ y + " && " + x + ") = " + result);
result = !(x || y); //result here is false
System.out.println("!(" + y + " || " + y + ") = " + result);
}
}

The output of the program above is:

8
MODULE OF INSTRUCTION

The Conditional Operators

Conditional operator is also called as the ternary operator because this


operator consists of three operands. The purpose of this operator is to
evaluate which value should be returned to the variable. The structure
of the expression using this operator is:

operand1?operand2:operand3

The operand1 is a Boolean expression that will be evaluated, if the


value of operand1 is true, operand2 is the value returned, otherwise
operand3 will be returned.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 17;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

Computer Programming 2 9
Week 3-4 Operator and Operator Precedence

The output of the program above is:

Let us discuss what happened in the program after we use the


conditional operator. The expression (age >= 18) ? "Qualified to
Vote!" : "Too young!" uses conditional operator, the first operand
here is (age >= 18) and if we evaluate this we will get the value of
false because the variable age has a value of 17 and it is not greater
than or equal to 18. Since the value of the first operand is false this
expression will return the value of operand3 which is “too young to
vote”.

Let’s try another example, this time we set the value of variable age to
19.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 19;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

The output of the program above is:

Bitwise and Bit Shift Operators

Bitwise and Bit Shift Operators are basically used for bit manipulation,
or using bits of an integral type value to perform bit-by-bit operation.
These operators can be applied to any integral type (long, int, short,
char and byte).

10
MODULE OF INSTRUCTION

There are three Bitwise operators in Java, these are & (Bitwise And), |
(Bitwise Inclusive Or), ^ (Bitwise Exclusive Or) and ~ (One’s
Compliment). The truth table for Bitwise operators are as follows:

A B A&B A|B A^B ~A


0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0

We will be using byte data type for all the examples in bitwise
operators, because byte can be easily represented in bits (byte is only 8
bits while other integral data types is much more than that).

 & (Bitwise And) – The result of the operation will be 1 if it


exists in both operands.
For example: 12 & 5
We need to convert both values to binary:
12 = 00001100, 5 = 00000101
Value Bit Representation
12 1 1 0 0
5 0 1 0 1
Result 0 1 0 0

The table above shows the bit computation of the example, each
bit will be computed separately using the & operator. For
example, let us execute the second row from the table 1 & 0 the
result would be 0. The result if we execute 00001100 & 00000101
expression is 00000100 or 4.

therefore: 12 & 5 = 4

Here is the example of Bitwise And in Java program:

Computer Programming 2 11
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
14 = 00001110, 5 = 00000101
Value Bit Representation
a = 14 1 1 1 0
b=5 0 1 0 1
Result 0 1 0 0
c = 00000100 or 4

 | (Bitwise Inclusive Or) – The result of the operation will be 1


if it exists in either operand.
For example: 9 | 13
We need to convert both values to binary:
9 = 00001001, 13 = 00001101
Value Bit Representation
9 1 0 0 1
13 1 1 0 1
Result 1 1 0 1

therefore: 12 | 5 = 13

Here is the example of Bitwise Inclussive Or in Java


program:

12
MODULE OF INSTRUCTION

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010100, 16 = 00010000
Value Bit Representation
a = 20 1 0 1 0 0
b = 16 1 0 0 0 0
Result 1 0 1 0 0
c = 00010100 or 20

 ^ (Bitwise Exclussive Or) – The result of the operation will be


1 if both operands are different.
For example: 6 | 9
We need to convert both values to binary:
6 = 00000110, 9 = 00001001
Value Bit Representation
6 0 1 1 0
9 1 0 0 1
Result 1 1 1 1

therefore: 6 | 9 = 15

Here is the example of Bitwise Exclussive Or in Java


program:

Computer Programming 2 13
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010010, 17 = 00010001
Value Bit Representation
a = 18 1 0 0 1 0
b = 17 1 0 0 0 1
Result 0 0 0 1 1
c = 00000011 or 3

 ~ (Bitwise One’s Complement) – This operator is used to flip


the bits, it toggles each bit from 0 to 1 or from 1 to 0.
For example:
10001001 and if we flip the each bit it will result to
01110110.

 << (Binary Left Shift) –This operator shifts or move the left
operands value to the left by the number of bits specified in the
right operand.
For example:
00000001 << 2 = 00000100
.01010001 << 3 = 1010001000

 >> (Binary Right Shift) – This operator shifts or move the left
operands value to the right by the number of bits specified in
the right operand, filling with the highest (sign) bit on the left.
For example:
01001000 >> 3 = 00001001

14
MODULE OF INSTRUCTION

.10100001 >> 2 = 00101000


 >>> (Unsigned Right Shift Zero Fill) –This operator shifts
the left operands value to the right by the number of bits
specified in the right operand and shifted values will be filled
with zeros.
For example:
01101000 >>> 2 = 00011010
.10000001 >>> 2 = 00100000

Assignment Operators

Let us discuss first what is Assignment Statement and Assignment


Expressions.

An assignment statement is use to assign value to a variable. It uses =


(equal) operator or any assignment operators to designate a value for a
variable. The syntax for assignment statement is as follows:

<variable> = <expression>;

An expression can be a value, variable or a computation of values and


variables using operators and evaluate them to a value. For example,

m = 2; //assign value of 2 to variable m

cm = m * 100; // assign the multi to variable cm

In assignment statement, we can assign the variable to itself, for


example:

int x = 1;
x=m+1

The assignment statement x = x + 1 means, we assign the addition of x


and 1 to variable x, then the value of x becomes 2 after the statement is
executed.

In the case that we need to assign the value to a multiple variables, we


can do this:

x = y = z = 1;

Computer Programming 2 15
Week 3-4 Operator and Operator Precedence

The statement above is equivalent to:

x = 1;
y = 1;
z = 1;

Augmented Assignment Operators

Java allows you to combine arithmetic operator with assignment (=)


using Augmented Assignment Operators. The list of augment assignment
operators are as follows:

Operator Description Example


Simple assignment operator. Assigns z = x + y will
= values from right side operands to left assign value of x +
side operand. y into z
Add and assignment operator. This
operator adds right operand to the left z += 2 is equivalent
+=
operand and assign the result to left to z = z + 2
operand.
Subtract and assignment operator. This
operator subtracts right operand from z -= x is equivalent
-=
the left operand and assign the result to to z = z – x
left operand.
Multiply and assignment operator. This
operator multiplies right operand with z *= x is equivalent
*= the left operand and assign the result to to z = z * x
left operand.
Divide and assignment operator. This
operator divides left operand with the z /= 2 is equivalent
/= right operand and assign the result to to z = z / 2
left operand.
Modulus and assignment operator. This
z %= x is
operator takes modulus using two
%= equivalent to z = z
operands and assign the result to left
%x
operand.
z <<= 2 is same as
<<= Left shift and assignment operator.
z = z << 2
z >>= x is same as
>>= Right shift and assignment operator.
z = z >> x

16
MODULE OF INSTRUCTION

z &= 2 is same as z
&= Bitwise AND and assignment operator.
=z&2
Bitwise exclusive OR and assignment z ^= 2 is same as z
^=
operator. =z^2
Bitwise inclusive OR and assignment z |= x is same as z =
|=
operator. z|x

Precedence of Java Operators

Operator precedence determines which operators should be the first to execute.


An operator can have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator +. The
table shows the list of operators according to precedence order.

Operators Precedence
postfix expr++, expr--
++expr, --expr, +expr, -
unary
expr, ~, !
multiplicative *, /, %
additive +, -
shift <<, >>, >>>
relational <, >, <=, >=
equality ==, !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
=, +=, -=, *=, /=, %=, &=,
assignment
^=, |=, <<=, >>=, >>>=

For example:

Given a complicated expression,

z = x%2*3+b/4+9-c;

Computer Programming 2 17
Week 3-4 Operator and Operator Precedence

we can re-write the expression and place some parenthesis base on operator
precedence,

z = ((x%2) *3) + (b/4) + 9 - c;

18
MODULE OF INSTRUCTION

Programming Fundamentals

In this module we are going to discuss the basic parts of Java program
and coding guidelines to write readable programs.

At the end of this lesson you should be able to:

- Recognize the parts of Java program.

- Apply Java comments in your program.

- Identify Java literals, primitive data types, variable types and


identifiers.

- Develop a simple program using the concepts mentioned


above.

A. Dissecting a Java program

Let us try to dissect your first Java program:

/**
* Sample Java Program
*/
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World!");
}
}

Always remember that Java code is case sensitive. Now let’s discuss
the each part of the sample program above.

1. The comment:
/**
* Sample Java Program
*/

Computer Programming 2 1
Week 3-4 Programming Fundamentals

All programs should begin with a comment to define the


purpose of it and this will also serve as reference for other
programmers or future used. The comments are not actually part of the
program, the compiler will not generate bytecodes for the comments or
it will just ignore during the compilation process.

2. Class definition
public class HelloWorld

Every Java program is a class. This part of the program


indicates the declaration of the class and we used the class keyword to
define it. All succeeding codes must be placed inside the class
declaration.

The public keyword is an access modifier, it indicates that our


class is accessible anywhere. We will be discussing more about access
modifiers later.

HelloWorld indicates the name of the class. The class name


must be the same as the file name of this program. In this case the
program is saved as HelloWorld.java.

The coding guidelines for naming class are:

 Class name must start with a letter, an underscore or a dollar


sign. It is a good practice that you use uppercase letter at the
beginning of the word, and in the case that the class name is
more than one word, every first character of the word should be
in upper case. For example HelloWorld.
 Class name must only contain letters, digits, underscores or
dollar signs. Always remember that the class name must not
contain whitespace. The

Reserved word is not allowed to use as class name. We are going


to identify all the Java reserved words later.

3. Left curly brace (or opening curly brace) after class declaration
{

A set of curly braces { } is needed for every class. Curly braces are needed to
define the block or the beginning and end of the program or statement. The
opening curly brace indicates the beginning of the block of the statement.

2
MODULE OF INSTRUCTION

4. Main Method
public static void main (String[ ] args)

This part defined the main method of the program. The main method is
needed to start the execution of the program or it is executed first therefore
you need to have at least one method named main. You will not be able to run
a Java program without a main method. The static and void keyword will be
discussed later. The String args[] represents an array of String parameter, this
will also further discuss later. The public keyword is also the same as the
public defined in a class definition, it is an access modifier that sets the
accessibility of the method, in this case our main method is accessible
anywhere, this will be discuss further later.

5. Left curly brace (or opening curly brace) after class main method
{

Since the method also contained codes or block of codes, opening


curly brace is also needed to indicate the beginning of the method.

6. Output Statement
System.out.println("Hello World!");

The System.out.println( ) is an output statement used in Java. This


statement will print any text inside the double quotes and add a new line at the
end of the printed text. Since the "Hello World!" was placed inside the
System.out.println( ) statement therefore it will output on the screen the text
Hello World!.

7. Two Right curly braces (or closing curly braces)


}}

The right curly brace (}) represents the end of the block of codes. The
two right curly braces are used to end the main method and class definition.

Reminders:

1. You should always save your Java program with a filename


extension .java.
2. Your java program filename should match the name of your
class declaration. For example, public class HelloWorld should
be saved as HelloWorld.java.

Computer Programming 2 3
Week 3-4 Programming Fundamentals

B. Java Comments

The Comment is an understandable explanation or notes of a code in a


program and it makes the code easier to understand. Although comment is
part of the program, it is not translated into bytecode during the compilation,
the compiler will just ignore the comment.

Comments are very useful, especially in a big project where several


programmers are working together and sharing codes with each other. It
would be very difficult or time consuming reading others code, but having
comments along with code you can easily understand the purpose of the code.
Even you are not working on a team comments are still very useful, as a
programmer we write a tremendous line of codes and I am sure that you will
not be able to recall all the codes that you have written that's why we need
comments to remind us about what we have written. There are three types of
comments in Java these are single line comments, multi-line comments and
documentation comments.

1. Single line comments.


To have a single line comment you need to place two forward slashes
// before the text. All text after the // will be treated as a comment. For
example:
// This is a single line comment.

2. Multi-line comments.
This comment is used for block commenting or series of multiple lines
of code. It starts with /* then followed by the text you want to comment and
then ends with */. All text inside the /* */ will be treated as comments. For
example:
/* This multi-line comment,
it can support multiple
line of codes. */

3. Documentation Comments
It is almost the same as multi-line comment that covers a block of
codes commenting but has a special purpose. Documentation comments are
used by the JDK java doc tool to generate HTML documentation for your
Java programs.
/**
* The HelloWorld program is an application that \n
* simply displays "Hello World!".

4
MODULE OF INSTRUCTION

*
* @author Juan Dela Cruz
* @version 1.0
*/

C. Java Statements and blocks

A statement is an action that is defined in the program to perform a


certain task. The common actions include variable declarations, assigning
value and calling and defining the method, traversing collection and
performing decision construct.
A statement may consist of one or more lines of code that ends in a
semicolon. An example of a single statement is:
System.out.println(“Hello World!”);

A block is a group of zero or more statements enclosed in opening and


closing curly {} brackets and can contain nested blocks. The following code
shows an example of a block:

public static void main(String[] args){ //begin block


System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block

Coding Guidelines:
1. In block, you should place opening curly brace in line with the statement.
For example:
public static void main(String[] args){

2. Always indent the statements after the begin block, for example:
public class HelloWorld{ //begin block 1
public static void main(String[] args){ //begin block 2
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block 1
} //end block 2

Computer Programming 2 5
Week 3-4 Programming Fundamentals

3. Closing curly brace should be vertically aligned with the statement that
defines the block (they should be on the same column number). For
example,
public class HelloWorld{ //begin block 1
public static void main(String[] args){ //begin block 2
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block 1
} //end block 2

D. Identifiers

Identifiers represent the name of variable, method, class, package and


interface. It is simply used to identify a declaration. In the HelloWorld program,
HelloWorld, args, main and System are identifiers.

Rules for an Identifier (Take note that invalid identifier will result to syntax
error.):
 Identifier must start with a letter, an underscore or a dollar sign.
 Identifier must only contain letters, numbers, underscores or dollar
signs.
 Special characters, such as a semicolon, period, whitespaces, slash or
comma are not allowed to be used as Identifier.
 Identifiers are case sensitive in Java. For example hello and Hello are
two different an identifiers in Java.
 Java Keywords is not allowed to use as an identifier. We are going to
identify all the Java reserved words later.

The following are the examples of invalid identifiers:


 1stInput - Identifier begins with a number.
 Hello World - Identifier contains whitespace or special character.
 O'Reilly - Identifier contains apostrophe or special character.
 static - Static is a java keyword.

Coding Guidelines:
1. Use meaningful, descriptive or straight forward identifier, for example, if
you have a method that computes for the grade, name it computeGrade.

6
MODULE OF INSTRUCTION

2. Avoid using abbreviations for identifiers and use complete words to make
it readable.
3. In naming classes you should capitalize the first letter and for methods and
variables the first letter should be in lowercase. For example:
public class Hello (class identifier Hello starts with a capital letter)
public void main (method declaration main starts with small letter)
4. For multi-word identifiers use camel case. Camel case may start with a
capital letter or with a lowercase letter and all the succeeding words must
start with a capital letter. For example,
HelloWorld (this is a class identifier)
computeGrade (this is method identifier)
firstName (this is a variable identifier)

5. For constant variable, the convention changes slightly, we need to


capitalize all the letters and separate the succeeding words with
underscore. For example, MAX_CREDIT = 10;
6. Avoid using underscore and dollar ($) sigh at the start of the identifier. We
only use underscore (at the start of an identifier) in an inevitable situation
where we need to use the reserved word as an identifier. For example,
_for, _true. And in some cases you may find a dollar sign (at the
beginning of the identifier) in auto-generated identifiers.

E. Java Keywords

Keywords are reserved words defined by Java for specific purposes. It


cannot be used as an identifier or name for class, method, variable, etc.
Please refer below for the list of keywords.

abstract double Int super


assert else interface switch
boolean enum long synchronized
break extends native this
byte final new throw
case finally package throws
catch float private transient
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static

Computer Programming 2 7
Week 3-4 Programming Fundamentals

do instanceof strictfp

In addition to the keywords listed above true, false and null are also
reserved words. The keywords goto and const are keywords reserved in
other programming languages like C, C++, c#, etc. but currently not used
in Java. There will be a discussion of each keyword as we go along the
way.

F. Java Literals

A Java literal is a constant value represented directly in the code.


Literals can be assigned to any primitive type variable. The following are
the different literals in Java:
 Integer Literals
 Floating-Point Literals
 Boolean Literals
 Character Literals
 String Literals

Integer Literal
An integer literal can be stored to an integral type variable. It can be a
decimal, binary, octal or hexadecimal constant. There is a format that we need
to follow in order to use integer literal. To represent a binary integer using a
prefix 0b or 0B (zero B), to represent hexadecimal integer use a prefix 0x or
0X (zero X), for octal use a prefix 0 (zero) and decimal has no prefix.
The following are the examples of integer literal in a program:
System.out.println(42); //Displays 42
System.out.println(0b101010); //Displays 42
System.out.println(0x2A); //Displays 42
System.out.println(052); //Displays 42

By default, the integer literal data type is int. An int value is between
-2147483648 and 2147483647. In case, that you want to use long type literal
you need to append the letter "L" or "l" on it. For example, to use
21474836470 in a Java program, you have to write it as 21474836470L,
because if you didn’t append “L” on the literal you will get an error since the
value exceeds the range for int value. We should use the L suffix in long type
integer literal because l (lowercase L) can easily be confused with 1 (the digit
one).
The following are the examples of integer literal with long data type in
a program:
System.out.println(21474836470L); // Displays 21474836470
System.out.println(0b101010L); // Displays 42

8
MODULE OF INSTRUCTION

System.out.println(0237777777766L); //Displays
21474836470
System.out.println(0x4FFFFFFF6L); // Displays 21474836470

Floating-Point Literals
Floating-point literal is an integer literal followed by a decimal point.
By default, the floating-point literal data type is double, but if you want to
explicitly express that the floating point literal is a double type value you can
append d or D on it and in case that you need to use type float value you need
to append f or F on it. For example, you can use 3.1416f or 3.1416F for a float
value, and 3.1416, 3.1416d or 3.1416D for a double value.

You can express floating-point literals either in decimal form or


scientific notation. The following are the examples of floating-point literal
expressed in scientific notation:
 The scientific notation for 1234.56 is 1.23456 * 103 can be
written as 1.23456E3 or 1.23456E+3 in Java program.
 The scientific notation for 0.00123456 is 1.23456 * 10-3 can be
written as 1.23456E-3 in Java program.

Boolean Literals
Boolean literals have only two possible values, true and false.

Character Literals

Character literals are enclosed in single quotes; for example, 'a' can be
stored in a simple variable of char type.

A character literal can be:


 A plain character (e.g., 'x')
 A Unicode character (e.g., '\u02C0'). A Unicode character is a 16-
bit character set, and it allows the inclusion of symbols and
special characters from other languages.
 An escape sequence (e.g., '\n'). An escape sequence is a character
preceded by a backslash (\) and followed by a character that has
special meaning to the compiler. Below are the Java escape
sequences:

Escape Sequence Character Represented

\t Tab
\b Backspace

Computer Programming 2 9
Week 3-4 Programming Fundamentals

\n New line
\r Carriage return
\f Form Feed
\' Single quote character
\" Double quote character
\\ Backslash character

String Literals
String literals are constant value consist of zero or more characters
enclosed in double quotes, for example, “Hello World”.
String literals may contain escape sequence character. When an escape
sequence is used in a print statement, it will be evaluated according to its
purpose. For example, if you want to print a text that is enclosed in double
quotes you need to use the escape sequence \". The code below demonstrates
the printing of text enclosed in double quotes:
System.out.println("Escape sequence \"double quote\" demo.");
The code above will display:
Escape sequence "double quote" demo.

G. Primitive Data Type

A data type is a classification of a particular type of data. It


specifies what kind of value can be stored in a particular data item and
determines how much space it occupies in storage. There are eight
primitive data types in Java, these are byte, short, int, long, double, float,
boolean and char.

byte

 byte data type is an 8-bit signed integer


 byte data type can hold values from -128 to 127 (or -27 to 27 -
1)
 The default value for byte data type is 0
 It saves memory, it only consumes eight bits as against to 32
bits for integer.
 Examples are:
byte b1 = -60;
byte b2 = 101;

short

10
MODULE OF INSTRUCTION

 short data type is a 16-bit signed integer


 short data type can hold values from -32768 to 32767 (or -215
to 215 - 1)
 The default value for short data type is 0
 Like bytes, it also saves memory and better alternative to int
data types, particularly if your data falls within the specified
range.
 Examples are:
short s1 = -129;
short s2 = 128;

int

 int data type is a 32-bit signed integer


 int data type can hold value from - 2,147,483,648 to
2,147,483,647 (or -231 to 231-1)
 The default value for int data type is 0
 It is usually used as the default data type for integral values.
 Examples are:
int i1 = -32769;
int i2 = 32768;

long

 long data type is a 64-bit signed integer


 long data type can hold value from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (or 263 to 263-1)
 The default value for long data type is 0L
 Long data type is used when you need a bigger range than int.
 Examples are:
long l1 = -32769L;
long l2 = 32768L;

float

 float data type is a 32-bit IEEE 754 floating point


 float data type can hold a negative value from -3.4028235E+38 to -
1.4E–45, and a positive value from 1.4E -45 to 3.4028235E +38.
 The default value for float data type is 0.0F
 float data type consumed less memory as compare to double.
 Examples are:
float f1 = -1.2345F;
float f2 = 3.4028235E+38F;

Computer Programming 2 11
Week 3-4 Programming Fundamentals

double

 double data type is a 64-bit IEEE 754 floating point


 double data type can hold a negative value from -
1.7976931348623157E+308 to -4.9E-324, and a positive value from
4.9E - 324 to 1.7976931348623157E + 308.
 The default value for double data type is 0.0D
 The double type is twice as big as float type, so you should use this
type because it is more accurate than the float type.
 Examples are:
double d1 = 1.23456;
double d2 = -12.3456D;
double d3 = 12.3456D;

boolean

 boolean data type represents 1 bit of information.


 boolean data type can only have a value of either true or false.
 The default value for boolean data type is false.
 The double type is twice as big as float type, so you should use this
type because it is more accurate than the float type.
 Example: boolean odd = true;

char

 char data type represents single 16-bit Unicode character.


 char data type can have a value from \u0000 (or 0) to \uFFFF (65,535)
 The default value for char data type is '\u0000'
 Char data type is used to store any single character and it must be
enclosed in single quotes.
 Examples are:
char letterA = ‘a’; //The letter a
char newLine = ‘\n’; //A new line
char hash = ‘\u0023’; //for hash sign (#)

The Unicode standard has been extended to allow up to 1,112,064


characters. The Java character data type can only support 65,535 characters
and it is sometimes referred to as the Basic Multilingual Plane (BMP) and
those characters that go beyond the 16-bit (65,535) limit is called
supplementary characters. Supplementary characters are represented as a pair
of char values and it can be handled using String data type. String is not a
primitive data type (it is a Class or non-primitive data type). A String data
type contains multiple characters and enclosed in double quotes.

12
MODULE OF INSTRUCTION

For example:
String message = “Hello world!”;
String supplementaryCharacter = “\uD801\uDC00”;

H. Variables

Variable is used to store a specific value or literals that can be used


later in a program. Since it holds value, you may assign or call its value in
a statement or block. Variable has data type and name. Variable Data Type
identifies the kind of value that you can store, like number or text.

Declaring and Initializing Variable

To declare a variable you need to have the following:

<data type> <name> [= initial value]

Data type and name are both required and initial value for variable is optional.

Below is the example of implementation of variables in a program:

The output of the program is:

The line 4 or this code

Computer Programming 2 13
Week 3-4 Programming Fundamentals

is a variable declaration with initial value. The word meter is the variable
name, int is the data type and 2 is the initial value.

Line 5 or this code

is also a variable declaration and it has a variable name of centimeter and int
data type and has no initial value.

Line 6 or this code

is a statement where we assign value to variable centimeter. We call this


statement as a variable assignment. This statement will just perform the
operation and assign the result to variable centimeter. In this case will just
multiply the value of meter (which is 2) to 100 and will result to 200. The
value of centimeter now is 200.

Line 7 and 8 or this code

will just print the value inside the println. The + sign in the code is used to
combine or concatenate the values in between the symbol. In this case the
statement will print: 2 m = 200 cm.

Printing Variable

There are two statements that you can use to display or output the value from
a variable, these are the following:

 System.out.println()
 System.out.print()

14
MODULE OF INSTRUCTION

The two statements are both used to display value, the only difference
is the System.out.println() appends newline after it display the value while the
other one does not.

Below is the implementation System.out.print() in java program::

The output of the example above is:

Below is the example of displaying variable using System.out.println():

The output of the example above is:

Computer Programming 2 15
MODULE OF INSTRUCTION

Getting to know the programming


environment

In this module we are going to know the programming environment of


Java. We are also going to discuss on how to write, compile and run
Java programs using Netbeans IDE (Integrated Development
Environment) and Text Editor.

At the end of this lesson you should be able to:

- Write simple Java code in Text Editor and Netbeans.

- Compile and run Java code using Command Line and


Netbeans.

- Differentiate the three types of error, the syntax errors, runtime


errors and logical errors.

A. The “Hello World!” application, your first Java Program

In this section we are going to write, compile and run a Java program
in Text Editor and Command Line. We are going to create a simple
program that will display the words “Hello World!”. Below is the
source code of our first program:
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World!");
}
}

Before we can run any Java program, we will need the following:

- Java Standard Edition (SE) Development Kit 8 (JDK8).

- A text editor, an example of this is Notepad.

Let’s start creating the “Hello World” program. The following are the
steps to create the program:

Step1 : Start the text editor.

Computer Programming 2 1
Week 2 Getting to know the programming environment

In this case we are going to use Notepad. Notepad is found in the


Accessories folder of the Start Menu.

Step 2: Write the source code in Notepad text editor.

2
MODULE OF INSTRUCTION

3. Save the source file.

We need to save the file as HelloWorld.java but before we do that we


need to first create a separate folder (let's name it JAVAPROGRAMS)
in drive C, the folder will be also used for all our future Java source
codes.

To save the file in notepad, on the menu bar, click file then select
"save as".

Computer Programming 2 3
Week 2 Getting to know the programming environment

The Save dialog box will show up, navigate to drive C and then select
the folder that you created a while ago.

On the file name input box, enter "HelloWorld.java" and change the
"Save as type" to "All Files" and then click save.

4
MODULE OF INSTRUCTION

Step 4. Compiling the source code using the windows command


line.

The first thing that we need to do to compile the source code is launch
the command prompt, click the start menu and on search bar type
command or cmd.

When the command prompt open up, by default it will take you to the
current user directory. In the example below the default directory is in
Administrator.

Computer Programming 2 5
Week 2 Getting to know the programming environment

We need to navigate to the folder where the Java source code was
saved or we need to go to “C:\JAVAPROGRAMS”. On the command
line type “cd C:\JAVAPROGRAMS” then press enter. You are now
inside the JAVAPROGRAMS directory. The “cd” command stands
for change directory; it is used to change the current directory.

Let us check whether we are in the right directory and see if the Java
source file was saved in this directory. On the command line type “dir”
then press enter, your Java source file should be displayed. “dir”
command is used to display files and subdirectories inside a directory.

6
MODULE OF INSTRUCTION

To compile the Java source file we need to enter “JavaC [filename]”


in the command line, in our case we should enter “JavaC
HelloWorld.java”.

As we discuss in the phases of a Java program, the compilation


process generates bytecodes, in this case the HelloWorld.class will be
created and this contains the actual Java bytecode.

Computer Programming 2 7
Week 2 Getting to know the programming environment

To run the Java program, we need to enter “Java [filename]” or in our


case “Java HelloWorld”. You have just run your first program and
displayed the message, “Hello World!”

Resolving an error: "javac is not recognized as an internal or


external command"

If there is a problem occuring during the compilation like the figure


below, we need to set the JavaC path in the command prompt because
Java compiler or JavaC does not recognize in command prompt. What
we perform during the compilation is call or executes JavaC program
using command line, the error occurs because we are calling a program
which is not present in the current directory. To set the path, we need
to locate the directory of the JavaC which is by default it is located in

8
MODULE OF INSTRUCTION

"C:\Program Files\Java\jdk[version]\bin". Once the path was set for


JDK all files and programs inside the path directory (such as JavaC,
Java, etc.) will be available to be executed in the command line.

There are two ways to set Java path, one is temporary and other one is
permanent.

1. Setting the temporary path of JavaC


a. Launch command prompt
b. Enter the path command, for example,
“path C:\Program Files\Java\jdk1.7.0_03\bin”

Computer Programming 2 9
Week 2 Getting to know the programming environment

2. Setting permanent path of JDK.


a. On your desktop, right click the computer icon, then
click properties.

b. Click the advance system settings

c. Select the Advance tab and click the environment


variables

10
MODULE OF INSTRUCTION

d. Click the new button of user variable.

Computer Programming 2 11
Week 2 Getting to know the programming environment

e. On the variable name field enter the “path” word

12
MODULE OF INSTRUCTION

f. Copy the path of the JDK bin folder.

Computer Programming 2 13
Week 2 Getting to know the programming environment

g. Paste the copied path in the variable value field. Then


click all the OK buttons from all the windows you have
opened.

B. Errors

The example source code that was provided in this module is


free from error, if it happens that you still encountered error
during compilation aside from unrecognized JavaC you
probably got a syntax error and this section will be able to help
understanding your error. There are three types of error that
you might encounter in Java programming:

14
MODULE OF INSTRUCTION

 Syntax errors
 Runtime errors
 Logical errors

Syntax Errors
The errors occur when the syntax of the language is
violated, specifically when a word or symbol was not correctly
placed in an instruction or statement of the program.

 Misspelled keyword, variable and method names or


incorrect used of capitalization.

The figures above demonstrate a program that has


syntax errors. After compilation of the program, the
compiler encountered two errors. The first error
message tells us that we had an error on line 1 of our

Computer Programming 2 15
Week 2 Getting to know the programming environment

program and it is pointed on the word publix, which is a


misspelled word for public. The second error message
suggests that we had an error in line 6 and pointed in
between of the words Public and static, as you can see
the first letter of the word Public is in upper case and it
is expected to be in lower case.

 Missing semi-colon at the end of the statement or


incorrect used of symbols.

The program above obviously produces errors, the


violations are, first the use of comma (,) instead of dot
(.) and the second one is missing semi-colon at the end
of the statement. You can compile the program above to
see the generated error message.

 Brackets such as curly braces “{}”, parentheses “()“


and square brackets “[]” is not properly matches. Never
forget to enclose your brackets, make it a habit to type
the brackets in pair (opening and closing bracket).

Runtime Errors

Runtime errors only occur after compilation (when there is


no syntax error in the program) and running your program.
Runtime is when the program is running therefore you can
only encounter runtime error during execution of the
program or when you are using your program. The
common examples of these are, trying to open a file, but

16
MODULE OF INSTRUCTION

the file doesn’t exist or is corrupted and when you try to


execute division by zero.

The figure above is a sample program that has no syntax


error, but will produce runtime error and it has a statement
that performs a division by zero. The figure below shows
that the program was successfully compiled and didn’t
produce syntax error, however when we tried to run the
program, we encountered runtime error. The message tells
us that we are executing division by zero, which is not
possible or incorrect.

Logical Errors

Computer Programming 2 17
Week 2 Getting to know the programming environment

Logical errors also occur once the program is in use and


these errors will not interrupt the execution of the program.
Errors are those where the program is running smoothly,
but produces unwanted or unexpected result from what you
designed. The common examples of these are:

 Incorrect used of mathematical operation like using


of + symbol for subtraction.
 Displaying the incorrect message.
 Using data from incorrect source.

The figure below is an example that demonstrates a logical


error. As you can see there is no error message being
shown or the program was not interrupted, however we can
notice that there is something wrong in the output, we want
the program to show the addition of “2” and “2” but instead
it displayed the concatenated number “22”. Logical errors
are considered the most difficult type of errors to fix
because it is not clear where the errors originate since it
didn’t display any information about the error.

18
MODULE OF INSTRUCTION

Using NetBeans
In our previous discussion, we tackled the hard way of
running Java program. Let’s now try the easiest way of
writing and running the Java program.

In this part of the lesson we are going to discuss writing


and compiling Java program using NetBeans. Netbeans is
an Integrated Development Environment or IDE, it is a
programming environment that provides comprehensive
facilities to programmers for Developing Java programs.
NetBeans contains a source code editor, GUI Builder,
Compiler, interpreter and a debugger.

Step 1: Start NetBeans

To open the NetBeans program, double click the NetBeans


shortcut icon in your desktop.

The figure below shows the graphical user interface (GUI)


of the NetBeans IDE.

Computer Programming 2 19
Week 2 Getting to know the programming environment

Step 2. Creating a project.

To create a project, in the IDE menu bar choose File then


click New Project.

20
MODULE OF INSTRUCTION

After clicking the New Project, a New Project dialog bar


will show up. On the category list, select Java and on the
Project list, select the Java Application, then click the Next
button.

Computer Programming 2 21
Week 2 Getting to know the programming environment

In the New Application Dialog, do the following (as shown


in the figure below):

 In the Project Name field change the value to


JavaPrograms.
 Leave the default value of the Project Location, by
default our project is located in
C:\Users\<user>\Documents\NetBeansProjects
directory and all the files will be saved in
C:\Users\<user>\Documents\NetBeansProjects\Jav
aPrograms.
 Leave the Use Dedicated Folder for Sharing
Libraries unchecked.
 On the Create Main Class field, enter
“HelloWorld” and then click the Finish button.

The Java Application project is now created and opened in


the IDE. The IDE will have the following components:

 Projects window displays all projects loaded in the


IDE and it is presented in a tree view. This window
shows the components of the project such as source
files, libraries, etc.

22
MODULE OF INSTRUCTION

 Source Code Editor Window where you can write


Java source code.
 Navigator window where you can navigate
elements within the selected class.

Step 3. Writing your program in NetBeans IDE...

Since you have left the Create Main Class checked in the
New Application dialog the NetBeans IDE have generated
HelloWorld.java file that contains code that is shown in the
source code editor window.

Let us now create a program that displays “HelloWorld”


message. Replace the line of code:

// TODO code application logic here

with this statement:

System.out.println(“Hello World!”);

Computer Programming 2 23
Week 2 Getting to know the programming environment

Save the code by selecting File on the menu bar and then click
save or we can simply press CTRL + S.

Step 4. Compiling and Running your program in NetBeans


IDE.

NetBeans IDE has Compile on Save feature, it


automatically compiles the Java source file after saving.
Therefore, we don’t need to manually compile the project
in order to run it.

NetBeans IDE has a real time syntax error checker, the


error icon (red glyph in the left margin) and red underline
on the statement will automatically show up if you typed a
misspelled keyword or forgot to enter the required symbol
(anything that violates the syntax).

24
MODULE OF INSTRUCTION

There are three ways to run your program in NetBeans


IDE:

 Select the Run on the menu bar then click Run


Project.

 Click the Run Icon on the Tool bar

 Press F6

Computer Programming 2 25
Week 2 Getting to know the programming environment

The output of the program will be shown in the output


window of NetBeans IDE.

LESSON SUMMARY:

1. You can write java program using notepad and compile it using
windows command line.

2. Set Java compiler path in command line to resolve "javac is not


recognized as an internal or external command" error.

3. There are three types of error in java these are Syntax errors, run
time errors and logical errors.

4. NetBeans IDE is a programming environment that provides


comprehensive facilities to programmers for Developing Java
programs.

26
MODULE OF INSTRUCTION

Introduction to Java

This is the first module of the course Computer Programming 2 and it


is about introducing Java. In this module we will be discussing the
background of Java and the Java technology. We will also discuss the
features and phases of Java.

Java Background
Java was developed in 1991 by a team of engineers called the “Green
Team” led by James Gosling and released in 1995 by Sun
Microsystems. It was initially called oak after an oak tree that stood
outside his office. Java was originally designed to use in embedded
chips in various consumer electronic appliances such as toasters and
refrigerators. In 1995 its name was changed to Java because a
trademark search revealed that Oak was used by Oak Technology and
it was also redesigned for developing Web applications. All the Java
releases since 2010 is owned by Oracle because they acquire Sun
Microsystems in that year.

Today Java is everywhere, in any devices and platform, in the Internet


and local device, from smart phones to computers, games to business
solutions. You can find Java anywhere and Java helps us to have a
better future.

What is Java Technology?

A programming language, Java is a general-purpose programming


language that can be used to create all kinds of applications on your
computer. Java syntax is mostly derived from C and C++, therefore if
you know how to write in C or C++ you could easily write Java
programs.

Computer Programming 2 1
Week 3-4 Administering Users and Roles

A Java platform, it is a software environment where the Java program


runs. There are four platforms that Java offers, these are:

 Java Standard Edition (Java SE), it is used to develop client-


side applications or an application that can run standalone.
 Java Enterprise Edition (Java EE), it is used to develop server-
side or network applications. There are several technologies
that JavaEE offers, such as Java servlets, JavaServer Pages
(JSP), and JavaServer Faces (JSF).
 Java Micro Edition (Java ME), it is used to develop
applications for small devices, such as cell phones, PDA and
smart phones.
 JavaFX is a platform for creating desktop applications and rich
internet applications that run across a wide variety of devices.

Phases of Java Program

The first phase of a java program is writing your source code in a text
editor or IDE (Integrated Development Environment). The text editors
that can be used are notepad, vi, sublime, etc. and for the IDE are
NetBeans, Eclipse, BlueJ, etc. The written code should be saved with
the .java extension.

2
MODULE OF INSTRUCTION

After creating the source file, you need to compile it using the javac
compiler. This process will produce a compiled file containing
bytecodes and with the extension name of .class. Normally the
compiler (other programming language like C, C++, etc.) should
produce object code (executable program) that is understandable by
the processor, however in Java the compiled object is a .class file
which contains bytecode that is not readable by your processor.

The Java Virtual Machine is responsible in interpreting your .class file.


It converts the bytecodes into another code that can be understood by
your processor. Since it is interpreted, the code will only be translated
everytime you perform operation of you program, unlike compiler all
your code will be translated at once.

Java Features
The main reason why they created Java was to deliver a portable and
secured programming language. In addition to these major features,
other Java features are the following:

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. High Performance
10. Multithreaded
11. Distributed

Computer Programming 2 3
Week 3-4 Administering Users and Roles

Simple

Java is simple because of the following:

 It is easy to learn and the syntax is easy to understand, clean


and user-friendly.

 The syntax is mostly derived from C and C++ therefore it is


easier to learn Java after C or C++. The confusing features of
C++ were removed such as pointers, operator overloading etc.

 It has Garbage Collector that automatically removed


unreferenced or unused objects. One of the problems
encountered when writing a program is memory leak or the
program consumes too much available memory because the
programmer forget to deallocate memory. In Java, you no
longer need to deallocate the memory the garbage collection
thread is responsible for cleaning your memory.

Object Oriented

In Java, program focuses on Object that may contain data or


attributes and behaviour or methods. Java programs are made out
of objects that interact with one another, and it can be easily
extended since it is based on Object model.

4
MODULE OF INSTRUCTION

Platform Independent

A Java program is platform independent, which means you just


need to write a program once and run it on many different operating
systems. Unlike other programming languages such as C, C++, etc.,
they are compiled on a specific platform. The Java Virtual Machine or
JVM is responsible for making the same program capable of running
on multiple platforms.

Code Security

Java is secured which allow us to develop a program that is


free from virus or tampering. Java is secured because of the following
features:

Computer Programming 2 5
Week 3-4 Administering Users and Roles

 Java programs run inside a virtual machine (JVM). The Java


Virtual Machine is an abstract machine that is implemented by
emulating software on a real machine. Typically the program
(created from another language like C) directly interacts with
the operating system and if the program is infected with virus,
it will definitely affect the operating system, unlike in Java
program will not directly run though the operating system.

 The Class Loader is responsible for loading classes into Java


Virtual Machine. It adds security by separating the package for
the classes of the local file system from those that are imported
from network sources and classes are verified before it is
loaded to JVM.

 The Bytecode Verifier is responsible for traversing the


bytecode and checking the code fragments for illegal code that
can violate access right to object. It checks the bytecodes for
the correct number and type of operands, data types are not
accessed illegally, the stack is not over or underflowed and that
methods are called with the appropriate parameter types.

Robust

Robust means strong and effective in all or most situations and


condition. Java uses strong memory management and automatic
garbage collection mechanism. It has no pointers that avoids
security problem. There is an exception handling and type
checking mechanism. The Java Compiler checks the program for
any errors and interpreter checks any run time error.

Architecture-neutral

Architecture refers to the processor (CPU Architecture), Java


programs can run on any processors without considering the
architecture or vendor (providers). The languages like C or C++ is

6
MODULE OF INSTRUCTION

architecture dependent which means you need to have a separate


program for 32-bit and 64-bit Operating System.

Portable

According to Sun Microsystem:

“Portability = Platform Independent + Architecture Neutral”

Language Portability is when you can do the WORA ("Write


once, run anywhere") program. Java bytecode can be ported to
any platform regardless its architecture. It's a combination of
platform independence and architectural neutral that makes Java
portable.

Dynamic

Byte code makes Java become dynamic and can adapt to an


evolving environment. New features can be easily integrated or
the software can be easily extended without creating a new
version.

High Performance

Even though Java is an interpreted language the execution speed


of Java programs improved significantly because of just-in-time
compilation (JIT). Java is also faster compared to any interpreted
language because it uses byte code that is close to native code.

Computer Programming 2 7
Week 3-4 Administering Users and Roles

Multithreaded

Multithreading is a capability of a single program to execute


several tasks independently and continuously. Playing music
while downloading the video file in one program is an example of
multithreading. Multithreading is important for multimedia,
network programming etc.

Distributed

Distributed computing is a model wherein the components of a


software are located in multiple networked computers working
together to achieve common goals. In this way, it will improve the
efficiency and performance of the software. For example, in a 3-
tier model, rendering user interface is performed in one computer,
another computer conducts reading and writing to the database
and business logic is done in another computer. Java allows you to
create distributed software, since networking capability is
integrated into it.

LESSON SUMMARY:

In this lesson, you should have been introduced to Java.

 Java was developed in 1991 by James Gosling.

 Java is a programming language and a platform.

 Java code generates bytecodes after compilation and


interpreted by JVM.

8
MODULE OF INSTRUCTION

 Java is simple, object-oriented, platform independent, secured,


robust, architecture neutral, portable, dynamic, high
Performance, multithreaded and distributed.

Computer Programming 2 9

Vous aimerez peut-être aussi