You are on page 1of 48

UNIVERSITY OF MAKATI

COMPUTER PROGRAMMING 1

INTRODUCTION TO JAVA PROGRAMMING


Learning Outcomes:
In this section, we will be discussing a little bit of Java history and what is Java
Technology. We will also discuss the phases that a Java program undergoes. At the end of the
lesson, the student should be able to:
• Describe the features of Java technology such as the Java virtual machine, garbage
collection and code security
• Describe the different phases of a Java program

JAVA BACKGROUND: HISTORY

 The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time. The
history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology
was incorporated by Netscape.
 The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming,
mobile devices, games, e-business solutions, etc. Following are given significant points that
describe the history of Java.
 Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995.
 James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team changed the name from Oak to
Java.
 Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
 Platform: Any hardware or software environment in which a program runs, is known
as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.
 Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. Following are given significant points that describe the history of Java.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
 Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project.
 Why Java was named as "Oak"?
 Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
 Why Java Programming named "Java"?
 Why had they chose the name Java for Java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt",
"DNA", etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.
 According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.
 Java is an island in Indonesia where the first coffee was produced (called Java
coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while
having a cup of coffee nearby his office.
 Notice that Java is just a name, not an acronym.
 Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
 In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

FEATURES OF JAVA

 The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.
 A list of the most important features of the Java language is given below.
 Simple: Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple programming
language because:
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
 Object-oriented: Java is an object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our software as a combination
of different types of objects that incorporate both data and behaviour.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules. Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

 Platform Independent: Java is platform independent because it is different from


other languages like C, C++, etc. which are compiled into platform specific machines
while Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
 Runtime Environment
 API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

 Secured: Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

 Classloader: Classloader in Java is a part of the Java Runtime Environment


(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
 Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.

 Robust: The English mining of Robust is strong. Java is robust because:


 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
 There are exception handling and the type checking mechanism in Java. All
these points make Java robust.

 Architecture-neutral: Java is architecture neutral because there are no


implementation dependent features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

 Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

 High-performance: Java is faster than other traditional interpreted programming


languages because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.

 Distributed: Java is distributed because it facilitates users to create distributed

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
applications in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any machine
on the internet.

 Multi-threaded: A thread is like a separate program, executing concurrently. We can


write Java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

 Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It


means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage


collection).

WHAT IS JAVA TECHNOLOGY?

 A programming language – Java can create all kinds of applications that you could
create using any conventional programming language.
 A development environment – Java technology provides you with a large suite of tools:
a compiler, an interpreter, a documentation generator, a class file packaging tool, and so
on.
 An application environment – Java technology applications are typically general-
purpose programs that run on any machine where the Java runtime environment (JRE)
is installed.
 A deployment environment
There are two main deployment environments: First, the JRE supplied by the
Java 2 Software Development Kit (SDK) contains the complete set of class files for all
the Java technology packages, which includes basic language classes, GUI component
classes, and so on. The other main deployment environment is on your web browser.
Most commercial browsers supply a Java technology interpreter and runtime
environment.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

C++ VS JAVA
There are many differences and similarities between the C++ programming language and Java. A
list of top differences between C++ and Java are given below:

Comparison
C++ Java
Index

Platform-
C++ is platform-dependent. Java is platform-independent.
independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.

Design Goal C++ was designed for systems and Java was designed and created as an
applications programming. It was an interpreter for printing systems but
extension of the C programming later extended as a support network
language. computing. It was designed to be easy
to use and accessible to a broader
audience.

Goto C++ supports the goto statement. Java doesn't support the goto
statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple


inheritance inheritance through class. It can be
achieved by using interfaces in java.

Operator C++ supports operator overloading. Java doesn't support operator


Overloading overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the pointer
program in java. It means java has
restricted pointer support in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the compiler interpreter. Java source code is
which converts source code into converted into bytecode at
machine code so, C++ is platform compilation time. The interpreter
dependent. executes this bytecode at runtime and

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

produces output. Java is interpreted


that is why it is platform-independent.

Call by Value C++ supports both call by value and Java supports call by value only.
and Call by call by reference. There is no call by reference in java.
reference

Structure and C++ supports structures and unions. Java doesn't support structures and
Union unions.

Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party
libraries for thread support.

Documentation C++ doesn't support documentation Java supports documentation


comment comments. comment (/** ... */) to create
documentation for java source code.

Virtual C++ supports virtual keyword so Java has no virtual keyword. We can
Keyword that we can decide whether or not to override all non-static methods by
override a function. default. In other words, non-static
methods are virtual by default.

unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift
shift >>> >>> operator that fills zero at the top
for the negative numbers. For positive
numbers, it works same like >>
operator.

Inheritance Tree C++ always creates a new Java always uses a single inheritance
inheritance tree. tree because all classes are the child
of the Object class in Java. The
Object class is the root of
the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented language. Java is also an object-


However, in the C language, a single oriented language. However,
root hierarchy is not possible. everything (except fundamental
types) is an object in Java. It is a
single root hierarchy as everything
gets derived from java.lang.Object.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Note
 Java doesn't support default arguments like C++.
 Java does not support header files like C++. Java uses the import keyword to include
different classes and methods.

 C++ Program Example


Filename: main.cpp

1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }

