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

Hapter 2 The Java Technology

Java is both a programming language and platform. As a language, it is simple, object-oriented, distributed, integrated, robust, architecture neutral, and multithreaded. Source code is compiled to bytecode, which runs on the Java Virtual Machine (JVM) and is platform independent. The Java platform includes the JVM and Java API libraries. Key aspects of the Java language include comments, whitespace, identifiers, literals, operators, and variables/data types.

Uploaded by

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

Hapter 2 The Java Technology

Java is both a programming language and platform. As a language, it is simple, object-oriented, distributed, integrated, robust, architecture neutral, and multithreaded. Source code is compiled to bytecode, which runs on the Java Virtual Machine (JVM) and is platform independent. The Java platform includes the JVM and Java API libraries. Key aspects of the Java language include comments, whitespace, identifiers, literals, operators, and variables/data types.

Uploaded by

Ermias
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

CHAPTER 2 THE JAVA TECHNOLOGY

 Java technology is both a programming language and a platform.

JAVA PROGRAMING LANGUAGE


It is a general purpose high level programing language originally developed by sun micro systems by a
team led by James gosling and released in 1995. It was designed to be:

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.

How does it work?


First all the source code is written in plain text and saved in to .java extension files. Then, after
compilation with Javac compiler to byte code it will be saved to .class extension file.

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.

ACRONYMS AND JARGONS


Applets: Java programs that run directly with in a web browser. To run the applet the browser starts
JVM and that virtual machine is given a portion of the web.

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 LEXICAL STRUCTURE

Java comments: java has multiline, single line and documentation type comments.

- //example single line comment


- /*example*/ multi line comment
- /** example */ documentation comment

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.

o Integers 23, 6, 7 ...


o Floating point numbers 20.75, 5.399 …..
o Strings “example” , “string”
o Boolean true or false
o Character ‘a’, ’B’, ’j’……
o Null it is also a literal that can be assigned to references. var = null;

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.

o [] used during array declaration


o () used for method definition E.g. name(par1,par2)
o ; end of statement
o “ ” to indicate a string literal
o ‘ ’ to indicate a character literal
o { } to group block of statement

Java Keyword: It is a reserved word in java language. It is a word that is has a specific meaning in java
language.

Variables and Data types:

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…..;

The following are Java primitive data types:

Name Size Type of data


int 4 byte integer
short 2 byte integer
long 8 byte integer
byte 1 byte integer
float 4 byte Floating
numbers
double 8 byte Floating
numbers
char 16 bit character
Boolean Not precisely 0 or 1
known true or false
Types of variables
1. Class variables (static variable): it is a variable that any method in the class access, including
static methods. It is also known as a static variable and only one copy of it will be there per class.
It should be declared outside a method. The class name is used to access it.

Syntax

Static datatype identifier;

Static int number;

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:

final datatype identifier=value; or

final datatype identifier;

identifier = value;

final int number = 10; or

final int number;

number = 10;

Class variables (static variables) can be a constant

syntax

static final datatype identifier = value;

static final int number = 44;


Character Literals:
Character literals are a type that we have discussed earlier while talking about literals in this chapter.
Some of the characters especially alphabets, numeric and some special characters are easy to insert
using a keyboard. However, some cannot be inserted using a keyboard. Therefore, we can use special
escape sequences to represent some special characters. Some of the escape sequences and the
characters they represent are listed below:

Escape Sequence Explanation


\b Back space
\t Horizontal tab
\n Line feed(new line)
\r Carriage return
\” Double quote
\’ Single quote
\\ Backslash
Please experiment with the above escape sequences by inserting them with in a string, as shown below:

System.out.println(“I still have no idea what \r escape sequence character does.”);

Output Statement in Java


To output literals or values from variables we use java System class. Since java made this class visible
anywhere in our program, it is possible to use it without importing it to our class file.

We can use it in two ways:

System.out.println(“hello”); this moves the cursor to a new line after displaying

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.

Input Statement in Java


To scan a user input from the keyboard java provides us with a class called Scanner. Since the class is not
visible anywhere in our code, we should first import it before trying to use it within a class file. Scanner
class resides in java.util package.

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

Scanner identifier(name) = new Scanner(System.in);

Scanner input = new Scanner(System.in);

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

The following are some usage examples:

Scanner input = new Scanner(System.in);

Int size;

char grade;

size = input.nextInt();

char = input.next().charAt(0);

Expressions and Operators


