Java Fundamentals 12.0
Identifier(s)
- An identifier is a symbolic name that is assigned to some entity (e.g. name of
class
, method
, variable
, constant
, parameter
, etc.) within a computer code or program.
- Begin Character: In Java, an identifier can only begin with either an English alphabet (a-z, A-Z), an underscore (_), or some currency symbol ($, £, €, ¥, ¢, ₿, etc.).
- Trailing Character(s): In Java, trailing characters which exist after the Begin Character can include: numbers (0-9), English alphabets (a-z, A-Z), underscores (_), or currency symbols ($, £, €, ¥, ¢, ₿, etc.).
- Also, in Java, Reserved Words and Keywords (or Command Words) cannot be used as identifier. A comprehensive and up-to-date list of Reserved Words and Command Words is accessible by clicking here.
- Just as syntaxing in Java is case-sensitive; same applies to the naming convention for identifiers as they are case-sensitive too.
- There exist several notations that can be applied with respect to defining identifiers in Java programming. Hence, one of the most popular notation is the CamelCase notation, viz:
- UpperCamelCase notation: The syntactic standard this notation employs is by setting to UPPERCASE the first letter of each significant word in the identifier while all other letters remain in lowercase. Examples are:
MyVarName
, ProgrammingLessons
, MyStudentId
, MyIdentifier
, etc.
- lowerCamelCase notation: The syntactic standard employed by this notation is by setting to lowercase all the letters of the first significant word in the identifier; thereafter, for each subsequent significant word in the identifier, it is handled via UpperCamelCase notation. Examples are:
myVarName
, programmingLessons
, myStudentId
, myIdentifier
, etc.
Indentation
- Simply an abstract approach for aligning the physical layout of a program to its corresponding logical implementation.
- In other words, it is a syntax-formatting standard that helps in highlighting the logical flow of a computer program.
- In Java programming, the indentation standard is neither considered nor processed by the compiler and/or interpreter.
- The indentation standard of a Java program is essentially for human usage (and not for the computer).
- Thus, indentation makes a Java program or code much more easier to read, debug, update, etc.
- There exist quite a couple of indentation standards that can be applied to Java programming. Some of these popular standards include, viz:
-
Layout 1: Notice the placements of the curly brackets:
{
and }
.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class LayoutStyle1
{
public static void main(String[] args)
{
//Lines of code are resident here
}
}
Code Snippet: Layout Style 1
-
Layout 2: Also, take note of the placements for the curly brackets:
{
and }
.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class LayoutStyle2 {
public static void main(String[] args) {
//Lines of code are resident here
}
}
Code Snippet: Layout Style 2
2.1Data Types in Java
Basically, a data type refers to the kind or group of elements that can be stored and managed by an identifier. In Java, there exist two (2) broad categories of data types, viz:
- Primitive Data Types: These are data types which have been naturally defined in the core of Java programming language.
- Non-Primitive (or Derived) Data Types: These are data types which are usually derivatives of one or more primitive data types; and they are uniquely defined in separate
class
blocks that exist within Java's plugin library.
At the moment, we shall concentrate on the category of
Primitive Data Types that exist in Java; and their attributes are as summarized in the table below.
Category |
Type |
Data Type |
Size |
Capacity Range |
Default Data Type |
Primitive Data Types |
Integer |
byte |
8 bits |
28: -128 to +127 |
int |
short |
16 bits |
216: -32,768 to +32,767 |
int |
32 bits |
232: -2,147,483,648 to +2,147,483,647 |
long |
64 bits |
264: -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 |
Floating-Point |
float |
32 bits |
232: ±1.4E-45 to ±3.4028235E+38 |
double |
double |
64 bits |
264: ±4.9E-324 to ±1.7976931348623157E+308 |
Boolean |
boolean |
1 bit |
true or false |
Character |
char |
16 bits |
a single number, letter, or character |
2.2Variable(s) in Java
Variable: This is a storage location in memory denoted by a valid identifier, and which can be used to store varying values of a specific data type. The concept of variable(s) is/are often employed
in various aspects and domains of the real-world. For example, in a queue or line where the floor is labelled with a "STAND HERE" identifier serving as a placeholder for the accommodation
of any entity with 2 legs (this entity may vary such that it can either be a man, a woman, a boy, a girl, a child, etc.).
Caption: Real-world example for the concept of variable
In Java, the process of declaring and initializing a variable involves the following aspects, viz:
- Specify a data type for the variable.
- Specify a valid identifier for the variable.
- Optionally, we may specify an initial value for the variable with the aid of the Assignment (
=
) operator.
Therefore, the syntax for declaring a valid variable (
without initialization) is:
{data-type} {identifier};
Also, the syntax for declaring a valid variable (
with initialization) is:
{data-type} {identifier} = {value};
Note: In Java, this operator
=
is known as the
Assignment operator; and it assigns the content present on the right-hand-side to the variable identified on the left-hand-side.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
byte byteVar; //variable declaration (data-type = byte)
byteVar = 110; //variable initialization (value = 110)
short shortVar; //variable declaration (data-type = short)
shortVar = 30000; //variable initialization (value = 30000)
int intVar; //variable declaration (data-type = int)
intVar = 1000000000; //variable initialization (value = 1000000000)
long longVar; //variable declaration (data-type = long)
/* Append the letter 'L' or 'l' during initialization */
longVar = 1000000000000000L; //variable initialization (value = 1000000000000000)
longVar = 1000000000000000l; //variable initialization (value = 1000000000000000)
float floatVar; //variable declaration (data-type = float)
/* Append the letter 'F' or 'f' during initialization */
floatVar = 0.0005F; //variable initialization (value = 0.0005)
floatVar = 5.0E-4F; //variable initialization (value = 0.0005)
floatVar = 0.0005f; //variable initialization (value = 0.0005)
floatVar = 5.0e-4f; //variable initialization (value = 0.0005)
double doubleVar; //variable declaration (data-type = double)
/* Append nothing or the letter 'D' or 'd' during initialization */
doubleVar = 0.00082; //variable initialization (value = 0.00082)
doubleVar = 8.2e-4; //variable initialization (value = 0.00082)
doubleVar = 0.00082D; //variable initialization (value = 0.00082)
doubleVar = 8.2E-4D; //variable initialization (value = 0.00082)
doubleVar = 0.00082d; //variable initialization (value = 0.00082)
doubleVar = 8.2e-4d; //variable initialization (value = 0.00082)
boolean booleanVar; //variable declaration (data-type = boolean)
booleanVar = true; //variable initialization (value = true)
booleanVar = false; //variable initialization (value = false)
char charVar; //variable declaration (data-type = char)
charVar = 'A'; //variable initialization (value = 'A')
charVar = 65; //variable initialization (value = 'A' because 65 is the ASCII equivalent of 'A')
charVar = "A"; //Wrong variable initialization of data-type: char. Single quotes should be used only.
}
}
Code Snippet: Variable declaration and initialization statements with regard to several data types in Java
Note: The letter-suffix appended to the
long
,
float
, and
double
primitive data-type variable initialization is quite an important aspect of these respective variable initialization.
Generally, in Java programming,
a variable whose data type possesses a relatively higher capacity range can always accommodate a variable (or value) possessing a lower capacity range. However, the reverse is not possible.
For example, if we fail to append the letter-suffix 'L' or 'l' to a value during a
long
data-type variable initialization, the value by
default assumes an
int
data type and can only accommodate integers
up to the maximum capacity (+2,147,483,647) defined for the
int
data type.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
long longVar1; //variable declaration (data-type = long)
/*
The statement below results in a Syntax Error because the value: 1000000000000000 is now considered
as an "int" data type by the Java compiler; and 1000000000000000 exceeds the maximum capacity
defined for the "int" data type.
*/
longVar1 = 1000000000000000; //variable initialization (value = 1000000000000000)
long longVar2; //variable declaration (data-type = long)
/*
However, the statement below does not result in any error yet because the value: 2147483647, which is
now considered as an "int" data type by the Java compiler, is still within the maximum capacity
defined for the "int" data type.
*/
longVar2 = 2147483647; //variable initialization (value = 2147483647)
}
}
Code Snippet: Variable declaration and initialization statements with regard to the long
data type in Java
Now, for another example, if we fail to append the letter-suffix 'F' or 'f' to a value during a
float
data-type variable initialization, the value by
default assumes a
double
data type.
Since, by default definition, the maximum capacity (1.7976931348623157E+308) of a
double
data type exceeds the maximum capacity (3.4028235E+38) of a
float
data type.
Hence, the
float
data-type variable will not be able to accommodate the value defined as a
double
data type due to a data-type mismatch or incompatibility.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
float floatVar1; //variable declaration (data-type = float)
/*
The statement below results in a Syntax Error because the value: 1.7976931348623157E+308 is now considered
as a "double" data type by the Java compiler; and a "double" data type cannot be stored in a "float"
data-type variable due to a "type mismatch" error.
*/
floatVar1 = 1.7976931348623157E+308; //variable initialization (value = 1.7976931348623157E+308)
float floatVar2; //variable declaration (data-type = float)
/*
Also, the statement below results in a Syntax Error because the value: 21474.83647 is now considered
as a "double" data type by the Java compiler; and this throws a "type mismatch" error.
*/
floatVar2 = 21474.83647; //variable initialization (value = 21474.83647)
}
}
Code Snippet: Variable declaration and initialization statements with regard to the float
data type in Java
Yet another example, if we declare a
double
data-type variable and assign a
float
value to it, this will not throw any error because a
double
data-type variable can and will always accommodate any value defined as a
float
data-type; since the maximum capacity of a
float
value is always lesser than the maximum capacity of a
double
data-type.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
double doubleVar1; //variable declaration (data-type = double)
/*
The statement below is fine and valid without any Syntax Error.
*/
doubleVar1 = 21474.83647F; //variable initialization (value = 21474.83647F)
}
}
Code Snippet: Variable declaration and initialization statements with regard to the double
data type in Java
2.3Constant(s) in Java
Caption: Real-world example for the concept of constant
Constant: This is a storage location in memory denoted by a valid identifier, and which can be used to store a specific and fixed value of a particular data type. The concept of constant(s) is/are often employed
in various aspects and domains of the real-world. For example, in any office possessing a Reception Desk, that unit or desk can only be constantly occupied by a Receptionist whom has the specific qualities and etiquette
for the job.
In Java, the process of declaring and initializing a constant involves the following aspects, viz:
- Specify the
final
keyword.
- Specify a data type for the constant.
- Specify a valid identifier for the constant.
- Optionally, we can specify a fixed value for the constant with the aid of the Assignment (
=
) operator.
Therefore, the syntax for declaring a valid constant (
without initialization) is:
final {data-type} {identifier};
Also, the syntax for declaring a valid constant (
with initialization) is:
final {data-type} {identifier} = {value};
Note: In Java, we can clearly observe that the declaration and/or initialization of a constant is quite similar to that of a variable except for the prefixing of the
final
keyword. In fact,
a constant simply implies:
final
+ variable declaration/initialization. However, do note that whatever value is assigned to constant is fixed and final; this means that its value can neither be
altered nor updated during the execution/run time of the Java program. Also, in Java programming, it is customary to always specify the identifiers for constants in all UPPERCASE.
2.4Package(s) in Java
A package is a directory-like structure used in Java for aggregating and storing correlated source files and/or class blocks. Most times, a package usually contain one or more sub-package(s); and in turn, each of these
sub-packages can store several correlated source files (or class blocks). In fact, a realistic illustration of how packages function in Java can be likened to your conventional book shelf at either your room, home, school, etc.
For example, using our sample book shelf (i.e.
package in Java) titled:
ProgLessons; this shelf possesses 3 rows/sections (i.e.
sub-packages in Java), namely:
Section1,
Section2,
Section3;
and each row/section organizes one or more books (i.e.
source files in Java). Hence, to refer and/or access any of these books, we essentially employ this path-reference syntax:
<shelfID>
.
<sectionID>
.
<bookID>
.
So, to access some selected books; we can simply use the following paths, respectively:
-
bookID = FUNDAMENTALS:
ProgLessons
.Section3
.FUNDAMENTALS
-
bookID = CODING:
ProgLessons
.Section3
.CODING
-
bookID = NATURE:
ProgLessons
.Section1
.NATURE
Basically, all the prewritten classes in Java's libraries are structured, organized, and stored using package(s); and to access and/or reference any of the prewritten source file (or class block), the following path-reference
syntax is used, viz:
<packageName>
.
<sub-packageName>
.
<className>
. Moreover, once a package and/or sub-package is created in Java, this also creates a corresponding
folder/directory for the package and a corresponding sub-folder/sub-directory for the sub-package (all within the
src
folder for a Java project). To access the contents of the
src
folder for a Java project,
simply navigate to the
Package Explorer panel (i.e.
leftmost panel) of the Eclipse
® IDE and perform the following, viz:
- Right-click on the
src
folder contained within the Java Project folder;
- In the drop-down menu that appears, click on the
Show In
option;
- Lastly, in the next drop-down menu that appears, click on the
System Explorer
option.
Caption: System-Explorer view of a Java Project
Additionally, a package can possess several sub-packages nested within it by means of multi-level nesting. Hence, to create a package in Java, we can perform the following, viz:
- Right-click on the
src
folder contained within the Java Project folder;
- In the drop-down menu that appears, click on the
New
option;
- Thereafter, in the next drop-down menu that appears, click on the
Package
option;
- Next, in the next menu window that appears, specify the name of the package and corresponding (nested) sub-packages using the dot-notation syntax:
<packageName>
.<sub-packageName>
;
- Lastly, click on the
Finish
button.
Caption: Creating a Package and Sub-package for a Java Project
Next, to populate a package/sub-package (in Java) with some source files or class blocks; we can perform the following, viz:
- Right-click on the
package.sub-package
folder contained within the Java Project;
- In the drop-down menu that appears, click on the
New
option;
- Lastly, in the next drop-down menu that appears, click on the
class
option.
Caption: Creating a Java source file within a package/sub-package
Do notice that for every package and/or sub-package created in a Java project, a corresponding folder and/or sub-folder is created, respectively. Thus, the diagram below shows the directory/folder hierarchy
containing a package, a sub-package, and a source file, respectively.
Caption: Creating a Java source file within a package/sub-package
2.5Importing Classes from existing Packages in Java
The
import
keyword is a command word in Java which is reserved for importing a source file (or class block) from a predefined or existing package/sub-package in Java programming. Generally, packages/sub-packages
can be broadly categorized into two (2), namely:
- Predefined Package: This refers to a package that has already been prewritten and exists by default within the Java API (Application Programming Interface) library.
- User-defined Package: This refers to a package that is self-defined and managed by a programmer for the purpose of code reusability, management, etc.
The following code snippet shows how we can use the
import
keyword for referencing and importing a source file (or class block) located either in a
Predefined Package or
User-defined Package.
Thus, the following syntax is employed with regard to the usage of the
import
keyword:
import <packageName>.<sub-packageName>.<sourceFileName>;
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
/* ABSOLUTE REFERENCING (via a Predefined package): */
/* Links/References directly to a specific source file (or public-class block).
Here, we have imported the 'Scanner' file which is located within the
'util' sub-package, and this sub-package resides within the 'java' package */
import java.util.Scanner;
/* RELATIVE REFERENCING (via a Predefined package): */
/* Links/References indirectly to all the source files (or public-class blocks)
resident within a particular sub-package or package.
Here, we have imported all the files which are located within the 'util'
sub-package, and this sub-package resides within the 'java' package */
import java.util.*;
/* ABSOLUTE REFERENCING (via a User-defined package): */
/* Another example which directly imports the 'HelloWorld' class or file
that we recently created within the 'section1' sub-package and the
'proglessons' package */
import proglessons.section1.HelloWorld;
}
}
Code Snippet: import
statement in Java
2.6Type Casting
In Java programming,
Type Casting is a technique used to convert a value from one primitive (data) type to another primitive (data) type. Thus, this is done with the aid of the
cast operator in Java;
and its syntax is:
(target data-type)
. The following examples illustrate how the
cast operator is employed during primitive (data) type conversions.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
char var1 = 'a';
int var2 = (int) var1; //Returns the ASCII equivalent for 'a'
System.out.println(var2);
double var3 = 12345.67890;
int var4 = (int) var3; //Truncates trailing values after decimal point
System.out.println(var4);
}
}
Code Snippet: (Data) Type Casting in Java
Notice that for
var3
, which is originally of data type:
double
; and upon casting to
int
, the trailing values after the decimal point are always lost (
and not rounded up).
To perform a rounding up, we should use the
round()
method which is predefined in the
Math
class and located within the
java.lang
package.
Math
class
- This is an important prewritten
class
block which is packaged and available in the java.lang
package.
- The
Math
class block encapsulates several method
implementations which perform different unique tasks.
- The
java.lang
package is automatically and implicitly imported into any Java program (or source code); hence, there is no need for any explicit import
statement for this package.
- Some of the
method
implementations in this class include: round()
, pow()
, random()
, ceil()
, floor()
, etc.
round()
: rounds a float
or double
data-type value to its nearest whole number.
pow(a, b)
: returns the value of ab.
random()
: returns a random value, x, of double
(data) type which lies between 0.0 ≤ x < 1.0.
ceil(x)
: computes the ceiling operation for x (double
data type).
floor(x)
: computes the floor operation for x (double
data type).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals1 {
public static void main(String[] args) {
double var3 = 12345.67890;
int var4 = (int) Math.round(var3); //By default, Math.round() returns a 'long' data type
System.out.println(var4);
double var5 = 12345.12345;
int var6 = (int) Math.round(var5); //By default, Math.round() returns a 'long' data type
System.out.println(var6);
double var7 = 12345.12345;
double var8 = Math.ceil(var7); //By default, Math.ceil() returns a 'double' data type
System.out.println(var8);
double var9 = 12345.12345;
double var10 = Math.floor(var9); //By default, Math.floor() returns a 'double' data type
System.out.println(var10);
}
}
Code Snippet: (Data) Type Casting and rounding up numeric values in Java
2.7Practice Exercise
- TRUE or FALSE: In Java programming, an identifier can begin with a
€
symbol?
- TRUE or FALSE: In Java programming, the name of a variable can end with a
¥
symbol?
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
float v4 = 123.45f;
System.out.println(10 + 20 + v4 + "123" + 10);
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
int walletValue;
double itemCost = 22.22d;
double change = walletValue - itemCost;
System.out.println("Your change is: " + change);
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
int v5 = 100;
double v6 = 123.987;
v5 = (int) (v5 + v6);
System.out.println(v5);
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 1.
* @author Dr. Bonaventure Chidube Molokwu.
*/
int v5 = 2;
int v6 = 7;
v5 = v6 / v5;
System.out.println(v5);