Output:

Hello C++ Programming

 Java Program Example


Filename: Simple.java

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

Output:

Hello Java

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 For executing any Java program, the following software or application must be properly
installed.
 Install the JDK if you don't have installed it, download the JDK and install it.
 Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
 Create the Java program
 Compile and run the Java program

 Creating Hello Java Example


1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

 Save the above file as Simple.java.


o To compile: javac Simple.java
o To execute: java Simple

Output:

Hello Java

 Compilation Flow:
o When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.

 Parameters used in First Java Program


o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to
all.
o static is a keyword. If we declare any method as static, it is known as the static

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it
in coming section.
o System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will
discuss the internal working of System.out.println() statement in the coming section.

 To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shown below:

 As displayed in the above diagram, write the simple program of Java in notepad and saved it
as Simple.java. In order to compile and run the above program, you need to open the
command prompt by start menu -> All Programs -> Accessories -> command prompt.
When we have done with all the steps properly, it shows the following output:

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 What happens at runtime?
 At runtime, the following steps are performed:

 Class Loader: It is the subsystem of JVM that


is used to load class files.
 Bytecode Verifier: Checks the code
fragments for illegal code that can violate
access rights to objects.
 Interpreter: Read bytecode stream then
execute the instructions.

PHASES OF A JAVA PROGRAM

 The following figure describes the process of compiling and executing a Java program.
o The first step in creating a Java program is by writing your programs in a text editor.
Examples of text editors you can use are notepad, vi, emacs, etc. This file is stored in a
disk file with the extension .java.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
o After creating and saving your Java program, compile the program by using the Java
Compiler. The output of this process is a file of Java bytecodes with the file extension
.class.
o The .class file is then interpreted by the Java interpreter that converts the bytecodes into
the machine language of the particular computer you are using.

HOW JAVA WORKS

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

GETTING TO KNOW YOUR PROGRAMMING


ENVIRONMENT

Objectives:
In this section, we will be discussing on how to write, compile and run Java programs.
There are two ways of doing this; the first one is by using a console and a text editor. The second
one is by using NetBeans/JCreator/Eclipse which is an Integrated Development Environment
or IDE.
At the end of the lesson, the student should be able to:
• Create a Java program using any text editor
• Differentiate between syntax-errors and runtime errors
• Create a Java program using NetBeans/JCreator/Eclipse

INTEGRATED DEVELOPMENT ENVIRONMENT


 An IDE is a programming environment integrated into a software application that provides a
GUI builder, a text or code editor, a compiler and/or interpreter and a debugger.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Example: My First Java Program

public class Hello {


/**
* My first java program
*/
public static void main(String[] args) {
//prints the string "Hello world" on screen
System.out.println("Hello world!");
}
}

ERRORS
What we've shown so far is a Java program wherein we didn't encounter any problems in
compiling and running.

Two Types of Errors


 Syntax Errors
