Prelim PDF
Prelim PDF
Prelim PDF
In this module, we are going to discuss the different operators that can
be use in Java.
4.1 Operator
Arithmetic Operators
Relation Operators
Logical Operators
Conditional Operator
Bitwise and Bit Shift Operators
Assignment Operators
Computer Programming 2 1
Week 3-4 Operator and Operator Precedence
System.out.println("Variable values:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("result = " + result);
2
MODULE OF INSTRUCTION
Computer Programming 2 3
Week 3-4 Operator and Operator Precedence
4
MODULE OF INSTRUCTION
Computer Programming 2 5
Week 3-4 Operator and Operator Precedence
6
MODULE OF INSTRUCTION
System.out.println("Logical Expression:");
Computer Programming 2 7
Week 3-4 Operator and Operator Precedence
8
MODULE OF INSTRUCTION
operand1?operand2:operand3
Computer Programming 2 9
Week 3-4 Operator and Operator Precedence
Let’s try another example, this time we set the value of variable age to
19.
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:
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).
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
Computer Programming 2 11
Week 3-4 Operator and Operator Precedence
therefore: 12 | 5 = 13
12
MODULE OF INSTRUCTION
therefore: 6 | 9 = 15
Computer Programming 2 13
Week 3-4 Operator and Operator Precedence
<< (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
Assignment Operators
<variable> = <expression>;
int x = 1;
x=m+1
x = y = z = 1;
Computer Programming 2 15
Week 3-4 Operator and Operator Precedence
x = 1;
y = 1;
z = 1;
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
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:
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,
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.
/**
* 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
2. Class definition
public class HelloWorld
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
{
6. Output Statement
System.out.println("Hello World!");
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:
Computer Programming 2 3
Week 3-4 Programming Fundamentals
B. Java Comments
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
*/
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
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.
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)
E. Java Keywords
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
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.
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.
\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.
byte
short
10
MODULE OF INSTRUCTION
int
long
float
Computer Programming 2 11
Week 3-4 Programming Fundamentals
double
boolean
char
12
MODULE OF INSTRUCTION
For example:
String message = “Hello world!”;
String supplementaryCharacter = “\uD801\uDC00”;
H. Variables
Data type and name are both required and initial value for variable is optional.
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.
is also a variable declaration and it has a variable name of centimeter and int
data type and has no initial value.
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.
Computer Programming 2 15
MODULE OF INSTRUCTION
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:
Let’s start creating the “Hello World” program. The following are the
steps to create the program:
Computer Programming 2 1
Week 2 Getting to know the programming environment
2
MODULE OF INSTRUCTION
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
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
Computer Programming 2 7
Week 2 Getting to know the programming environment
8
MODULE OF INSTRUCTION
There are two ways to set Java path, one is temporary and other one is
permanent.
Computer Programming 2 9
Week 2 Getting to know the programming environment
10
MODULE OF INSTRUCTION
Computer Programming 2 11
Week 2 Getting to know the programming environment
12
MODULE OF INSTRUCTION
Computer Programming 2 13
Week 2 Getting to know the programming environment
B. Errors
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.
Computer Programming 2 15
Week 2 Getting to know the programming environment
Runtime Errors
16
MODULE OF INSTRUCTION
Logical Errors
Computer Programming 2 17
Week 2 Getting to know the programming environment
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.
Computer Programming 2 19
Week 2 Getting to know the programming environment
20
MODULE OF INSTRUCTION
Computer Programming 2 21
Week 2 Getting to know the programming environment
22
MODULE OF INSTRUCTION
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.
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.
24
MODULE OF INSTRUCTION
Press F6
Computer Programming 2 25
Week 2 Getting to know the programming environment
LESSON SUMMARY:
1. You can write java program using notepad and compile it using
windows command line.
3. There are three types of error in java these are Syntax errors, run
time errors and logical errors.
26
MODULE OF INSTRUCTION
Introduction to 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.
Computer Programming 2 1
Week 3-4 Administering Users and Roles
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.
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
Object Oriented
4
MODULE OF INSTRUCTION
Platform Independent
Code Security
Computer Programming 2 5
Week 3-4 Administering Users and Roles
Robust
Architecture-neutral
6
MODULE OF INSTRUCTION
Portable
Dynamic
High Performance
Computer Programming 2 7
Week 3-4 Administering Users and Roles
Multithreaded
Distributed
LESSON SUMMARY:
8
MODULE OF INSTRUCTION
Computer Programming 2 9