0% found this document useful (0 votes)
16 views11 pages

Chapter 2 Fundamentals of Java Programming AutoRecovered

Chapter II of the document covers the fundamentals of Java programming, including essential components like the Java API, identifiers, keywords, separators, literals, comments, data types, variables, and operators. It emphasizes the importance of syntax correctness, coding guidelines, and the distinction between primitive and reference data types. The chapter also outlines variable declaration, initialization, and the use of operators in Java programming.

Uploaded by

elysaludes9157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views11 pages

Chapter 2 Fundamentals of Java Programming AutoRecovered

Chapter II of the document covers the fundamentals of Java programming, including essential components like the Java API, identifiers, keywords, separators, literals, comments, data types, variables, and operators. It emphasizes the importance of syntax correctness, coding guidelines, and the distinction between primitive and reference data types. The chapter also outlines variable declaration, initialization, and the use of operators in Java programming.

Uploaded by

elysaludes9157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

ITECC-2 – Fundamentals of Programming

CHAPTER II. JAVA PROGRAMMING FUNDAMENTALS


An understanding of the most fundamental parts, which are considered the
building blocks of Java us essential to successful Java programming. However, if you
fail to enter syntactically correct codes into your program, the compiler will report a
syntax error message when it tries to compile your program. However, the error that
is reported may not always be the actual source of the problem. Some error messages
are misleading. Thus, you need to take extra effort and patience to find the real
problem.

I. THE BUILDING BLOCKS OF JAVA

 JAVA APPLICATION PROGRAMMING INTERFACE (API)


ο contains hundreds of predefined classes and methods that can use in Java
programs
ο these classes and methods are organized into what we call packages
o packages
▪ it contain classes that have related purpose
▪ e.g. java.io, java.util, java.lang, java.awt, javax.swing
o packages declaration
▪ syntax:

<import> <name_of_packacge><dot><asterisk><semicolon>

▪ e.g. java.io.*; java.util.*; javax.swing.*;

 IDENTIFIERS
ο are tokens that represent names of variables, methods, classes, etc.
▪ examples of identifiers are: Hello, main, System, out
ο these are case-sensitive
▪ this means that the identifier: Hello is not the same as hello.
ο 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
ο Java keywords should NOT be used as identifiers

Coding Guidelines:
1. For names of classes, capitalize the first letter of the class name. For
names of methods and variables, the first letter of the word should start
with a small letter. For example:
ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName
2. In case of multi-word identifiers, use capital letters to indicate the start of
the word except the first word. For example, charArray, fileNumber,
ClassName.
3. Avoid using underscores at the start of the identifier such as _read or
_write

 KEYWORDS
ο these are predefined identifiers reserved by Java for a specific purpose
and they are always spelled in lowercase letters
ο these are reserved words that has its own special meaning in the Java
programming language, and that meaning doesn’t change from one
program to another
ο it cannot be use as names for your variables, classes, methods …etc.

Prepared by: Dr. Michael John R. Robles Page 1 of 11


ITECC-2 – Fundamentals of Programming

 SEPARATORS
ο it refer to punctuation characters and paired-delimiters that divide the
source code into fragments in order to define the structure of a Java
program

Table 1.0. Java Separators


Separator Meaning/Purpose
pair of used to enclose arguments in method
parenthesis (()) definitions and calling and alter precedence
in arithmetic expressions
pair of braces used to define blocks of code
({})
period (.) used to select a method from an object;
separate package names from sub-package
and class names
comma (,) used to separate consecutive identifiers n
variable declarations and expressions in a for
loop
colon (:) used after loop labels
Semicolon (;) this is used to terminate statements

 JAVA LITERALS
ο these are tokens that do not change or are constant
• Integer Literals
o come in different formats: decimal (base 10), hexadecimal
(base 16), and octal (base 8).
o For decimal numbers, we have no special notations. We just
write a decimal number as it is.
o For hexadecimal numbers, it should be preceded by “0x” or
“0X”.
o For octals, they are preceeded by “0”

Decimal Hexadecimal Octal

12 = 0xC = 014
• Floating-Point Literals
o represent decimals with fractional parts
▪ an example is 3.1415
o can be expressed in standard or scientific notations
▪ for example
• 583.45 is in standard notation
• while 5.8345e2 is in scientific notation
• Boolean Literals
o have only two values, true or false
• Character Literals
o represent single Unicode characters

Prepared by: Dr. Michael John R. Robles Page 2 of 11


ITECC-2 – Fundamentals of Programming

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
o to use a character literal, enclose the character in single quote
delimiters (‘ ‘)
▪ for example, the letter a, is represented as ‘a’
• String Literals
o represent multiple characters and are enclosed by double
quotes (“ “)
▪ an example of a string literal is, “Hello World”

Java Escape Sequences


ο sometimes referred to as backslash character constants
ο used in place of the characters that they represent

Table 1.1. Java Escape Sequences