Syntax errors are usually typing errors. You may have misspelled a command in
Java or forgot to write a semi-colon at the end of a statement. Java attempts to isolate the
error by displaying the line of code and pointing to the first incorrect character in that
line. However, the problem may not be at the exact point.
Other common mistakes are in capitalization, spelling, the use of incorrect special
characters, and omission of correct punctuation.
 Run-time Errors
Run-time errors are errors that will not display until you run or execute your
program. Even programs that compile successfully may display wrong answers if the
programmer has not thought through the logical processes and structures of the program.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

PROGRAMMING FUNDAMENTALS

Objectives
In this section, we will be discussing the basic parts of a Java program. We will start by
trying to explain the basic parts of the Hello.java program introduced in the previous section. We
will also be discussing some coding guidelines or code conventions along the way to help in
effectively writing readable programs.

At the end of the lesson, the student should be able to:


• Identify the basic parts of a Java program
• Differentiate among Java literals, primitive data types, variable types, identifiers and
operators
• Develop a simple valid Java program using the concepts learned in this chapter

Dissecting my first Java program


Now, we'll try to dissect your first Java program:
public class Hello {
/**
* My first java program
*/
public static void main(String[] args) {
//prints the string "Hello world" on screen
System.out.println("Hello world!");
}
}

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
JAVA COMMENTS
Comments are notes written to a code for documentation purposes. Those text are not
part of the program and does not affect the flow of the program. Java supports three types of
comments:

 C++-Style Comments
C++ Style comments starts with //. All the text after // are treated as comments.

For example,
// This is a C++ style or single line comments
 C-Style Comments
C-style comments or also called multiline comments starts with a /* and ends with
a */. All text in between the two delimeters are treated as comments. Unlike C++ style
comments, it can span multiple lines.

For example,
/* this is an exmaple of a
C style or multiline comments */
 Special Javadoc Comments
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.

For example,
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/

JAVA STATEMENTS AND BLOCKS


 A statement is one or more lines of code terminated by a semicolon.

An example of a single statement is,


System.out.println(“Hello world”);
 A block is one or more statements bounded by an opening and closing curly braces that
groups the statements as one unit. Block statements can be nested indefinitely. Any
amount of white space is allowed.
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
An example of a block is,

public static void main( String[] args ) {


System.out.println("Hello");
System.out.println("world");
}

JAVA IDENTIFIERS
 Identifiers are tokens that represent names of variables, methods, classes, etc.
Examples: Hello, main, System, out.
 Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as
hello. Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”.
Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9.
 Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more
about Java keywords later.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
JAVA KEYWORDS
 Java keywords are also known as reserved words. Keywords are particular words that act as a
key to a code. These are predefined words by Java so they cannot be used as a variable or
object name or class name.
 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.

A list of Java keywords or reserved words are given below:


1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide
the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True
and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be
used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with
a variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of iteration is
fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current
source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using
JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes
the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

32. protected: Java protected keyword is an access modifier. It can be accessible within the package
and outside the package but through inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The
static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It
can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in
multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is
mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try
block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iteration is not fixed, it is recommended to use the while loop.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
JAVA LITERALS
Literals are tokens that do not change or are constant. The different types of literals in
Java are:

 Integer Literals
Integer literals come in different formats: decimal (base 10), hexadecimal (base
6), and octal (base 8). In using integer literals in our program, we have to follow some
special notations. For decimal numbers, we have no special notations. We just write a
decimal number as it is. For hexadecimal numbers, it should be preceded by “0x” or
“0X”. For octals, they are preceded by “0”. For example, consider the number 12. It's
decimal representation is 12, while in hexadecimal, it is 0xC, and in octal, it is equivalent
to 014. Integer literals default to the data type int. An int is a signed 32-bit value. In some
cases, you may wish to force integer literal to the data type long by appending the “l” or
“L” character. A long is a signed 64-bit value.

 Floating-Point Literals
Floating point literals represent decimals with fractional parts. An example is
3.1415. Floating point literals can be expressed in standard or scientific notations. For
example, 583.45 is in standard notation, while 5.8345e2 is in scientific notation. Floating
point literals default to the data type double which is a 64-bit value. To use a smaller
precision (32-bit) float, just append the “f” or “F” character.
 Boolean Literals
Boolean literals have only two values, true or false.

 Character Literals