Expression
An expression is a construct that convey a value. It is made up of combination of variables, literals and
operators or a method call that can be evaluated to a value.

Assignment size = 83;

Increment or decrement size++; or size--;

Object creation Maths m=new Maths();

Comparison value1 == value2

Method call area();

Operators
Arithmetic: + * - / %

%( modulus) operator is used to evaluate the reminder when the right side operand is divided by the left
side operator.

E.g. 5%2 = 1 7%4 = 3 10%5 = 0


Assignment: it evaluates the right side value and store it on left side variable.

variable = expression; number = size + 10;

variable = literal; number = 10; or name = “Alemu”;

variable = variable2; number = size;

Compound assignment: it the combination of assignment and other operators

+= -= /= *= %=

Variable += 3; is equivalent with variable = variable+3;

Variable %= 3; is equivalent with variable = variable%3;

and soon.

Increment and decrement: it increases or decreases the value within the variable by one.

Postfix Prefix

Increment var++; ++var;

Decrement var--; --var;

Int x = 0;

System.out.println(++x); it displays 1 after incrementing the value in x by 1

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 == !=

Relational <= < > >=

Int x = 10;

x >= 10 this will be evaluated to true

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.

- And operator && or &


- Or operator || or |
- Not operator !
- Xor operator ^

Truth tables for the above 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

num will be assigned on x

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:

- Assignment var1 = value;


- Increment and decrement var1++; var1--; …
- Method (function) invocation sum(); or divide(8,2);
- Object creation Math m = new Maths();

Declaration Statements: also, variable declarations act as one single unit of execution and terminate
with a semicolon. Therefore, they are considered as statements.

E.g. Int age; float area; ……..

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


- Looping statements
- Branching statements

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.

- Simple if statement if(condition){ block of code }


- If else statement if(condition){ block of code }else{ }
- If else if statement if( condition){ block of code }else if(condition){ block of code }else
if(condition){ block of code }else{ block of code }
- Switch statement switch(argument){
case first: block of code break;

case second: block of code break; …..

default: block of code }


Looping statement: It is a type of statement that enables us to form section of a program that execute
specific block of code at least more than once. Blows are types of loops in java:

- for loop: for(initialization; condition; increment/decrement){


Block of code
}
- while loop: while(condition){
block of code
}
- do while loop: do{
block of code

}while(condition);

- for loop to parse through an array variable:


E.g. String[] people = {“solomon”,”abiy”,”moges”};
for(String person:people){
System.out.println(person);
}
Solomon abiy moges will be displayed.
Int numbers = {3,4,5};
For(int num:numbers){
System.out.println(num);
}
3 4 5 will be displayed.
It is a kind of for loop that enables us to parse through an array elements with ease.

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

Classes, Objects and Methods


1. Class
It is a blue print or a template used to create objects. In Java individual classes are stored in their own
.java file. In java, similar classes are organized in a folder called package. Therefore, a class .java file must
include a package name before defining the class. A class definition has the following members:

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

The syntax for declaring a class is:

Access-specifier class identifier{


Members
}
public class Geometry{
Members
}

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.

We can classify fields in to two:

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

E.g. public class Wheel{


public static int number = 10; //static variable
}
System.out.println(Wheel.number); this displays 10

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.

E.g. public class Wheel{


int number = 10; //static variable
}

Wheel w1 = new Wheel(); // the first instance/object


Wheel w2 = new Wheel(); //the second instance/object

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.

public static final int NUMBER; //static/class final fields


public final int NUMBER; // instance final fields

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.

- Public fields can be accessed anywhere in our programs


- Protected fields can only be used inside the derived classes of that class.
- Default fields can only be used in the classes that are within the same package.
- Private fields can only be used within that class.

E.g. public static int number; //public type of visibility


int number; //since no access specifier is given its visibility will be default

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.

E.g. public class Geometry{


public final int PI = 3.14;

public function int add(int a, int b){


return a+b;
}
}

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.

What happens when we use assignment operator on two variables.

Geometry g1 = new Geometry();


Geometry g2 = g1; // here what happens is both g1 and g2 start to refer to the same object

Geometry g3 = new Geometry();


Geometry g4= new Geometry();
g3 = g4; // before this statement both g3 and g4 where holding different objects reference.
However, after this statement they both start to refer the same object that g4 was referring

g3 = null; // after this statement g3 will be referring to no objects

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:

public static void main(String[] args){

A general format to create a method is:

Access-specifier return type name (parameters) {


block of code;
}

Access specifier: it can be public, protected, default and private.

- Public methods can be accessed anywhere in our programs


- Protected methods can only be used inside the derived classes from that classes.
- Default methods can only be used in the classes that are within the same package.
- Private methods can only be used within that class.

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 increment(){ // a function definition with no parameter

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

public class circle{


private int radius; //a private instance variable
public int getRadius(){ // a getter function with an int return type
return radius;
}

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 class circle{


private int radius; //a private instance variable
public int getRadius(){
return radius;
}

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.

E.g. Access-specifier static return-type name(parameter){

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

- Must match the class name


- Cannot have a return type
- Can be defined with a different type and number of parameters.
- A class can be defined with multiple constructors as long as they have different signature (you
can find a detail about a method signature in the topic that discuss overloading).

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”);

Java Garbage Collection


Another important thing to consider while developing a robust application software is keeping our code
efficient regarding usage of system resources such as temporary storage capacity, processing power and
soon. One of the multiple ways to do that is, to prevent the system memory from being stuffed with
objects that are no longer used by the program. Other programming languages like c++, dynamically
allocated objects must be manually released from the memory by a code specifically written to remove
them. In such cases, a delete operator is used on the pointer that is pointing to these objects. However,
Java handles the deallocation of unused objects for you automatically. The technique that accomplishes
this task is called Garbage Collection.

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.

void gbExample(){ //definition of a method with one object created in it


Maths m = new Maths();

gbExample(); // a statement for calling the above method. After the execution of the
method the object created will become unreachable.

2. Reassigning the reference variable: when reference variable of an object is reassigned to


reference id of another object, it becomes unreachable and becomes legible for garbage
collection.

Maths m = new Maths(); //creation of the first object


Maths m1 = new Maths(); //creation of the second object
m = m1; //after this code, the first object becomes 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.

Maths m = new Maths(); //creation of an object.

m = null; // after this the above object is no longer reachable.

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.

It is a method that is found in java.lang.Object class. Therefore, whenever we want something to be


done before object destruction, we should override (will be discussed below) the method in the class we
want it to be used. Finalize method has no parameter and return type.

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.

E.g Multilevel inheritance

class GrandFather{
protected String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

class Father extends GrandFather{


String profession;
public void setProfession(String profession){
this.profession = profession;
}
public String getProfession (){
return this.profession;
}

class Child extends Father{


String hobby;
public void setHobby(String hobby){
this. hobby = hobby;
}
public String getHobby (){
return this.hobby;
}

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{

2. Hierarchical inheritance: multiple child inherits from one base class.


class 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.

super() this is a parent class constructor

super.member 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.

N/B a method return type cannot be used as a method signature.

E.g.

1 public int add(int a, int b){


return a+b;

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;
}
}

class Child extends Parent1{

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.

class Child extends Parent1{


@overriden //this statement checks the below code if it overrides any method from parent
class public int add(int a, int b){ // this method overrides method #2 from the Parent1 class
return a+b+1;
}
}

Arrays, Character and Strings


Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value. Arrays are an important aspect of any programming language and java is no exception. An
array is a set of variables that is referenced by using a single variable name combined with an index
number. Each item of an array is called an element.

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.

Declaring an array of certain type:

Syntax type name[] = new type[size]; or type[] name =new type[size];


Array of primitive type
Integer type int[] numbers = new int[6]; // integer array with 6 indexes
Floaty type float[] numbers=new float[4]; // float array with 4 indexes

Array of class type


class Math{
int number;

Math[] m = new Math[3]; // this create an array of class math with 3 index

Array declaration has two steps:

1. The first step is creating a reference variable that refers to the array elements.

e.g. int name[]; //this statement creates the reference variable


or int[] name;

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.

e.g. name = new int[10]; //this creates 10 array elements

In order to get the size of an array at runtime you can call length property using the array name.

e.g. int test = new test[10];


System.out.println(name.length); //this statement displays 10

Accessing the array elements


To access an array element we use the variable name, a square bracket and the index. If it is a class type
we can call on elements of the class from it.

e.g.

public class Circle{


int radius = 10;
public int getRadius(){
return this.radius;
}
}

int[] x = new int[4];


Circle[] c = new Circle[3];
x[0] = 13; //this statement stores 13 on 0 index
System.out.println(c[1].getRadius()); // this will raise error so you
should create an object and set assign the reference to c[0] first as shown in the following code
c[1] = new Circle(); //this statement creates a Circle object and assigns the reference to 1 index
System.out.println(c[1].getRadius()); //this will display 10

Initializing Array Elements


Java has a short hand way to create an array by initializing its elements. It also determines its size from
the number of values used to initialize it.

E.g. int[] prime = {1,3,5,7}; or int[] prime = new int[]{1,3,5,7};


//the above statement displays an array of length 4
String[] days = {“Monday”,”Tuesday”};
days[1] = “ Wednesday ”; //this statement replaces “Tuesday” with
“Wednesday” Circle[] c = {new Circle(), new Circle(), new Circle()};
System.out.println(prime[2]); //this code displays 5

Parsing Through an Array Elements


The common way to parse through an array elements is using a loop. In fact, for loops were invented
specifically to deal with arrays.

Using regular for loop


Use the length property of the array to limit the max for loop iteration.

char[] letters = {‘a’,’c’,’h’,’z’};


for(int i = 0;i<letters.length;i++){
System.out.println(letters[i]);
}

Using enhance for loop


for(char let:letters){
System.out.println(let);
}

Using an Array with Methods


It is possible to write methods that accept arrays as parameters or/and as return values. In this case, you
just use an empty set of brackets to indicate that the parameter type or return type is an array.

E.g.

A method that returns a String array


String[] getName(){
String[] a = new String[3];
return a;
}
A method that receives an integer array
parameter void setIntegers(int[] a){

}
A method with array
parameter and array return type int[]
getName(int[] c){
return c;
}

Two Dimensional Arrays


The elements of an array can be of any type, including another array. This is called a two dimensional
array or you can call it an array of arrays. Two dimensional arrays are often used to track data in a
column row format.

Creating a two dimensional array


The syntax is type[][] name = new type[row size][column size];

Two dimensional arrays with a double data type


double[][] table = new double[3][4]; // this creates a double type two dimensional array with 3 rows and 4 columns

0 1 2 3
0
1
2

Initializing a two-dimensional arrays


1. Initializing at declaration
int[][] intTable = {{1,2},{3,4},{10,7}};

0 1
0 1 2
1 3 4
2 1 7
0

String[][] days = {{“mon”,”tue”,”fri”}, {“sat”,”sun”,”wed”}};

0 1 2
0 m t fr
o u i
n e
1 sa s w
t u e
n d

2. Initialization after declaration

With literal values


days[0][2] = “thu”; // this statement replaces “fri” with “thu”
with a user input
Scanner sc = new Scanner(System.in);
days[0][1] = sc.next(); //this replaces “tue” with a user input from keyboard

Accessing Two-Dimensional Array Elements


To access the two dimensional array elements we use the variable name two square brackets and the
row index and column index respectively.

String[][] days = {{“mon”,”tue”,”fri”}, {“sat”,”sun”,”wed”}};

0 1 2
0 mon tue fri
1 sat sun wed
For instance, to display string “wed” from the above days array

System.out.println(days[1][2]); //this code displays wed

Parsing through an array elements


int[][] intTable = {{1,2},{3,4},{10,7}};

0 1
0 1 2
1 3 4
2 10 7

1. Using regular for loop

for(int i=0;i<intTable.length;i++){
for(int j=0;j<intTable[i].length;j++){
System.out.println(intTable[i][j]);
}
}

2. Using enhanced for loop

for(int [] it:intTable){
for(int i:it){
System.out.println(i);
}
}

Each of the above two codes display the result as follows:

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

//this creates a variable ‘letter’ and stores ‘a’ in it


char letter = ‘a’;
char letter = “a”; //this raises an error because of the double quotation
char letter = 97; // since 97 is ascii representation of ‘a’ it stores ‘a’ on the
variable letter please refer to ascii number representation
int x = ‘a’; //this statement stores 97 on variable ‘x’

After Declaration

char letter;
letter = ‘a’;

From a user input

Scanner sc = new Scanner(System.in);


letter = sc.next().charAt(0);

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

Parsing Through a char Array


Using a regular for loop
for(int i=0;i<letters.length;i++){
System.out.println(letters[i]);
}

Using enhanced for loop

for(char lt: letters){


System.out.println(lt);
}

Conversion between String and char Array


String to char array
String example = “abx”;
char[] ex = example.toCharArray();
Char array to String
char[] ex = {‘j’,’l’,’n’};
String ex2 = new String(ex);

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’

Please read about methods of class String

equals(), equalsIgnoreCase(), substring()….

You might also like