by eturo
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 an 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:
§ e.g. java.io.*; java.util.*; javax.swing.*;
¤ IDENTIFIERS
Ø are tokens that represent names of variables,
methods, classes, etc.
o
examples of identifiers are: Hello, main, System, out
Ø these are case-sensitive
o
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.
Java Escape Sequences
Ø sometimes referred to as backslash character constants
Ø used in place of the characters that they represent
Table 1.0. 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)
|
Ø sample program that demonstrate escape sequences
public class Demo
{
public static void main(String args[])
{
System.out.print("Hello \tWorld");
System.out.println("\nMy
name is \"Ashlee Shayne\"");
System.out.println("I \’love\’ \n\tJava
Programming!") ;
}
}
Ø the output is shown here:
Hello World
My name is “Ashlee Shayne”
I ‘love’
Java Programming
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
/*
* This is
my first Java program.
* This is
an example of a comment in Java.
*/
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
*/
·
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: November 28, 2010
@version 1.0
*/
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”
|
|||||||
·
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
§ 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”
Abstract Data Types
Ø is a keyword of a programming language that specifies the amount of
memory needed to store data
Ø 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,
such as the int, char, float, double, short, byte and boolean data
types
§ sometimes call these as built-in data types
o user-defined 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 character
§ ideal for storing names of things
·
Boolean
(logical)
§ stores a true or false value
§ the correct choice for storing a yes or no or true or
false response to a question
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.12: Simple Java Data Types.
|
|||
Data Type
|
Data Type Size/Length
|
Range of Values
|
Group
|
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 2,147,483,647
|
Integers (Integral)
|
long
|
64 bits
|
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
|
Integers (Integral)
|
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 (Unicode)
|
65,536 (Unicode)
|
Characters (textual)
|
boolean
|
1 bits
|
0 or 1
|
Boolean (Logical)
|
·
Integer (Integral) Group
·
uses
three forms – decimal, octal or hexadecimal.
2 //The decimal
value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hexadecimal value
·
signed number – an integer that
is stored with a sign (negative numbers)
·
unsigned number – an integer that isn’t stored with a sign (positive
numbers)
Ø byte
o it is the smallest
abstract data type in the integer group and is declared by using the keyword byte
o typically use when sending data to and receiving data
from a file or across a network
Ø short
o it is ideal for use in programs that run on 16-bit
computers
o it is the least used integer abstract data type
Ø int
§ used for control variables in control loops
§ used in array indexes
§ used when performing integer math
Ø long
o it is used whenever using whole numbers that are beyond
the range of an int
data type
·
Floating-Point Group
·
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
·
used to store real numbers in memory
o a real number contains a decimal value
·
two
kinds of floating point data types:
o float data
type is a single precision number
o double data
type is a double precision number
§ Precision – it is the number of places after the decimal point
that contains an accurate value
§ the real number which is stored as a whole number
§ the position of the decimal point within the whole number
Ø float
o it is used for real numbers
that require single precision
§ Single precision
·
means
the value is precise up to 7 digits to the right of the decimal
Ø double
o the default data type in
floating point group
·
Character (Textual) Group
·
it is
represented as an integer value that corresponds to a character set
·
character
set - assigns an integer value to each character, punctuation, and symbol used
in a language
Ø char
o represents a single Unicode character. It
must have its literal enclosed in single quotes(’ ’). For example:
‘a’ //the letter a
‘\t’ //a tab
·
Although, String is not a
primitive data type (it is a Class). 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!”;
·
Boolean (Logic) Group
boolean result = true;
·
the example shown above, declares a variable
named result as boolean type and assigns it a value of true
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.
A.
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:
§ Note: Values
enclosed in < > are required values, while those values enclosed in [ ]
are optional.
§ 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 1.25
double grade = 1.25;
}
}
Ø Initializing Variables
Assignment operator (=)
–
Used to assign value to a variable
•
char c =
‘a’; à note the single quotes
•
boolean
test = true;
•
double
grade = 1.25;
–
Important:
This is different from the comparative equals (==)
–
If variable is not initialized, most will default
to null.
–
All variables should be initialized.
B. 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 );
}
}
§ The program will output the following text on screen:
10
The value of x = A
§ In the statement, System.out.println(“The value of
x = “ + x );, the concatenation operator (the plus (+) sign) is used to
concatenate or join the string litertals “The
value of x = “ to the value of the variable
x.
C.
Reference
Variables vs. Primitive Variables
§ We will now differentiate the two types of variables that Java programs
have.
§ These are reference variables and primitive variables.
o
Primitive variables
§ are variables with primitive data types
§ 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
§ 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();
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”
o
it denotes value cannot
change
Ø declaration syntax:
Ø examples:
final double PI = 3.1416;
final double SALES_TAX_RATE = 4.5;
final int PASSING_GRADE = 75;
Happy coding guys..
Happy coding guys..