Character Literals represent single Unicode characters. A Unicode character is a
16-bit character set that replaces the 8-bit ASCII character set. Unicode allows the
inclusion of symbols and special characters from other languages.
To use a character literal, enclose the character in single quote delimiters.
For example,
the letter a, is represented as ‘a’.
To use special characters such as a newline character, a backslash is used
followed by the character code. For example, ‘\n’ for the newline character, ‘\r’ for the
carriage return, ‘\b’ for backspace.

 String Literals
String literals represent multiple characters and are enclosed by double quotes.
An example of a string literal is, “Hello World”.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
JAVA DATA TYPES
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays

PRIMITIVE DATA TYPES


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
A boolean data type represents two states: true and false.

An example is,
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(’ ’).

For example,
‘a’ //The letter a
‘\t’ //A tab
To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \.

For example,

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
'\'' //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(“”).

For example,
String message=“Hello world!”

 Integral – byte, short, int & long


Integral data types in Java uses three forms – decimal, octal or hexadecimal.
Examples are,
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.

Integral data types have the following ranges:

 Floating Point – float and double


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)
Examples are,
3.14 //A simple floating-point value (a double)

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
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.

Floating-point data types have the following ranges:

VARIABLES
A variable is an item of data used to store state of objects. A variable has a data type
and a name. The data type indicates the type of value that the variable can hold. The variable
name must follow rules for identifiers.

 Declaring and Initializing Variables


To declare a variable is as follows,
<data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while those values enclosed in []
are optional.

 Types of Variables
1. Local Variable - A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.

- A local variable cannot be defined with "static" keyword.


2) Instance Variable - A variable declared inside the class but outside the body of the method,
is called an instance variable. It is not declared as static.

- It is called an instance variable because its value is instance-specific and is not shared
among instances.

3) Static variable - A variable that is declared as static is called a static variable. It


cannot be local. You can create a single copy of the static variable and share it among all
the instances of the class. Memory allocation for static variables happens only once when
the class is loaded in the memory.

Example to understand the types of variables in java


1. public class A
2. {

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Here is a sample program that declares and initializes some variables,
public class VariableSamples {
public static void main( String[] args ){
//declare a data type with variable name
// result and boolean data type
boolean result;
//declare a data type with variable name
// option and char data type
char option;
option = 'C'; //assign 'C' to option
//declare a data type with variable name
//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}

 Outputting Variable Data


In order to output the value of a certain variable, we can use the following
commands,
System.out.println()
System.out.print()

Here's a sample program,


public class OutputVariable {
public static void main( String[] args ){
int value = 10;
char x;
x = ‘A’;
System.out.println( value );
System.out.println( “The value of x=“ + x );
}
}
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
The program will output the following text on screen,
10
The value of x=A

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


What is the difference between the commands System.out.println() and
System.out.print()? The first one appends a newline at the end of the data to output, while
the latter doesn't.

Consider the statements,


System.out.print("Hello ");
System.out.print("world!");

These statements will output the following on the screen,


Hello world!

Now consider the following statements,


System.out.println("Hello ");
System.out.println("world!");

These statements will output the following on the screen,


Hello world!

Reference Variables vs. Primitive Variables

• 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.

For example, suppose we have two variables with data type’s int and String.
int num = 10;
String name = "Hello"

Suppose, the illustration shown below is the actual memory of your computer,
wherein you have the address of the memory cells, the variable name and the data they
hold.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

As you can see, for the primitive variable num, the data is on the actual location
of where the variable is. For the reference variable name, the variable just holds the
address of where the actual data is.

JAVA OPERATORS

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.

 Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
 Unary Operator,  Bitwise Operator,
 Arithmetic Operator,  Logical Operator,
 Shift Operator,  Ternary Operator and
 Relational Operator,  Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence

postfix expr++ expr--


Unary
prefix ++expr --expr +expr -expr ~ !

multiplicative */%
Arithmetic
additive +-

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

Shift shift << >> >>>

comparison < > <= >= instanceof


Relational
equality == !=

bitwise AND &

Bitwise bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&


Logical
logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


 The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a Boolean

o Java Unary Operator Example: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

o Output:
10
12
12
10

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
o Java Unary Operator Example 2: ++ and --
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

o Output:
22
21

o Java Unary Operator Example: ~ and !


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}

o Output:
-11
9
false
true

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

Arithmetic operators
 Here are the basic arithmetic operators that can be used in creating your Java programs,

o Java Arithmetic Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}

o Output:
15
5
50
2
0

o Java Arithmetic Operator Example: Expression


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}

