Hapter 2 The Java Technology
Hapter 2 The Java Technology
Simple – Java is designed to be easy to learn. If you understand the basic concept of OOP it will
be easy to master. They have also tried to avoid confusing concepts such as pointer, multiple
inheritance etc.
Object oriented – Java is inherently object oriented. Most object oriented languages began
strictly as procedural. However, Java was designed from the start to be object oriented.
Distributed - distributed computing involves several computers working together on a network
as a single unit. Since, networking capability is inherently integrated in to Java writing a network
program is very easy.
Integrated - the programs are compiled in to the java virtual machine code called Byte code.
The byte code is machine independent and can run on any machine that has a java interpreter
installed which is part of JVM.
Robust (reliable) - It supports early error checking and exception handling.
Architecture Neutral – you can write a program that can run on any plat form. This kind of
programming is called WORA (write once run anywhere).
Multithreaded – it gives a capability to program software’s that can perform several tasks
simultaneously.
E.g.
Example.java source code
Example.class the compiled byte code
Byte code – is a machine language of JVM (java virtual machine). It is not native to any of the
processors.
Then, the java launcher tool runs your Example.class with an instance of the java virtual machine. Since
JVM is available for many different operating system the .class file is capable of running on Windows,
MAC, Solaris, Linux etc.
JAVA PLATFORM
A platform is hardware or a software environment in which a program runs. However, Java platform is a
software only platform that runs on the top of other hardware based platforms such as operating
systems. Java platform includes JVM and JAVA API.
JVM – it is the base for java platform and is ported on to various hardware based platform (Operating
systems).
Java API – it is a large collection of ready-made software components that provide many useful
capabilities such as database connectivity, input output, graphical user interface etc. It is grouped in to
libraries of related classes and interfaces. These libraries are known as packages.
Servlets: are web based java programs that run on an internet server computer rather than in an
internet user browser.
JDK (Java development kit): it is a toolkit for developers. It includes Javac compiler and java runtime
environment (JRE).
JRE (Java runtime environment): the program that emulate the JVM. Therefore, if a user wants to
run a program developed with java it should download and install the JRE.so that the users can run java
to run java you only download and install the JRE.
JVM (Java virtual machine): It is the platform independent machine emulated by JRE. All java
programs run in JVM. It is responsible for tasks such as interpretation, garbage collection etc.
JDB (Java debugger): the Java debugger is used for running java codes from command-line interface.
Java SE (Standard Edition): a term used to describe the java language and the basic set of API
libraries that are used to create java programs. It is the purest form of java and foundation for all other
editions.
Java EE (Enterprise Edition): an extended set of API libraries that provide us special functions to
develop servlets.
Java ME (Micro Edition): the version of java for developing the applications running on embedded
systems, mobiles and small devices.
Java comments: java has multiline, single line and documentation type comments.
Java white spaces: White spaces are separate token in the source code. It is also used to improve
readability of the source code. White spaces include a space created by space bar; newline and tab.
White spaces are required in some places, forbidden in others and have no impact in some places.
o White spaces are required within declarations:
Int name = 0; here between the data type and identifier
o Has no impact on other places. But can be used to increase readability and to make
a meaningful indentation.
Int name = 0;
Int name = 0;
Int name = 0;
The above three declarations work fine.
o White spaces are forbidden at some places.
Int na me = 0; it is forbidden to use space within a variable name.
In t name=0; it is forbidden to use them within key word
N/B the amount of white spaces is irrelevant between tokens. It doesn’t matter if it is one or multiple,
tab or newline. However, we can use them to increase the readability of our source code.
Java Identifiers: Identifiers are name of a variable, methods classes or parameters that are defined by
the user. Some of the rules are the following:
o Alphanumerical character
o Dollar sign
o Underscore
o Can include upper or lower case letters
o Other special characters are not allowed such as space, &, *, etc…
o Identifiers are case sensitive. For instance, Number and number are recognized as
two distinct names.
o An identifier cannot begin with a digit (numeric).
o Java keywords cannot be used as an identifier.
Java Literals: A literal is a textual representation of a particular value of a type. Literal types include
Boolean, integer, floating point, string, null or a character.
N/B a literal will be assigned a value at compile time, while a variable is assigned at runtime.
Java Operators: It is a symbols used to perform a specific action on some value. Some of the operators
are +,*,^,& etc…
Java Separators: Separators are a sequence of one or more character used to specifity the boundary
between separate, independent regions in a source code. The following are the basic separators used in
java.
Java Keyword: It is a reserved word in java language. It is a word that is has a specific meaning in java
language.
Declaring a variable
- In a Java program you must explicitly declare all variables before using them. Some languages
such as Basic and Visual Basic used to allow using of variables that has never been declared.
- Variable declaration is a memory allocation that holds a certain type of data.
Syntax
Datatype identifier; or datatype identifier1, identifier2, identifier3…..;
Syntax
2. Instance variable: is a variable declared in a class but outside a of a method. As the name
indicates it is associated with an instance of a class. You must use the object of that class to
access them.
Syntax
Datatype identifier;
Int number;
3. Local variables: a local variable is a variable with a body of a method. Therefore, you can only
use it with in that method.
Constants
A final or constant variable is whose value you can’t change after it is assigned once.
Syntax:
identifier = value;
number = 10;
syntax
System.out.print(“hello”);this leaves the cursor on the same line where the output is
displayed. Therefore, the next output will be displayed on the same line.
An import statement should be outside the class below the package statement.
Import java.util.Scanner;
Unlike outputting with a System class which we use a static object out, if we want to use the scanner
class methods we should instantiate (create an object from it).
So, in the above example we use the input object to access methods that are used to accept different
types of data. The following are list of the methods in the Scanner class:
Method The data type it accept
nextByte() Byte integer
nextDouble() double
nextInt() integer
nextShort() Short integer
nextLong() Long integer
nextFloat() float
nextLine() String
next().charAt(0) Character
Int size;
char grade;
size = input.nextInt();
char = input.next().charAt(0);
Operators
Arithmetic: + * - / %
%( modulus) operator is used to evaluate the reminder when the right side operand is divided by the left
side operator.
+= -= /= *= %=
and soon.
Increment and decrement: it increases or decreases the value within the variable by one.
Postfix Prefix
Int x = 0;
System.out.println(x++); it displays 1 but increments the value by 1 afterwards and the value in
x will be 2
Comparison Operators: it compares the right and left side numerical values and returns true or false.
Comparison operators are binary operators. Therefore, it only works for two operands.
Equality == !=
Int x = 10;
x <= 10 > x this is a syntax error because it used three operands x, 10 and x
Logical Operators: it compares right side and left side truth values and returns true or false. Logical
operators allow multiple operands unlike comparison operators.
A B A || B
T T T
T F T
F T T
F F T
A B A && B
T T T
T F F
F T F
F F F
A B A^B
T T F
T F T
F T T
F F F
A !A
F T
T F
Conditional Operator: it is a tertiary operator that accepts a condition as the first operand and values
or variables as the second and third operands. It evaluates the first conditional statement and if it is true
returns the second operand or returns the third operand if it is false.
int x;
x = (6==12) ? 20 : 30; in this case 30 will be assigned to x since the condition (6==12) returns
a false value
boolean j = true;
boolean c = false;
int num = 13;
x = (j||c) ? num : 20; in this case since the condition(j||c) will be evaluated to true the value with in
Java statements
Statements are roughly equivalent to sentences in natural language. A statement forms a complete unit
of execution. Some of expressions can be made into a statement since they can make one complete unit
of execution.
Expression Statements: as mentioned above they are a kind of expressions that can make one
complete unit of execution and ends with semicolon. Below are expressions that can be considered as a
statement:
Declaration Statements: also, variable declarations act as one single unit of execution and terminate
with a semicolon. Therefore, they are considered as statements.
Control Flow Statements: these are statements that are used to manipulate the flow of our program
execution. It can be subcategorized in to three.
Decision making statements – these are statements that enable us to write a section of our program
that will choose and execute a block of code based on a conditional expression given.
}while(condition);
Branching Statements:
- Break statement: it is used to break out of the loop before the condition that stops the loop is
fulfilled.
E.g. for(int i=0;i<5;i++){
System.out.println(i);
If(i==2){
Break;
}
}
Without the break statement the loop will stop only when ‘i’ reaches 5 displaying 0 1 2
3 and 4. However, with the loop included the loop will be stoped by the break statement when
‘i’ reaches 2. Therefore, it only displays 0 1 and 2.
- Continue statement: it is used to jump the block of code after it and returns back to the starting
point of the loop.
E.g. for(int i=0;i<5;i++){
If(i==2){
continue;
}
System.out.println(i);
}
Without the continue statement the loop will display 0 1 2 3 and 4. However, since continue;
statement will be executed when ‘i’ reaches 2 the system.out.println() statement will be jumped
once. Therefore, what will be displayed is 0 1 3 and 4.
- Return statement: it is used with in methods (functions) that are defined with a return type.
When used not only returns a value but also terminates the function when executed.
E.g public float testReturn(int x){
if(x>1){
return x;
}
x+=2;
return x;
}
If we invoke the testReturn(int) passing a value greater than one it will enter the if condition and
execute return x; and terminates the function right there.
testReturn(3); displays 3
testReturn(4); displays 4
However, if the function is supplied with number less than one and invoked, it will execute the
statement x+=2; and return x; then it terminates the function right there.
testReturn(1); displays 3
testReturn(0); displays 2
- Fields (variables)
- Methods
- Constructor
- Inner classes
- Finalize
You can include all or some of the members according to your need. Also, java doesn’t care about the
order of the class members are put when defining the class.
Class Visibility
A class can have two types of access levels, public and default. If public key is used to declare it, it will
assume a public visibility and can be accessed everywhere in our program. However, if we declare it
without the public key word it will assume the default visibility level. In this case, the class will only be
visible to the classes in the same package.
Naming a Class
A class name is an identifier given to a class which is used to create an instance from it. Some of the
things to consider while naming a class:
- The class name should be self-explanatory. It should be neither short which will be hard to
understand what it does, nor very long which will make our code look congested.
- Follow the upper camel case rule. It should begin with an upper case and every word that follow
should begin with an upper case.
E.g. public class UpperCase{ members }
public class FoodTaster{ members }
- Since nouns are used to name objects in the real world, it is appropriate to use nouns for a class
name.
- Try not to use Java API class names. If so, you need to use fully qualified name to call them. For
instance if you create your class with the name Scanner, since it confuses the compiler which
class it should use, we must call the Scanner class using its fully qualified name that include its
package path: java.util.Scanner s = new java.util.Scanner(System.in);
Fields
A field is a variable that is defined within the body of a class and outside any of the class methods. A
field is an important member of a class by which the data that uniquely distinguishes one
instance/object from a class with another. If a class is only made from methods/functions the whole
idea of creating lots of instance/object from that class would be valueless.
- Class fields
- Instance fields
Class Fields:
Class fields are also called static fields or static variables. Only one copy of class fields are created for a
class. This type of variables is visible within any kind of method/functions in that class. A static key word
is used to declare such variables. To access the class fields we simply use the class name and a dot
operator. It is not mandatory to create an object to access class/static fields.
Instance Fields:
As the name indicates these types of fields/variables are created whenever an instance/object is created
form that class. Each object/instance from that class will have their own copy of them. Therefore, it is
mandatory to create an object to use this type of member fields. Such fields cannot be used with in a
static method.
w1.number = 20; // now we are setting ‘number’ that exist with in the first object
System.out.println(w2.number); displays 10 // ‘number’ variable within the second object
System.out.println(w1.number); displays 20 // ’number’ variable within the first object
Both class fields and instance fields can be made constant. Constant fields cannot be changed anywhere
in our program once they have given a value. We use final keyword to make fields constant.
It is a good practice to make all the letters in the name of a constant variable upper case.
Access specifier: a variable access type can be public, protected, default and private according to one’s
need.
2. Objects
Creating a class is just creating a data type or a template; unless you create an object or inherit from it
you cannot use the members of that class except the static ones. In order to create an instance/object of
that class type we use the name of the class.
Obtaining an object of a class is a two-step process. First, you must declare a variable of that class type.
This variable does not define an object. However, it serves as a reference to an object we are going to
create later and holds its address in the memory.
E.g. Assume we have a class named Geometry. The first step would be creating a reference.
Geometry g; //g is a variable or a reference to our object we are about to create. It is not an object it self.
Second, you must create an actual physical copy of the object and assign it to that variable. In order to
do this, we use a new keyword and a constructor form that class. The new operator and a constructor
dynamically allocate memory for an object and return a reference to it. This reference is, more or less,
the address of the object in the memory.
g = new Geometry(); //the new keyword and the constructor( Geomery()) stores the address on variable ‘g’
We can create anonymous objects by just using a new keyword and the class constructor.
System.out.println(new Geometry().PI); displays 3.14 // this displays the value in PI variable using anonymous object
System.out.println(new Geometry().add(3,4)); displays 7 // it is another anonymous object we used to call add(int,int) function
Since we haven’t stored their address in a variable, anonymous objects cannot be used later in our code
after used the once.
3. Methods
A method is one type of a class member that is used to operate on data’s within that object or passed to
it from outside.
Java main method: java desktop application must have one main method. It is declared in the class
which you want to be the starting point of your program. This method contains the general logic of your
program in which the other classes interact to perform the task we want our software to perform.
The signature of the main method is:
Return type: a return type specifies the type of data the method must return somewhere inside. If we
want to create a method without a return type we make it void.
E.g. protected void show(){ // this method has a protected visibility and returns nothing
}
private float show(){ //this method has a private visibility and must returns float type of data
return 12.02;
}
Parameter: it is a variable defined by a method so that the function can perform an operation on a
value that is passed to it. A parameter allows a method to be generalized. Therefore, it can operate on a
general data that is passed to it from anywhere in our program. A function can be defined without or
with a parameter.
E.g public int increment(int a){ // a definition of a function with a single integer parameter
a = a+1;
return a;
}
Public int sub(int a,int b){ a function definition with two parameter
return a-b;
}
As a good practice most classes may have either a getter or setter methods or both.
Getters: getter methods also called an accessor are used to access data from an object. Their typical
structure is, it will have a return type but not a parameter. Their name will be a concatenation of get and
the name of the variable/field.
E.g if the variable/field name is area the method name will be getArea
>> length >> getLength
Setters: setter methods also called mutator are used to change a specific field. There typical structure
is, they are mostly declared with no return type and a single parameter. Their name will be a
concatenation of set and the name of the variable/field.
E.g if the variable/field name is height the method name will be setHeight
>> length >> setLength
public void setRadius(int radius){ // a setter function with one int parameter type
this.radius = radius;
}
Static methods: a static method belongs to the class rather than the object created by that class. It can
be invoked without creating an object. Static keyword is used in order to define a static method.
public static float getPI(){ // this is a sample of a static method that has a return type
return 3.14;
}
Constructor: it is a special type of method called only when an object is created. Every class must have
at least one constructor. It is used to initialize variables or fields, open files, open databases and soon. If
you don’t create one the compiler creates it for you. The default constructor initializes fields to their
default values numbers to 0, boolean fields to false and references to null.
Rules for creating a constructor are the following
If you define a constructor with a private access type you can only create an object within the class itself
or it should be an inner class of other class in order to be used. However, it cannot be accessed by
inheritance and object creation.
class ConstuctorExample{
int var;
ConstuctorExample(){ // a constructor with no parameter
System.out.println(“I am a constructor without parameter”);
}
ConstuctorExample(int a){ //a constructor with one integer parameter
this.var = a;
System.out.println(“I am another constructor with a single integer
parameter”);
Garbage collection is done to objects that are no longer possible to be referenced and accessed by our
program. These objects will be deallocated from the memory by Java, since they are assumed to be no
longer needed. Therefore, the memory can be ready for another use.
The following are some of the ways we can make objects legible for garbage collection:
1. Object created inside a method: when a method is called it goes inside the stack frame.
When the method execution is finished and popped out from the stack, all its members die.
Therefore, if an object is created with in an object, its life time will be the methods life time
within the stack. After the method is executed and popped out of the stack, the object will be
unreachable or anonymous. As a result, it becomes legible for garbage collection.
gbExample(); // a statement for calling the above method. After the execution of the
method the object created will become unreachable.
3. Nullifying the reference variable: when a reference variable of an object is assigned a null
value, it becomes unreachable and becomes legible for garbage collection.
4. Anonymous Object: the reference id of anonymous object is not stored anywhere. Therefore,
it becomes unreachable after used once.
new Maths(); // anonymous object . The object cannot be accessed after used once.
Finalize method
It is a type of method that is called before an object is destroyed by java Garbage Collector. It is an
important method if one wants to take care of the resources that were used by the object being
destroyed; such as closing files that has been used by that object.
class GarbageCollectionExample{
protected void finalize(){ // the definition of finalize method
// the code we want the function to perform comes here
}
}
It is possible to call java garbage collection instead of waiting java runtime to call it in its own time. The
syntax is: System.gc();
Inheritance
One of the pillars of object oriented programming is the concept of inheritance. As it is in Object
oriented programming, the main objective of inheritance is to promote code reusability and avoid
redundancy. It is a concept that enables a child class to obtain the features of its parent class. The
fields/variables and methods of the parent class will be passed on to the child class. In addition, it
enables the child class to add fields and methods of its own.
The class that does the inheriting is called child, derived or subclass. Whereas, the class that
is inherited, will be called parent, base or superclass.
Private members of parent or superclass can’t be accessed in side the child or subclass.
Visibility property of the members (fields and methods) that are inherited will remain the
same in the subclasses.
If you want to define members to be accessed only by inheritance you give them protected
access type. In the code below, the name field will only be accessed by the classes that
inherits from it, in this case, Father and Child classes.
Parent class members will also be passed to the derived class of the child class and soon. For
instance, according to the code below, the Child class can inherit members of GrandParent
class.
Parent classes can hold a reference of their child classes. However, it can only access
members of itself and its parents.
e.g GrandFather gf = new Father(); // it’s okay to this but gf can only access the members
of Grand Father class.
class GrandFather{
protected String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
In many cases, we might want to avoid using inheritance and just create an instance of the class we
want to use.
Types of Inheritance
1. Single Inheritance: one child class inherits from one base class.
class Parent{
}
class Child extends Parent{
}
class Child1 extends Parent{
}
class Child2 extends Parent{
}
3. Multilevel inheritance: parent class has a grand child.
class GrandParent{
}
class Child1 extends Parent{
}
class Child2 extends Parent{
}
4. Multiple inheritances: child inherits from two or more base classes. This type of inheritance is
not allowed in java because it creates the diamond problem(read further).
class Parent1{
}
class Parent2{
}
class Child2 extends Parent1, Parent2{
Super keyword
Super keyword is used to access parent class members.
class Parent1{
int a=10;
Parent1(){
System.out.println(“parent constructor”);
}
}
class Child extends Parent1{
Child(){
System.out.println(super.a); //used to display super class variable ‘a’
super(); //super class constructor displays ‘ parent constructor’
}
}
Overloading
It is a type of polymorphism that enables us to create multiple methods with the same name but
different signature.
Method signature
A method signature is the type, order and number of parameters.
E.g.
2 public float add(float a, int b){ // this method is different from method # 1
// because of the type of parameters
return a+b;
3 public float add(int a, float b){ // this method is different from method #2
// because of the order of parameters
return a+b;
4 public float add(int a, int b, int c){ // this method is different from method #1
// because of the number of parameters
return a+b+c;
Overriding
Overriding is redefining of a method that was already created within the parent class. In order to be
considered as overriding, the name and the method signature should be the same as the method found
in the parent class.
E.g.
class Parent1{
int a=10;
1 public float add(int a, int b, int c){
return a+b+c;
}
2 public int add(int a, int b){
return a+b;
}
}
public int add(int a, int b){ // this method overrides method #2 from the Parent1 class
return a+b+1;
}
@override Annotation
It is a statement that requests Java compiler to check if we have overridden a method from super
classes. Java uses the name and method signature and if there wasn’t any method overridden it will not
compile our code. @override annotation should be written right above the method we defined to
override.
E.g.
In java, all the elements of an array must be of the same type. Thus, the array itself has a type that
specifies what kind of elements it contain,
It is possible to create an array with a primitive type such as int, float, etc... or with a user defined types
such as classes we created.
Math[] m = new Math[3]; // this create an array of class math with 3 index
1. The first step is creating a reference variable that refers to the array elements.
2. The second step is to use a new key word followed by the array type and a square bracket filled
with the size of the array. The array elements will be created by this statement.
In order to get the size of an array at runtime you can call length property using the array name.
e.g.
E.g.
}
A method with array
parameter and array return type int[]
getName(int[] c){
return c;
}
0 1 2 3
0
1
2
0 1
0 1 2
1 3 4
2 1 7
0
0 1 2
0 m t fr
o u i
n e
1 sa s w
t u e
n d
0 1 2
0 mon tue fri
1 sat sun wed
For instance, to display string “wed” from the above days array
0 1
0 1 2
1 3 4
2 10 7
for(int i=0;i<intTable.length;i++){
for(int j=0;j<intTable[i].length;j++){
System.out.println(intTable[i][j]);
}
}
for(int [] it:intTable){
for(int i:it){
System.out.println(i);
}
}
1
2
3
4
10
7
Characters
char Data Type
If we want our program to work with characters the one alternative java provides us with is char data
type. It is one of the primitive data types. A variable declared with a char data type can hold 2 bytes of
data which is sufficient to store a single Unicode character.
Declaration
e.g. char letter; //this creates a variable named ‘letter’ that can hold 2 bytes of data
Initialization
At Declaration
After Declaration
char letter;
letter = ‘a’;
Character Arrays
Declaration
char[] letters = new char[10];
Initialization
At Declaration
char[] letters = {‘a’,’g’,’h’}; or char[] letters = new char[]{‘a’,’g’,’h’};
After Declaration
//this statement replaces ‘h’ by ‘z’
letters[2] = ‘z’;
From a User Input
1. Character by character
letters[0] =
sc.next().charAt(0); //this replaces ‘a’ with a user input 2. A sequence
of character at once letters =
sc.next().toCharArray(); //this accepts multiple characters from the
user and stores it on ‘letters’ array
String
Unlike other primitive data types a string is class type. It provides us with functions that are very easy to
manipulate sequence of characters.
Declaration
String st = new String(“hello”); or String st = “hello”;
Concatenation (+)
String name = “example”;
String name = name + “ one”;
//this statement strores “example one” on variable ‘name’
With a primitive type
int a = 50;
String st = a + “ kilo”; //this statement stores “50 kilo” on
variable ‘st’
Conversion between Numeric Types and String
String to integer
String e = “50”;
int j = Integer.parseInt(); //this stores 50 on variable ‘j’
integer to String
int x = 20;
String u = Integer.toString(); //this
stores 20 on variable ‘u’