Escape Sequence Meaning
\b Backspace
\t Horizontal tab
\n Line feed or create a new line
\f Form feed
\r Carriage return
\” Insert double quote (“)
\’ Insert single quote (‘)
\\ Insert backslash (\)
\ddd Octal constant (where ddd is an octal
constant)
\uxxxx Hexadecimal constant (where xxxx is a
hexadecimal constant)

 JAVA COMMENTS
ο is a special section of text inside a program whose purpose is to help people
understand the program
ο it is not part of the program itself, but used for documentation purposes
and does not affect the flow of the program
ο is indicated by the delimiters

3 Different Kinds of comments in Java:

• End-of-line comments/Single Line Comment: An end-of-line


comment starts with two slashes (//), and goes to the end of a line of
type. Once again, no text inside the end-of-line comment gets
translated by the compiler.

// This is an example of a single line comments

• Traditional comments/Multi-line Comment: The traditional


comment begins with /* and ends with */. Everything between the
opening /* and the closing */ is for human eyes only.

/*
* This is an example of a
* multiline comments
*/

Prepared by: Dr. Michael John R. Robles Page 3 of 11


ITECC-2 – Fundamentals of Programming

• Javadoc comments: These are used for generating an HTML


documentation for your Java/programs. It begins with a slash and two
asterisks (/**).

/**
This is an example of special Javadoc comment.
@author: Vilchor G. Perdido
@date: June 12, 2011
@version 1.0
*/

 ABSTRACT DATA TYPES OR DATA TYPES


ο is a keyword of a programming language that specifies the amount of
memory needed to store data and it specifies what the kind of data that
will be stored in that memory location
ο divided into two categories
o primitive data type
▪ is defined by the programming language, sometimes call these as
built-in data types such as the int, char, float, double, short, byte
and boolean data types
o user-defined or reference data type,
▪ it is a group of primitive data types defined by the programmer

Primitive Data Types


o built into the system and are not actual objects, which makes them
more efficient to use
o types are machine-independent, which means that you can rely on
their sizes and characteristics to be consistent across Java programs
o There are four data type groups:
• Integer (integral)
▪ stores whole numbers and signed numbers
• Floating-point
▪ stores real numbers (fractional values)
• Character (textual)
▪ stores a single character or escape sequence and ideal for
storing names of things
• Boolean (logical)
▪ stores a true or false value
o the Java programming language defines eight primitive data types:
boolean (for logical), char (for textual), byte, short, int, long
(integral), double and float (floating point)

Table 1.2: Simple Java Data Types.


Data Data Type Range of Values Group
Type Size/Length
byte 8 bits –128 to 127 Integers
(Integral)
short 16 bits –32,768 to 32,767 Integers
(Integral)
int 32 bits –2,147,483,648 to Integers
2,147,483,647 (Integral)
long 64 bits –9,223,372,036,854,775,808 Integers
to (Integral)
9,223,372,036,854,775,807
float 32 bits 3.4e-038 to 3.4e+038 Floating-point
double 64 bits 1.7e-308 to 1.7e+308 Floating-point
char 16 bits 65,536 (Unicode) Characters
(Unicode) (textual)
boolean 1 bit 0 or 1 Boolean (Logical)

Prepared by: Dr. Michael John R. Robles Page 4 of 11


ITECC-2 – Fundamentals of Programming

User-Defined or Reference Data Type


o are used as references to an object such as arrays and user-defined
data types (classes)
o String is considered a reference data type

 VARIABLES
ο it is sometimes called as a placeholder which is an item of data used to
store state of objects
ο is a named memory location that can be assigned a value
o the value of a variable can be changed during the execution of a
program meaning the content of a variable is changeable, not fixed
ο three kinds of variables in Java
▪ Instance variables
o are used to define attributes or the state for a particular object
o e.g. Button myButton = new Button();
myButton.setEnabled(true);
▪ Class variables
o are similar to instance variables, except their values apply to all
that class's instances (and to the class itself) rather than having
different values for each object
o e.g. StudentRecord student = new StudentRecord()
▪ Local variables
o are declared and used inside method definitions, for example,
for index counters in loops, as temporary variables, or to hold
values that you need only inside the method definition itself
o e.g. double radius = 3.25;

ο all variables have:


o Data Type
▪ indicates what kind of data that the variable can contain or
hold
▪ it also identify how many bits of memory to be reserved for
the data
o Name
▪ a unique reference name or identifier that refers to the
variable
o Value
▪ the default or specified value
▪ also called the literal of the statement
o Semicolon
▪ Remember: All java statements end with a semicolon!

Rules in Naming Variables in Java


✓ Variable names in Java can start with a letter, an
underscore (_), or a dollar sign ($).
✓ They cannot start with a number.
✓ After the first character, your variable names can include
any letter or number.
✓ Symbols, such as %, *, @, and so on, are often reserved
for operators in Java, so be careful when using symbols in
variable names.
✓ In addition, the Java language uses the Unicode character
set. Unicode is a character set definition that not only
offers characters in the standard ASCII character set, but
also several million other characters for representing
most international alphabets.
NOTE: By Java convention, the first word is lowercase, but
all following words have an initial uppercase letter.

Prepared by: Dr. Michael John R. Robles Page 5 of 11


ITECC-2 – Fundamentals of Programming

Declaring and Initializing Variables


ο to use any variable in a Java program, it must first declared
ο to declare a variable, the syntax is as follows:

<data_type> <variable_name> [= initial_value];

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

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()
ο Example:
System.out.println(“The random number is ” +
randomNumber);
System.out.print(“The ” + username + “ and ” +
password + “ do not matched.”);

Reference Variables vs. Primitive Variables


ο The types of variables that Java programs have:
o Primitive variables (variables)
▪ are variables used to store the actual data (only one at a
time) with primitive data types in the computer’s memory
▪ they store data in the actual memory location of where
the variable is
▪ they are not capitalized in variable declarations

int aNumber = 5;
char letter = ‘A’;

o Reference variables (references)


▪ are variables that stores 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
▪ they are capitalized

String myString = “Hello World”;


Employee emp1 = new Employee();

Prepared by: Dr. Michael John R. Robles Page 6 of 11


ITECC-2 – Fundamentals of Programming

For example, suppose we have two variables with data types 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.

Variable CONSTANTS in Java


ο a variable with a value that doesn’t change
ο it used the keyword “final”
▪ it denotes value cannot change
ο declaration syntax:

<final_keyword> <data_type> <VARIABLE_NAME> [= final_value];

ο examples:
final double PI = 3.1416;
final double SALES_TAX_RATE = 4.5;
final int PASSING_GRADE = 75;

 JAVA OPERATORS
Java provides a rich set of operators to manipulate variables. 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.

a. Arithmetic Operators
– are used in mathematical expressions in the same way that they are used
in algebra

Prepared by: Dr. Michael John R. Robles Page 7 of 11


ITECC-2 – Fundamentals of Programming

a.1. 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

• 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

b. Relational Operators
– compare two values and determines the relationship between those
values
– the output of evaluation are the Boolean values true or false

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

Prepared by: Dr. Michael John R. Robles Page 8 of 11


ITECC-2 – Fundamentals of Programming

– 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

c.1. Logical AND (&&) and Boolean Logical AND(&)

c.2. Logical OR (||) and Boolean Logical OR (|)

c.3. Boolean Logical Exclusive OR(^) and Logical NOT (!)

d. Conditional Operator
– the conditional operator (?:) is a ternary operator
o 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

Prepared by: Dr. Michael John R. Robles Page 9 of 11


ITECC-2 – Fundamentals of Programming

– 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":"Failed";

//print status
System.out.println(status);
}
}