o Output:
21

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Here's a sample program in the usage of these operators:
public class ArithmeticDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
double x = 27.475;
double y = 7.22;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" x = " + x);
System.out.println(" y = " + y);
//adding numbers
System.out.println("Adding...");
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));
//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));
//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));
//computing the remainder resulting from dividing numbers
System.out.println("Computing the remainder...");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Here is the output of the program,
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i/j=0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58

Note: When an integer and a floating-point number are used as operands to a single
arithmetic operation, the result is a floating point. The integer is implicitly converted to a
floating-point number before the operation takes place.

Java Left Shift Operator


 The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
o Java Left Shift Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
o Output:
40
80
80
240

Java Right Shift Operator


 The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
o Java Right Shift Operator Example
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

o Output:
2
5
2

o Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

o Output:
5
5
-5
1073741819

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

Java AND Operator Example: Logical && and Bitwise &


 The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
o The bitwise & operator always checks both conditions whether first condition is
true or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

o Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}

o Output:
false
10
false
11

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

Java OR Operator Example: Logical || and Bitwise |


 The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
o The bitwise | operator always checks both conditions whether first condition is
true or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}

o Output:
true
true
true
10
true
11

Java Ternary Operator


 Java Ternary operator is used as one line replacement for if-then-else statement and used a
lot in Java programming. It is the only conditional operator which takes three operands.
o Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

o Output:
2

o Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

o Output:
5

Java Assignment Operator


 Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
o Java Assignment Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

o Output:
14
16

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
o Java Assignment Operator Example
1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}

o Output:
13
9
18
9

o Java Assignment Operator Example: Adding short


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

o Output:
Compile time error

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
o After type cast:
1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

o Output:
20

Increment and Decrement operators


 Aside from the basic arithmetic operators, Java also includes a unary increment operator
(++) and unary decrement operator (--). Increment and decrement operators increase and
decrease a value stored in a number variable by 1.

For example, the expression,


count = count + 1; //increment the value of count by 1
is equivalent to,
count++;

 The increment and decrement operators can be placed before or after an operand. When
used before an operand, it causes the variable to be incremented or decremented by 1, and
then the new value is used in the expression in which it appears.

For example,
int i = 10,
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1

 When the increment and decrement operators are placed after the operand, the old value
of the variable will be used in the expression where it appears.

For example,
int i = 10,
int j = 3;
int k = 0;

k = j++ + i; //will result to k = 3+10 = 13

Relational operators
 Relational operators compare two values and determines the relationship between those
values. The output of evaluation are the boolean values true or false.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Here's a sample program that uses relational operators,
public class RelationalDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
int k = 42;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);
//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false
//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true
//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true
//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Here's the output from this program:
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = true
k > j = false
Greater than or equal to...
i >= j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Less than or equal to...
i <= j = true
j <= i = false
k <= j = true
Equal to...
i == j = false
k == j = true
Not equal to...
i != j = true
k != j = false

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).

The basic expression for a logical operation is,


x1 op x2

where x1, x2 can be boolean expressions, variables or constants, and op is either


&&, &, ||, | or ^ operator. The truth tables that will be shown next, summarize the result
of each operation for all possible combinations of x1 and x2.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 && (logical AND) and & (boolean logical AND)
Here is the truth table for && and &,

The basic difference between && and & operators is that && supports short-
circuit evaluations (or partial evaluations), while & doesn't. What does this mean?

Given an expression,
exp1 && exp2
&& will evaluate the expression exp1, and immediately return a false
value is exp1 is false. If exp1 is false, the operator never evaluates exp2 because
the result of the operator will be false regardless of the value of exp2. In contrast,
the & operator always evaluates both exp1 and exp2 before returning an answer.

