0% found this document useful (0 votes)
14 views

Comprog1 W Module 3

University of Makati ComProg Module

Uploaded by

Marq Francis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Comprog1 W Module 3

University of Makati ComProg Module

Uploaded by

Marq Francis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

COMPUTER

PROGRAMMING

WEEK 3 - MODULE

PROF. ROEL C. TRABALLO

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
SECTION 4
INTRODUCTION TO JAVA PROGRAMMING
CHAPTER 2

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

Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called
Oak, in honor of the tree outside Gosling's window, its name was changed to Java because there
was already a language called Oak. The original motivation for Java was the need for platform
independent language that could be embedded in various consumer electronic products like
toasters and refrigerators. One of the first projects developed using Java was a personal hand-
held remote control named Star 7. At about the same time, the World Wide Web and the Internet
were gaining popularity. Gosling et. al. realized that Java could be used for Internet
programming.
The name Java was the developers’ name initials too.
JAVA - James Gosling,
Arthur Van Hoff,
Andy Bechtolsheim

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.

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
 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.

SOME FEATURES OF JAVA


 The Java Virtual Machine
The Java Virtual Machine is an imaginary machine that is implemented by
emulating software on a real machine. The JVM provides the hardware platform
specifications to which you compile all Java technology code. This specification enables
the Java software to be platform-independent because the compilation is done for a
generic machine known as the JVM.
A bytecode is a special machine language that can be understood by the Java
Virtual Machine (JVM). The bytecode is independent of any particular computer
hardware, so any computer with a Java interpreter can execute the compiled Java
program, no matter what type of computer the program was compiled on.
 Garbage Collection
Many programming languages allow a programmer to allocate memory during
runtime. However, after using that allocated memory, there should be a way to deallocate
that memory block in order for other programs to use it again. In C, C++ and other
languages the programmer is responsible for this. This can be difficult at times since
there can be instances wherein the programmers forget to deallocate memory and
therefore result to what we call memory leaks.
In Java, the programmer is freed from the burden of having to deallocate that
memory themselves by having what we call the garbage collection thread. The garbage
collection thread is responsible for freeing any memory that can be freed. This happens
automatically during the lifetime of the Java program.

 Code Security
Code security is attained in Java through the implementation of its Java Runtime
Environment (JRE). The JRE runs code compiled for a JVM and performs class loading
(through the class loader), code verification (through the bytecode verifier) and finally
code execution.

 The Class Loader is responsible for loading all classes needed for the Java program. It
adds security by separating the namespaces for the classes of the local file system from

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
those that are imported from network sources. This limits any Trojan horse applications
since local classes are always loaded first. After loading all the classes, the memory
layout of the executable is then determined. This adds protection against unauthorized
access to restricted areas of the code since the memory layout is determined during
runtime. After loading the class and lay outing of memory, the bytecode verifier then
tests the format of the code fragments and checks the code fragments for illegal code that
can violate access rights to objects. After all of these have been done, the code is then
finally executed.

PHASES OF A JAVA PROGRAM


The following figure describes the process of compiling and executing a Java program.

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


University of Makati – College of Computer Science
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


University of Makati – College of Computer Science
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


University of Makati – College of Computer Science
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


University of Makati – College of Computer Science
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”);

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
 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.
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


University of Makati – College of Computer Science
JAVA KEYWORDS
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot
use keywords as names for your variables, classes, methods …etc.

Here is a list of the Java Keywords.

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. We will cover more on data types later.

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

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
 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”.

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

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \.

For example,
'\'' //for single quotes
'\"' //for double quotes
Although, String is not a primitive data type (it is a Class), we will just introduce
String in this section. A String represents a data type that contains multiple characters. It
is not a primitive data type, it is a class. It has it’s literal enclosed in double quotes(“”).

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:

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
 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)
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.

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
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()

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
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 );
}
}

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!

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
 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.

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.


References:
 JEDI Course Notes



Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science
ASSESSMENT
NAME: _____________________________________________ Score: __________
Section: _________________ Date Submitted: _____________

K-W-L (KNOW, WANT TO KNOW, LEARNED)


K-W-L charts are graphic organizers that help students organize information before, during, and after a unit or a
lesson. They can be used to engage students in a new topic, activate prior knowledge, share unit objectives, and
monitor students’ learning.

1. Fill out column 1


Students shall respond to the first prompt in column 1: What do you know about the different learning
platforms? How and where did you know about those?
2. Fill out column 2
Students shall respond to the prompt in column 2: What do you want to know about this topic? Write down the
specific questions in which you are more interested.
3. Leave the last column blank: What did you learn? This must be filled out by the end of the week or after
discussion.

Compiled by: Prof. ROEL C. TRABALLO


University of Makati – College of Computer Science

You might also like