Introduction To Programming
Introduction To Programming
Introduction To Programming
COMPUTER PROGRAMMING 1
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.
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.
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
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.
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.
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.
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.
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
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.
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.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
Output:
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:
Hello Java
Output:
Hello Java
Compilation Flow:
o When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.
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:
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.
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
ERRORS
What we've shown so far is a Java program wherein we didn't encounter any problems in
compiling and running.
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.
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 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.
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.
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.
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”.
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,
For example,
String message=“Hello world!”
Integral types have int as default data type. You can define its long value by
appending the letter l or L.
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.
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.
- It is called an instance variable because its value is instance-specific and is not shared
among instances.
• 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.
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.
multiplicative */%
Arithmetic
additive +-
bitwise inclusive OR |
Ternary ternary ?:
o Output:
10
12
12
10
o Output:
22
21
o Output:
-11
9
false
true
Arithmetic operators
Here are the basic arithmetic operators that can be used in creating your Java programs,
o Output:
15
5
50
2
0
o Output:
21
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.
o Output:
2
5
2
o Output:
5
5
-5
1073741819
o Output:
false
false
o Output:
false
10
false
11
o Output:
true
true
true
10
true
11
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
o Output:
14
16
o Output:
13
9
18
9
o Output:
Compile time error
o Output:
20
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
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;
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.
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 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,
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);
}
}
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);
}
}
Here's a sample source code that uses the logical NOT operator,
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