Here's a sample source code that uses logical and boolean AND,

public class TestAND {


public static void main( String[] args ) {
int i = 0;
int j = 10;
boolean test= false;
//demonstrate &&
test = (i > 10) && (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
//demonstrate &
test = (i > 10) & (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
The output of the program is,
0
10
false
0
11
false

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Note, that the j++ on the line containing the && operator is not evaluated since
the first expression (i>10) is already equal to false.

 || (logical OR) and | (boolean logical inclusive OR)


Here is the truth table for || and |,

The basic difference between || and | operators is that || supports short-circuit


evaluations (or partial evaluations), while | doesn't. What does this mean?

Given an expression,
exp1 || exp2
|| will evaluate the expression exp1, and immediately return a true value is exp1 is
true. If exp1 is true, the operator never evaluates exp2 because the result of the operator
will be true regardless of the value of exp2. In contrast, the | operator always evaluates
both exp1 and exp2 before returning an answer.

Here's a sample source code that uses logical and boolean OR,
public class TestOR {
public static void main( String[] args ) {
int i = 0;
int j = 10;
boolean test= false;
//demonstrate ||
test = (i < 10) || (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
//demonstrate |
test = (i < 10) | (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}

The output of the program is,


0
10
true
0
11
True
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
Note, that the j++ on the line containing the || operator is not evaluated since the
first expression (i<10) is already equal to true.

 ^ (boolean logical exclusive OR)


Here is the truth table for ^,

The result of an exclusive OR operation is TRUE, if and only if one operand is


true and the other is false. Note that both operands must always be evaluated in order to
calculate the result of an exclusive OR.

Here's a sample source code that uses the logical exclusive OR operator,
public class TestXOR {
public static void main( String[] args ) {
boolean val1 = true;
boolean val2 = true;
System.out.println(val1 ^ val2);
val1 = false;
val2 = true;
System.out.println(val1 ^ val2);
val1 = false;
val2 = false;
System.out.println(val1 ^ val2);
val1 = true;
val2 = false;
System.out.println(val1 ^ val2);
}
}

The output of the program is,


false
true
false
true

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 ! (logical NOT)
The logical NOT takes in one argument, wherein that argument can be an
expression, variable or constant.
Here is the truth table for !,

Here's a sample source code that uses the logical NOT operator,

public class TestNOT {


public static void main( String[] args ) {
boolean val1 = true;
boolean val2 = false;
System.out.println(!val1);
System.out.println(!val2);
}
}

The output of the program is,


false
true

 Conditional Operator (?:)


The conditional operator ?: is a ternary operator. This means that it takes in three
arguments that together form a conditional expression.
The structure of an expression using a conditional operator is,
exp1?exp2:exp3
wherein exp1 is a boolean expression whose result must either be true or false. If
exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.

Compiled by: Prof. ROEL C. TRABALLO


Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
For example, given the code,
public class ConditionalOperator {
public static void main( String[] args ) {
String status = "";
int grade = 80;
//get status of the student
status = (grade >= 60) ? "Passed" : "Fail";
//print status
System.out.println( status );
}
}

The output of this program will be,


Passed

Here is the flowchart of how ?: works,

Here is another program that uses the ?: operator,


class ConditionalOperator {
public static void main( String[] args ) {
int score = 0;
char answer = 'a';
score = (answer == 'a') ? 10 : 0;
System.out.println("Score = " + score );
}
}

The output of the program is,


Score = 10
Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences
UNIVERSITY OF MAKATI
COMPUTER PROGRAMMING 1
 Operator Precedence
Operator precedence defines the compiler’s order of evaluation of operators so as
to come up with an unambiguous result.

Given a complicated expression,


6%2*5+4/2+88-10

we can re-write the expression and place some parenthesis base on operator
precedence,
((6%2)*5)+(4/2)+88-10;


Reference:
 JEDI Course Notes
Additional Readings:
 https://www.w3schools.com/java/default.asp
 https://www.tutorialspoint.com/java/index.htm
 https://www.javatpoint.com/java-tutorial


Compiled by: Prof. ROEL C. TRABALLO
Faculty, College of Computing and Information Sciences

You might also like