– The output of this program will be:


Passed

Operator Precedence
o it defines the compiler’s order of evaluation of operators so as to
come up with an unambiguous result

 TYPE CASTING
ο it is the process of converting data from one data type to another
ο it may be implicit or explicit

Implicit Casting
⎯ it is automatically performed by Java when no possible loss of data
may happen during conversion process
⎯ usually occurs when a smaller size data type is converted to a bigger
size data type
⎯ example:
byte a = 50; int b = a;

Explicit Casting
⎯ it is required if some data may be lost during the conversion process
⎯ usually occurs when a bigger size data type is converted to a smaller
size data type
⎯ syntax:
<(data type)> <expression>

• where: data type – is the name of data type you are converting
to (destination data type)
expression – is the value that is cast into the destination type
• example:
long a = 5000000;
int b = (int) a;

Prepared by: Dr. Michael John R. Robles Page 10 of 11


ITECC-2 – Fundamentals of Programming

 EXPRESSIONS
ο it is a combination of variables, operators, literals, and method
invocations that returns a value
ο used to assign values to variables, perform calculations, or control the
flow of execution (e.g. compare values)

Examples of simple expression


Examples Meaning
1. char middle = ‘F’ assigns the value ‘F’ to variable
middle
2. weight = weightKG * 2.2 computes the product of weightKg
* 2.2 and assigns the result to
variable weightLb
3. while(count < 10) { compares two integers, count and
10 and returns a Boolean value

Examples of compound/complex expression


Examples Meaning
1. Total = 1000 + (1000 * multiplies 1000 by 0.10 then add
0.10); the result to 1000
2. vPyramid = (1/3) * base * divides 1 by 3, multiplies the
height; result by base, multiplies the
result by height, them the assigns
the final result to vPyramid

 STATEMENTS
ο these are any code segment that is terminated by a semicolon
ο it can be an expression statement, declaration statement or control
flow statement, which usually appears in branching and loop control
structures
ο example:

System.out.print("Please Enter Your Name:");

 BLOCKS
ο it is one or more statements enclosed by a pair of braces { } that
groups the sequence of statements as one entity
ο an example of a block is the body of a class

import java.util.Scanner;

public class GetInputFromKeyboard


{
public static void main( String[] args )
{
Scanner input = new Scanner(System.in);
String name = "";

System.out.print("Please Enter Your Name:");


name = input.nextLine();

System.out.println("Hello " + name +"!");


}
}

Prepared by: Dr. Michael John R. Robles Page 11 of 11

You might also like