Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Comprog 4 - Programing Fundamentals

This document discusses the basic parts of a Java program and coding guidelines. It begins by dissecting a sample Java program line-by-line, explaining the purpose and structure of items like comments, the class definition, main method, output statements, and curly braces. It then covers Java comments in more detail, including single-line, multi-line, and documentation comments. Finally, it defines Java statements and blocks, noting that statements can span multiple lines but end in semicolons, and together make up the logic and functionality of a program.

Uploaded by

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

Comprog 4 - Programing Fundamentals

This document discusses the basic parts of a Java program and coding guidelines. It begins by dissecting a sample Java program line-by-line, explaining the purpose and structure of items like comments, the class definition, main method, output statements, and curly braces. It then covers Java comments in more detail, including single-line, multi-line, and documentation comments. Finally, it defines Java statements and blocks, noting that statements can span multiple lines but end in semicolons, and together make up the logic and functionality of a program.

Uploaded by

Mikey Ramos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

MODULE OF INSTRUCTION

Programming Fundamentals

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

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

- Recognize the parts of Java program.

- Apply Java comments in your program.

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


identifiers.

- Develop a simple program using the concepts mentioned


above.

A. Dissecting a Java program

Let us try to dissect your first Java program:

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

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

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

Computer Programming 2 1
Week 3-4 Programming Fundamentals

All programs should begin with a comment to define the


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

2. Class definition
public class HelloWorld

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


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

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


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

HelloWorld indicates the name of the class. The class name


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

The coding guidelines for naming class are:

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


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

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


to identify all the Java reserved words later.

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

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

2
MODULE OF INSTRUCTION

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

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

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

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


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

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

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


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

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


}}

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

Reminders:

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


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

Computer Programming 2 3
Week 3-4 Programming Fundamentals

B. Java Comments

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


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

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


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

1. Single line comments.


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

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

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

4
MODULE OF INSTRUCTION

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

C. Java Statements and blocks

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


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

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


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

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


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

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

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

Computer Programming 2 5
Week 3-4 Programming Fundamentals

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

D. Identifiers

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


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

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

The following are the examples of invalid identifiers:


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

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

6
MODULE OF INSTRUCTION

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

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


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

E. Java Keywords

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


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

abstract double Int super


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

Computer Programming 2 7
Week 3-4 Programming Fundamentals

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

F. Java Literals

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


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

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

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

8
MODULE OF INSTRUCTION

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

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


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

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

Character Literals

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

A character literal can be:


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

Escape Sequence Character Represented

\t Tab
\b Backspace
\n New line
\r Carriage return

Computer Programming 2 9
Week 3-4 Programming Fundamentals

\f Form Feed
\' Single quote character
\" Double quote character
\\ Backslash character

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

G. Primitive Data Type

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


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

byte

• byte data type is an 8-bit signed integer


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

short

• short data type is a 16-bit signed integer

10
MODULE OF INSTRUCTION

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

int

• int data type is a 32-bit signed integer


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

long

• long data type is a 64-bit signed integer


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

float

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


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

double

Computer Programming 2 11
Week 3-4 Programming Fundamentals

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


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

boolean

• boolean data type represents 1 bit of information.


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

char

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


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

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


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

12
MODULE OF INSTRUCTION

String supplementaryCharacter = “\uD801\uDC00”;

H. Variables

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


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

Declaring and Initializing Variable

To declare a variable you need to have the following:

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

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

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

The output of the program is:

The line 4 or this code

Computer Programming 2 13
Week 3-4 Programming Fundamentals

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

Line 5 or this code

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

Line 6 or this code

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


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

Line 7 and 8 or this code

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

Printing Variable

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

▪ System.out.println()
▪ System.out.print()

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

14
MODULE OF INSTRUCTION

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

The output of the example above is:

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

The output of the example above is:

Computer Programming 2 15

You might also like