0% found this document useful (0 votes)
3 views124 pages

Programming With Java

The document provides an overview of computer programming and the fundamentals of the Java programming language, discussing the types of programming languages, including high-level and low-level languages. It explains the differences between procedural and object-oriented languages, as well as the role of language translators like compilers and interpreters. The text emphasizes the importance of programming languages in facilitating effective communication between humans and computers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views124 pages

Programming With Java

The document provides an overview of computer programming and the fundamentals of the Java programming language, discussing the types of programming languages, including high-level and low-level languages. It explains the differences between procedural and object-oriented languages, as well as the role of language translators like compilers and interpreters. The text emphasizes the importance of programming languages in facilitating effective communication between humans and computers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Fundamentals of Java Programming language 1

Fundamentals of
Programming with Java

1
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER ONE

OVERVIEW OF COMPUTER PROGRAM

1.1 INTRODUCTION TO PROGRAMMING


Generally, computer programming is the process of writing, testing, debugging, and maintaining the
source code and documentation of computer programs. A programming language is a notational
system for describing computation in machine-readable and human-readable form. It is really a set of
tools that allow us to program at a much higher level than the 0’s and 1’s that exist at the lowest levels
of the computer. The purpose of programming is to invoke the desired behaviour from the machine.
However, there are three levels of languages available to program a microprocessor: Machine
Languages, Assembly Languages, and High-level Languages. Machine Language is only programming
language that any computer can actually understand and execute: its own native binary machine code.
Machine language is the lowest possible level of language in which it is possible to write a computer

2
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
program. A low-level language corresponds closely to machine code, so that a single low-level
language instruction translates to a single machine-language instruction. Machine languages and
assembly languages are sometime known as low level languages, because they are both close to the
architecture of the computer which support them.

High-Level Languages use English words and familiar symbols to specify operations, so easiest for
humans to use. It is a problem oriented language. It is a convenient and simple means of describing the
information structures and sequences of actions required to perform a particular task. Examples are
FORTRAN, Basic, COBOL, Pascal, Ada, C, C++, Python, Java etc. They may be run on any computer
that has a translation program such as a compiler or, an interpreter that translates a program in a particular
high-level language into the machine language of a particular computer. High-level language programs
are portable since they are independent of the architecture of any particular machine.

3
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
However, program in high level language are shorter than equivalent in low level languages. A single
high-level instruction may be translated into several machine language instructions. In summary, high-
level languages are easiest to use, portable and are shorter than equivalent ML or AL. High-level
languages permit faster development of large programs. The final program as executed by the
computer is not as efficient, but the savings in programmer time generally far outweigh the
inefficiencies of the finished product. Finally, the objectives of a high level language are to provide a
convenient means of expressing solution to a problem, efficiency (HLL program must be able to be
translated into machine code fairly quickly and run efficiently), simplicity and readability. The
defining characteristics of high level language are problem-orientation and machine independence.
1.2 SPOKEN LANGUAGES AND PROGRAMMING LANGUAGE
Spoken languages are spoken and written by human beings for the purpose of communicating with
themselves. Programming language are processed by the computers and serves as communication
between two computers or between human being and computer. The similarities between them are
given in the table below:
4
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Characteristics Spoken Language Programming Language

Vocabulary Consist of alphabets. Consist of alphabets.

Structure Consists of words, sentences and Consists of keywords, expressions and


phrases. statement.

Formation Has syntax rules for making up Has syntax rules for making up
sentences. statements.

Interpretation May require an interpreter before it be May require a translator before it can be
understood by human being. understood by a computer.

Communication Written and spoken by human beings Written and processed by computer for
for the purpose of communicating the purpose of communicating data
ideas. between the human being and the
computer.
5
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

However, the following are the reasons why spoken language cannot be used to program computers:
i. They are vague (not clear) &/or ambiguous in terms of their exact meaning.
ii. There are many vocabularies in NL. Computer has no common sense so it must have strictly
controlled vocabularies.
iii. The need to economize the computer memory, time and complexity.

1.3 PROGRAMMING LANGUAGES


A program is a sequence of instructions to perform some specific task using a computer. Programming
is the act of writing, testing, debugging and maintaining the source code and documentation of
computer program. Programming is the process of writing a program. Programming Language can be
defined as a notational system for communication with computers. The role of programming language
is that of allowing programmers/developers to easily express abstract ideas in a language that a

6
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
computer machine can understand. The purpose of programming language is to have effective
communication with programmable machines. The reasons why there are many programming
languages are:
i. The need to solve the shortcomings of the existing programming languages.
ii. The need to have a specialized program for a specific problem domain.

1.3.1 Types of Programming Language


A programming language is typically divided into two types namely: High-level and Low-level
languages.
Procedural
Language
High-
Level Object-Oriented
Language
Assembly Language
7
Low-
Level Machine Language
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Figure1: Types of programming languages

1.3.1 Procedural Language


This is a program written as sequence of instructions e.g. My morning activities

Start( )
Step 1: I wake up
Step 2: Brush my teeth
Step 3: Open the fridge
Step 4: Take milk
Step 5: Warm in the microwave

8
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1.3.2 Object-Oriented Language
Object-oriented language (OOL) is a high-level computer programming language that implements
objects and their associated procedures within the programming context to create software programs.
e.g. My morning activities

Start ( )

Object Me ( ) Object Microwave ( ) Object Fridge ( )


(( )
Wake up ( ) Warm ( ) Open ( )
; Brush ( ) Bake ( ) Close ( )

Figure 2: Example of Object-Oriented language


9
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Table 1: Difference between procedural and Object-oriented Language

Procedural language Object-Oriented Language


It follows Top-down approach It follows Bottom-up approach
Codes cannot be reuse Codes are reusable
Data not secure Data is secure
Codes are interdependent Codes are modular

1.3.3 MACHINE LANGUAGE


This language directly run on the computer central processing unit. Its contains series of bits like 0s
and 1s. Machine language is tedious, error prone, and not portable.

1.3.4 ASSEMBLY LANGUAGE


This is a low-level programming language designed for a specific type of processor.

10
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1.4 LANGUAGE TRANSLATORS
Any program written in a high-level language is known as source code. However, computers cannot
understand source code. Before it can be run, source code must first be translated into a form which a
computer understands. A translator is a program that converts source code into machine code.
Generally, there are three types of translator: compilers, interpreters, and assemblers.

1.4.1 COMPILERS
A compiler takes the source code as a whole and translates it into machine code all in one go. Once
converted, the object code can be run unassisted at any time. This process is called compilation.
Compilers have several advantages:

1. Compiled programs run quickly, since they have already been translated.

11
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
2. A compiled program can be supplied as an executable file. An executable file is a file that is
ready to run. Since an executable file cannot be easily modified, programmers prefer to supply
executable rather than source code.
3. Compilers optimise code. Optimised code can run quicker and take up less memory space.

Compilers also have disadvantages:

1. The source code must be re-compiled every time the programmer changes the program.
2. Source code compiled on one platform will not run on another - the machine code is specific to
the processor's architecture.

12
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1.4.2 INTERPRETERS
An interpreter translates source code into machine code one instruction at a time. It is similar to a
human translator translating what a person says into another language, sentence by sentence, as they
speak. The resulting machine code is then executed immediately. The process is called interpretation.

Interpreters have several advantages:


1. Instructions are executed as soon as they are translated.
2. Errors can be quickly spotted - once an error is found, the program stops running and the user is
notified at which part of the program the interpretation has failed. This makes interpreters
extremely useful when developing programs.

Interpreters also have several disadvantages:

13
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1. Interpreted programs run slowly as the processor has to wait for each instruction to be translated
before it can be executed.
2. Additionally, the program has to be translated every time it is run.
3. Interpreters do not produce an executable file that can be distributed. As a result, the source code
program has to be supplied, and this could be modified without permission.
4. Interpreters do not optimise code - the translated code is executed as it is.

1.4.3 ASSEMBLERS
The purpose of an assembler is to translate assembly language into machine code. Whereas compilers
and interpreters generate many machine code instructions for each high-level instruction, assemblers
create one machine code instruction for each assembly instruction.

1.5 BASIC TERMS IN PROGRAMMING LANGUAGE


14
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
i. Lexicons: Is a list of valid words in a language. (identifiers, operators, reserved words,
constants etc…)
ii. Syntax: They are the rules that govern the combination of valid words of a language in an
appropriate order to form an acceptable or valid sentence. Issues involve are formal description
(BNF), character sets, parsing, lexical analysis, etc..
iii. Semantic: Is the study of the meaning of words, phrase, and sentences in a language. It focuses
on what the words conventionally mean, rather than what a speaker/writer wants the words to
mean on a particular occasion. (e.g. Scopes, coercion, data type implementation, binding, etc.)
iv. Pragmatics: It refers to the study of the meaning a speaker/writer intends to convey and not just
what the word literally means. Pragmatic has to do with origin, uses, effects of the language,
programming methodologies such as oo programming, data abstraction, software engineering
etc.

15
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
v. Translation Time: This referred to time a program in non-machine language is being
translated to machine language equivalent. (Assembly time, compile time, link time etc.)
vi. Execution Time: This is the time in which a statement of a program are being carried out by the
computer.

Exercise 1
1. Explain the importance of both hardware and software in a computer system.
2. Give an advantage of using assembly language to write programs.
3. Give two disadvantages of using assembly language to write programs.
4. Give and explain two similarities and one difference between an assembler and a compiler.
5. What is JVM short for?
6. What is bytecode and how is bytecode different from source code?

16
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
7. Give and explain one advantage and one disadvantage of the way Java code is translated into
machine code compared to other languages (e.g. C++).
8. Explain the difference between a Java compiler and the Java JVM

17
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER TWO

JAVA PROGRAM FEATURES

2.1 INTRODUCTION TO JAVA PROGRAM


Java is an object-oriented programming language developed by James Gosling at Sun Microsystem in
the early 1990s. Java is the most popular language in today’s world billion of devices running on a
Java platform, Java touched every field of development of software, java’s features make it the most
powerful language in the current market of software development. It is the object-oriented
language it supports all the features of object-oriented programming language, It is the most
secure language in the current world due to that all the banking application development happens in
java only, it is very easy to learn like C, C++ language.

2.2 FEATURES OF JAVA PROGRAMMING LANGUAGE

18
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1. Simple: Java was developed keeping in mind the complexities in other programming languages
like C or C++. It has made the developer’s life comparatively easy as java does not make use of
pointers and has a build-in memory management system. Also, java can be easily understood
without prior knowledge to programming.
2. Portable: Java source code can be developed and compiled on one machine and can be made to
run on the same or any other operating system. Therefore a java program can be easily ported on
any other machine thus providing portability.
3. Architectural-Neutral: Java program never communicate with the platform directly. Changes
and upgrades in operating systems, processors, and system resources will not force any changes in
java program.
4. Platform Independent: If we write java program once, it can be run on any platform. Java
program follows Write Once Run Anywhere WORA principle. The java program can be migrated
from one machine to another without changing the source program.
19
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
5. Secure: In terms of security java is operated on byte code which is not readable in nature. It runs
source code inside a secured sandbox and does not allow any external intervention. Therefore it
allows developers to build tamper resilient and virus free applications thus providing high
security.
6. Multi-threading: Java supports creating multiple threads for execution thus providing high
performance. Also, it supports the synchronization mechanism to maintain synchronization
between different threads.
7. Robust: Java is strongly typed language. Java provides Garbage Collector GC for automatic
memory management. Hence, there is no chance of memory related problems. The GC destroy
any unused object automatically.
8. Distributed: Java supports developing distributed applications. It provides features like Remote
Method Invocation through which a program can communicate with another program present in
the remote machines through the network and generates the desired output.
20
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
9. Interpreted: The code is converted into byte code which in turn is interpreted by java run time
environment.
10. High-performance: Java is relatively faster than traditional interpreted languages. Since byte
code is close to native code. It has Just in time compiler through which high performance is
achieved.
11. Dynamic: Applications developed using java can adapt them to changing execution environment.
This is because this programming language has features like dynamic memory allocation in which
the amount of memory allocated changes according to the environment which in turn provides
high performance.
12. Object-oriented: Object-oriented programming (OOP) is a computer programming model that
organizes software design around data, or objects, rather than functions and logic. An object can
be defined as a data field that has unique attributes and behavior. This approach to programming is
well-suited for programs that are large, complex and actively updated or maintained. In java,
21
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
everything is treated as an object and all the operations involved in application development are
completed using these objects. Object-oriented programming is based on the following principles:

a. Encapsulation: The implementation and state of each object are privately held inside a defined
boundary, or class. Other objects do not have access to this class or the authority to make
changes but are only able to call a list of public functions, or methods. This characteristic
of data hiding provides greater program security and avoids unintended data corruption.
b. Abstraction: Objects only reveal internal mechanisms that are relevant for the use of other
objects, hiding any unnecessary implementation code. This concept helps developers more
easily make changes and additions over time.
c. Inheritance: Relationships and subclasses between objects can be assigned, allowing
developers to reuse a common logic while still maintaining a unique hierarchy. This property
of OOP forces a more thorough data analysis, reduces development time and ensures a higher
level of accuracy.
22
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
d. Polymorphism: Objects can take on more than one form depending on the context. The
program will determine which meaning or usage is necessary for each execution of that object,
cutting down the need to duplicate code.
2.3 DIFFERENT AREAS OF APPLICATION OF JAVA PROGRAM
1. Mobile Applications: Java is considered as the official programming language for mobile app
development. It is compatible with software such as Android Studio and Kotlin. Now you
must be wondering why only Java? The reason is that it can run on Java Virtual Machine (JVM),
whereas Android uses DVK (Dalvik Virtual Machine) to execute class files. These files are further
bundled as Android application Package(APK). With Java and its OOPs principles, it provides
better security and ease of simplicity with Android.
2. Cloud-Based Applications: Cloud computing means on-demand delivery of IT resources via the
internet with pay-as-you-go pricing. It provides a solution for IT infrastructure at a low cost. Java
provides you with features that can help you build applications meaning that it can be used in the
23
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
SaaS, IaaS and PaaS development. It can serve the companies to build their applications remotely or
help companies share data with others, whatever the requirement.
3. Big Data technologies: Java is the reason why the leading Big Data technologies like Hadoop have
become a reality and also the most powerful programming languages like Scala are existing. It is
crystal clear that Java is the backbone when it comes to developing Big Data using Java.
4. Business Applications: Java EE platform is designed to help developers create large-scale, multi-
tiered, scalable, reliable, and secure network applications. These applications are designed to solve
the problems encountered by large enterprises. The features that make enterprise applications
powerful, like security and reliability, often make these applications complex. The Java EE platform
reduces the complexity of enterprise application development by providing a development model,
API, and runtime environment that allow developers to concentrate on functionality.
5. Distributed Applications: Distributed applications have several common requirements that arise
specifically because of their distributed nature and of the dynamic nature of the system and
24
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
platforms they operate on. Java offers options to realize these applications. The Jini (Java
Intelligent Networking Infrastructure) represents an infrastructure to provide, register, and find
distributed services based on its specification. One integral part of Jini is JavaSpaces, a mechanism
that supports distribution, persistence, and migration of objects in a network.
6. Web-based Applications: Java is also used to develop web applications. It provides a vast support
for web applications through Servlets, Struts or JSPs. With the help of these technologies, you can
develop any kind of web application that you require. The easy coding and high security offered by
this programming language allow the development of a large number of applications for health,
social security, education, and insurance.
7. Enterprise Applications: Java is the first choice of many software developers for writing
applications and Java Enterprise Edition (Java EE) is a very popular platform that provides API and
runtime environment for scripting. It also includes network applications and web-services. JavaEE

25
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
is also considered as the backbone for a variety of banking applications which have Java running on
the UI to back server end.
8. Gaming Applications: Java has the support of the open-source most powerful 3D-Engine, the
jMonkeyEngine that has the unparalleled capability when it comes to the designing of 3D games.
However, it does cause an occasional latency issue for games as garbage collection cycles can cause
noticeable pauses. This issue will be solved in the newer versions of JVMs.

2.4 JAVA COMPILER


JDK
A Java compiler is a compiler for the java programming language. The figure below gives the
architectural operations of java compiler.
Compiler JRE

.Class file
(byte code) 26 JVM

Output
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Figure 3: Java Compiler Operational Architecture

2.5 JAVA DEVELOPMENT KIT (JDK)


The Java Development Kit (JDK) is helpful to write programs in Java. It is also known as the Java
Platform StandardEdition (Java SE). JDK is a development kit containing JRE and the development
tools (debugger and compiler) needed for getting a program output in Java. Simply put, JRE happens

27
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
to be a subset of JDK, that is, it is included in JDK. Therefore, we will need to install JDK to write
and run programs.

Exercise 2
1. List three features of every object-oriented programming language.
2. Explain, in your own words, what you think the meaning is of each of the three features listed in
part (1).
3. Why Java is platform independent?

CHAPTER THREE

BASIC JAVA VARIABLES, DATA TYPES AND SYNTAX

28
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
3.1 JAVA VARIABLES
Variables are the basic units used to store any information in Java. The variable name is the name
allotted for these units. A Java code may need information in the form of a numeric or a string value. A
variable cannot be used until and unless it is declared, and the data type we assign during declaration
defines the type of the value it can hold.

3.2 TYPES OF VARIABLES

There are 3 types of variables in Java: Local Variable, Instance Variable, and Static Variable

a. Local Variable: A local variable is a variable declared inside a method body, block or
constructor. It means variable is only accessible inside the method, block or constructor that
declared it.
Example 1
29
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
for(int i=0;i<=5;i++){……}
In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.
Example 2
if(x > 100)
{
String test = "Edureka";}

b. Instance Variable: Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another. An instance
variable can be declared public (visible to any class) or private or default (no modifier). When
we do not want our variable’s value to be changed out-side our class we should declare them
private. public variables can be accessed and changed from outside of the class.

Example 2
30
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
class Marks {
// a, b, c are instance variables
// a, b, c variables are being declared inside a class and not
function
int a;
int b;
int c;
}

c. Static Variable: These are variables declared inside a particular method or block or
constructor which they are in. Their variable value which is stored during declaration is valid
only within the scope of that method and is lost when the method is exited.
Example 3

31
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Public class PatientDetails{
public void Patient()
{
// local variable num
//local variable name
int num = 1200;
string name = "Harish";

3.23 JAVA DATA TYPES


Data type is a keyword, it describes the type of data. Data types are having different sizes and values
and the values are stored in a variable. Java data types are broadly categorized into Primitive data types
and Non primitive data types. Primitive data types are char, byte, short, int, long, float, double,
boolean. Non primitive data type is String. Before we begin looking at the types, there's some rules we
32
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
have to follow when picking variable names. In general, you can name your variables whatever you
want, as long as they follow these simple guidelines:
1. Java variables cannot start with a number or special symbol
2. Java variables cannot be a keyword already

i. Char: A char variable is a variable that holds a single character. A character is a single letter,
number, or symbol. For example, 'A' is a character, so is '1' and '&'. Those are all characters.
Syntax: char variableName = value;

Example: Char c = ‘g’ ;

ii. Boolean: A Boolean is one of the special Java variables that stores either true or false.
Example
Syntax: Boolean varibaleName = value;
Example: Boolean X = true;

33
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
iii. Double: A double variable is one that holds a decimal number. For example:
Syntax: double varibaleName = value;
Example: Double number = 4.69;
Double number = 4;
iv. Int: An int variable holds an integer.
Syntax: int varibaleName = value;
Example: int age = 30;
Unlike double, an int can ONLY hold integers. You cannot store a decimal inside of an int. You can
store negative numbers in both ints and doubles however.
The examples below are both valid.
Int num = -2; and double num = - 4.6;
v. String: String is more complicated because it's not one of the basic Java variables, but creating
a String variable is no different than the basic types.
34
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Syntax: String variableName = value;
Example: String name = “sadiq”;

A string variable must have quotes around the value in order for it to be a string. Strings can be
made up of one letter, one word, whole sentences, or even entire paragraphs. You can also have
empty strings.

String name = “ ”;
That string is empty because there is nothing inside of the quotation marks, not even a space.
vi. Long: The long is one of the primitive data types in Java, among the eight available data types.
This is a numeric data type like byte, int etc.
Syntax: long varibaleName = value;
Example: long Population = 1000000000;

35
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

3.3 JAVA PROGRAMMING LANGUAGE SYNTAX


The syntax of Java refers to the set of rules defining how a Java program is written and interpreted.
Every language has its individual [Link] proper knowledge of syntax, it would be difficult to
generate desired output from a programming language. Syntax are also referred to as the language of
the computer.

3.3.1 Java keywords


In the Java programming language, a Keyword is any one of 51 reserved words that have a predefined
meaning in the language; because of this, programmers cannot use keywords as name
for variables, methods, classes, or as any other identifier. Most integrated development
environments for Java use syntax highlighting to display keywords in a different colour for easy
identification.
36
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Examples of keywords are: Boolean, byte, integer, case, class etc.

3.3.2 Java Comment


The Java comments are the statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code. There are three types of
comments in java: Single Line Comment, Multi-Line Comment, and Documentation Comment.

1. Java Single Line Comment


The single line comment is used to comment only one line.

Syntax: //This is single line comment

Example:
37
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
[Link](i);
}

2. Java Multi-Line Comment


The multi-line comment is used to comment multiple lines of code.
Syntax: /*
This
is

38
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
multi line
comment
*/
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}

39
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
3. Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.
Syntax: /**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and sub
traction of given 2 numbers.*/
public class Calculator {
40
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}

3.3.3 Java Class Header


Java is an object-oriented programming language. Everything in Java is associated with classes and
objects, along with its attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and brake. A Class is like an
object constructor, or a "blueprint" for creating objects. A class should always start with an uppercase
first letter. Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning. A class can
be broken down into two things:
41
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
1. The first piece is a class-header which consists of the keyword "class" and the name you give to
the class.
2. The second piece is the body. It consists of a pair of open/close brackets.

Syntax for class creation : Public Class <identifier>


{
<member>
...
}
Example
Create a class named "MyClass" with a variable x
public class MyClass {
int x = 5;}
42
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Creating Object
In Java, an object is created from a class. We have already created the class named MyClass, so now
we can use this to create objects. To create an object of MyClass, specify the class name, followed by
the object name, and use the keyword new.
Example
Create an object called "myObj" and print the value of x

public class MyClass {


int x = 5;
public static void main(String[] args) {
MyClass myObj = new MyClass();
[Link](myObj.x);

43
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
}
}
multiple objects of one class can also be created as shown below

public class MyClass {


int x = 5;
public static void main(String[] args) {
MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
[Link](myObj1.x);
[Link](myObj2.x);
}
}

44
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

45
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
3.3.4 Java Method
Java Method is a collection of statements to process some specific task and return the response to the
caller. Methods allow us to write reusable code and dividing our program into several small units of
work. Java Method promotes clean and more readable code.
Example: write a program to add two numbers and return the sum. add(num1, num2)
Private Static int add(num1,num2){
int sum = num1 + num2
return sum;}

[Link] Java Main Method


When we execute a Java application, we use the "java" command which runs the Java Virtual Machine
(JVM) and we specify a class file for it to execute. But, how does the JVM know where to start

46
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
executing? It starts with a special method you identify as the "main" method of your
application. This convention is a tradition Java inherited from the "C" programming language.
Syntax for java method: Public static void main ( string [ ] args){
<statement>
...
}
The components for creating java main method are: Access modifier, keywords, return type, method
name,
Access modifier
An access modifier specifies how any class can access a given class and its fields, constructors and
methods within, and different packages. Java access modifiers: Private, Public, Protected, and
Default. The following table summarizes how we can apply Java access modifiers to the program:
Table below shows the level of access of each access modifier
47
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Modifiers Class Packages Sub-Class World


Private Y N N N
Public Y Y Y Y
Protected Y Y Y N
Default Y Y N N

48
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Static
You can make a method static by using the keyword static. We should call the main() method without
creating an object. Static methods are the method which invokes without creating the objects, so we
do not need any object to call the main() method.

Void
In Java, every method has the return type. Void keyword acknowledges the compiler that main()
method does not return any value.

main( )
It is a default signature which is predefined in the JVM. It is called by JVM to execute a program line
by line and end the execution after completion of this method. We can also overload the main()
method.
49
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

String args[ ]
The main() method also accepts some data from the user. It accepts a group of strings, which is called
a string array. It is used to hold the command line arguments in the form of string values.

Exercise 3

1. In two statements, declare a variable named numBeads and assign it the value 5.
2. In one statement, declare a variable named numBeads and assign it the value 5.
3. Determine the appropriate data type for each of the following values:
i. the number of basketballs in a department store.
ii. the price of a basketball.
iii. the number of players on a basketball team.
iv. the average age of the players on a basketball team.
50
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
v. whether a basketball player has received a jersey or not.
vi. the first initial of a basketball player’s first name
4. What is the use of access modifiers in Java?
5. Explain the difference between the private and public access modifiers.

CHAPTER FOUR

JAVA INPUT AND OUTPUT

51
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
4.1 JAVA INPUT
Input is any information that is needed by your program to complete its execution. There are many
forms that program input may take. Some programs use graphical components like a popup dialog box
to accept and return the character string that is typed by the user. You are certainly familiar with
programs that are controlled simply by clicking the mouse in a specific area of the screen. Still other
programs, like word processing programs, get some of their input from a file that is stored on the
computer's floppy or hard disk drive. One of the strengths of Java is the huge libraries of code
available to you. This is code that has been written to do specific jobs. All you need to do is to
reference which library you want to use, and then call a method into action. One really useful class that
handles input from a user is called the Scanner class. The Scanner class can be found in
the [Link] library. To use the Scanner class, you need to reference it in your code. This is done with
the keyword import.
import [Link];
52
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

The import statement needs to go just above the Class statement:

import [Link];

Public Class <identifier> {


}
4.2 JAVA OUTPUT
Output is any information that the program must convey to the user. The information you see on your
computer screen is being output by one or more programs that are currently running on your
computer. When you decide to print a document, a program is told to send some output to the printer.
Any sound that your computer makes is because some program sent output to the speakers on your
computer.

53
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Figure 4: Java Input and Output Stream

Before exploring various input and output streams let us look at 3 standard or default streams that Java
has to provide which are also most common in use:

54
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

[Link]
This is the standard input stream that is used to read characters from the keyboard or any other
standard input device. Java Scanner class allows the user to take input from the console. It belongs
to [Link] package. It is used to read the input of primitive types like int, double, long, short, float,
and byte. It is the easiest way to read input in Java program.

55
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Syntax: Scanner sc=new Scanner([Link]);

The above statement creates a constructor of the Scanner class having [Link] as an argument. It
means it is going to read from the standard input stream of the program. The [Link] package should
be import while using Scanner class. It also converts the Bytes (from the input stream) into characters
using the platform's default charset.

Methods of Java Scanner Class


Java Scanner class provides the following methods to read different primitives types:
a. int nextInt(): It is used to read an integer value from the keyboard.
b. int nextFloat(): It is used to read a float value from the keyboard.
c. long nextLong(): It is used to read a long value from the keyboard.
56
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
d. String next(): It is used to read string value from the keyboard.

Example 1: Write a java code to a accept name


public class Main{
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("My name is " + name);
[Link]();
}
}
Output
57
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Enter your name: Mike

Example 2: write a java program to accept integer numbers and print the result
import [Link];
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter an integer: ");
int data1 = [Link]();
[Link]("Using nextInt(): " + data1);
[Link]();
}
}
58
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Output
Enter First Number: 6
[Link]
This is the standard output stream that is used to produce the result of a program on an output device
like the computer screen.
Here is a list of the various print functions that we use to output statements:
print( )
This method in Java is used to display a text on the console. This text is passed as the parameter to this
method in the form of String. This method prints the text on the console and the cursor remains at the
end of the text at the console. The next printing takes place from just here.

Syntax: [Link](parameter);
Example: write a java program to print first statement, second statement, and third statement.

59
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
public class Test
{
public static void main(String [ ] args)
{
[Link]("first statement");
[Link]("second statement");
[Link]("third statement");
}
}
Output

60
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

println( )
This method in Java is also used to display a text on the console. It prints the text on the console and
the cursor moves to the start of the next line at the console. The next printing takes place from the next
line.

Syntax: [Link](parameter);

61
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Example: write a java program to print first statement, second statement, and third statement.
public class Test
{
public static void main(String [ ] args)
{
[Link]("first statement");
[Link]("second statement");
[Link]("third statement");
}
}

Output

62
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

printf( )
This is the easiest of all methods as this is similar to printf in C. Note that [Link]() and
[Link]() take a single argument, but printf() may take multiple arguments. This is used to
format the output in Java.

Syntax: [Link](parameter);

Example below will output in a specific format

[Link]("'%5.2f'%n", 5.1473);

Here we define the width of our number as 5, and the length of the decimal part is two
63
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

Output
' 5.15'

64
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER FIVE

JAVA OPERATORS

5.1 OPERATORS
Operators are symbols that perform operations on variables and values. For example, + is an operator
used for addition, while * is also an operator used for [Link] in Java can be classified
into: Arithmetic Operators, Assignment Operators, Relational Operators, Logical Operators, Unary
Operators, and Conditional operators.

5.2 ARITHMETIC OPERATORS


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators.
Assume integer variable A holds 10 and variable B holds 20, then
Operator Description Example
+ (Addition) Adds values on either side of the A + B will give 30
65
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
operator.
Subtracts right-hand operand
- (Subtraction) A - B will give -10
from left-hand operand.
* Multiplies values on either side
A * B will give 200
(Multiplication) of the operator.
Divides left-hand operand by
/ (Division) B / A will give 2
right-hand operand.
Divides left-hand operand by
% (Modulus) right-hand operand and returns B % A will give 0
remainder.
Increases the value of operand
++ (Increment) B++ gives 21
by 1.
Decreases the value of operand
-- (Decrement) B-- gives 19
by 1.

Example 1: Arithmetic Operators

66
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
public class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator
[Link]("a + b = " + (a + b));

// subtraction operator
[Link]("a - b = " + (a - b));

// multiplication operator
67
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link]("a * b = " + (a * b));

// division operator
[Link]("a / b = " + (a / b));

// modulo operator
[Link]("a % b = " + (a % b));
}
}
Output
a + b = 17
a - b = 7
a * b = 60
68
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
a / b = 2
a % b = 2

5.3 ASSIGNMENT OPERATORS


Assignment operators are used in Java to assign values to variables. For example,

int age;
age = 5;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That
is, 5 is assigned to the variable age. some more assignment operators available in Java.

69
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Operator Example Equivalent to
= a = b; a = b;
+= a + = b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

Example
Public class Main {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
[Link]("var using =: " + var);
70
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

// assign value using =+


var += a;
[Link]("var using +=: " + var);

// assign value using =*


var *= a;
[Link]("var using *=: " + var);
}
}

Output
var using =: 4
var using +=: 8
var using *=: 32

5.4 RELATIONAL OPERATORS


Relational operators are used to check the relationship between two operands. For example,

71
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
// check is a is less than b
a < b;
Here, > operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples

Operator Description Example


Checks if the values of two operands are equal (A == B) is not
== (equal to)
or not, if yes then condition becomes true. true.
Checks if the values of two operands are equal
!= (not equal to) or not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater
(A > B) is not
> (greater than) than the value of right operand, if yes then
true.
condition becomes true.
< (less than) Checks if the value of left operand is less than (A < B) is true.
72
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
the value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is greater
>= (greater than (A >= B) is not
than or equal to the value of right operand, if
or equal to) true.
yes then condition becomes true.
Checks if the value of left operand is less than
<= (less than or
or equal to the value of right operand, if yes (A <= B) is true.
equal to)
then condition becomes true.

Example
Public class Main {
public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b
[Link]("a is " + a + " and b is " + b);

73
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
// == operator
[Link](a == b); // false

// != operator
[Link](a != b); // true

// > operator
[Link](a > b); // false

// < operator
[Link](a < b); // true

// >= operator
[Link](a >= b); // false

// <= operator
[Link](a <= b); // true
}
}
74
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

5.5 LOGICAL OPERATORS


A logical operator (sometimes called a “Boolean operator”) in Java programming is an operator that
returns a Boolean result that’s based on the Boolean result of one or two other expressions. Sometimes,
expressions that use logical operators are called “compound expressions” because the effect of the
logical operators is to let you combine two or more condition tests into a single expression.
Operator Example Meaning
true only if both
&& (Logical AND) expression1 && expression2 expression1 and
expression2 are true
true if either expression1 or
|| (Logical OR) expression1 || expression2
expression2 is true
true if expression is false
! (Logical NOT) !expression
and vice versa

Example
75
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
public class Main {
public static void main(String[] args) {

// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false

// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false

// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}

5.6 UNARY OPERATORS


76
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Unary operators are used with only one operand. For example, ++ is a unary operator that increases the
value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning
Unary plus: not necessary to use since numbers are positive
+
without using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrements operator: decrements value by 1
! Logical complement operator: inverts the value of a Boolean

Also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the
operand by 1, while -- decrease it by 1.

Example,:

int num = 5;
// increase num by 1
77
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
++num;

Here, the value of num gets increased to 6 from its initial value of 5.

5.7 CONDITIONAL OPERATORS


Conditional Operators in Java are also known as ternary operators. I’m pretty sure that you are well
aware of the concept of the if-else statement in Java. Well, conditional operators are simply a
condensed form of the if-else statement which also returns a value. To further simplify the concept, let
me discuss this topic in detail with you.
Rules of conditional operator
a. If the result of Boolean-condition is true, first expression will be executed and its value is
returned.
b. If the result of Boolean-condition is false, second expression will be executed and its value is
returned.

78
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
c. First expression and second expression must result in a value.

Example
Public class Example
{
Public static void main(string [ ] args)
{
79
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Int A = 10;
Int B = 20;
String result = A>B? “A is greater” : “B is greater”;
[Link](result);
}
}

Output

B is greater

Java Operator Precedence Table


ecedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement

80
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
9 < Relational less than Left to right
<= Relational less than or equal
81
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
> Relational greater than
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
1 = Assignment Right to left
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment

82
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
/= Division assignment
%= Modulus assignment

Larger number means higher precedence.

83
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER SIX

JAVA CONTROL STATEMENTS

6.1 CONTROL STATEMENTS


A control statement works as a determiner for deciding the next task of the other statements whether to
execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to
execute first between the two. In Java, the control statements are divided into three categories which
are selection statements, iteration statements, and jump statements.
6.2 Decision Making Statement
Decision making statements are statements which decides what to execute and when. They are similar
to decision making in real time. Control flow statements control the flow of a program’s execution.
Java decision making statements are: Simple if Statement, if…else Statement, Nested if statement,
if...else if…else statement, and Switch statement.

84
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Simple if Statement
Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of
code should be executed based on the condition.

Syntax:

if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or
false

Example:
public class ifTest
{
public static void main(String args[])
{
int x = 5;
85
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
if (x > 10)
[Link]("You won");
[Link]("Try Again");
}
}

Output:
Try Again
IF…Else Statement
In if…else statement, if condition is true then statements in if block will be executed but if it comes out
as false then else block will be executed.
Syntax: If (condition)
Statement 1
Else
Statement 2

Example
86
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

public class MyClass {


public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
}}

Output:
x is greater than y

Nested if statement

87
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
In the nested, if-else statement there are multiple if conditions and finally there is a print statement.
The following is the syntax:
Syntax: If (condition1)
If(condition2)
If (condition3)
Statement 1

Example

public class NetstedIfStatementExample {


public static void main(String[] args) {
int num = 50;
if (num < 100) {
[Link]("number is less than 100");
if (num == 50) {

88
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link]("number equal to 50");
if (num > 40) {
[Link]("number is greater than 40");
}
}
}
}
}

Output:
number is less than 100
number equal to 50
number is greater than 40
89
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

IF...Else IF…Else statement


if…else if statements will be used when we need to compare the value with more than 2 conditions.
They are executed from top to bottom approach. As soon as the code finds the matching condition, that
block will be executed. But if no condition is matching then the last else statement will be executed.

Syntax: if (condition2) {
Statemen 1; //if condition1 becomes true then this will be
executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will
be executed
}
.
.
else {

90
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Statement 3; //executed when no matching condition found
}

Example

public class Test {

public static void main(String args[]) {


int x = 30;

if( x == 10 ) {
[Link]("Value of X is 10");
}else if( x == 20 ) {
[Link]("Value of X is 20");
}else if( x == 30 ) {
[Link]("Value of X is 30");
}else {
[Link]("This is else statement");
}
91
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
}
}
Output
Value of X is 30
Switch statement
Java switch statement compares the value and executes one of the case blocks based on the condition.
It is same as if…else if ladder. Below are some points to consider while working with switch
statements:
a. case value must be of the same type as expression used in switch statement
b. case value must be a constant or literal. It doesn’t allow variables
c. case values should be unique. If it is duplicate, then program will give compile time error.

Syntax: switch(expression) {
case x:
// code block
92
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
break;
case y:
// code block
break;
default:
// code block}
Example
public class SwitchCaseDemo1
{
public static void main(String[] args)
{
int day = 5;
switch (day) {
case 1:

93
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
94
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid");
}
}
}

95
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Output
Friday

Looping Statements in Java


Looping statements are the statements which executes a block of code repeatedly until some condition
meet to the criteria. Loops can be considered as repeating if statements. Available loops in Java are:
While, Do…while, For, and For-Each Loop.
While Loop
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then
executes the body of loop. This is repeated until the condition becomes false. Condition in while loop
must be given as a Boolean expression. If int or string is used instead, compile will give the error.

Syntax: while (condition)


{
96
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Statement1;
}

Example
public class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10)
{
[Link](j);

97
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
j = j+2;
}
}
}

Output:
1
3
5
7
9

Do…while
98
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
The Java Do While loop will test the given condition at the end of the loop. So, Java Do While loop
executes the statements inside the code block at least once even if the given condition Fails. The While
Loop tests the condition before entering into the code block. If the condition is True, then only
statements inside the loop will be executed. Otherwise, statements will not execute at least once. There
are some situations where it is necessary to perform some operations (execute some statements) first,
and then check for the condition. In these cases, we can go for Java Do While loop.

Syntax: do {
statement 1;
statement 2;
………….
statement n;
} While (condition);
99
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Example
public class MyClass {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
}
}

Output

100
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
0
1
2
3
4
For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:

Syntax: for (statement 1; statement 2; statement 3) {


// code block to be executed}

Statement 1 is executed (one time) before the execution of the code block.

101
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

Example
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i);
}
}
}

102
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true,
the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Output
0
1
2
3
4

For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
103
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Syntax: for (type variableName : arrayName) {
// code block to be executed}

Example
public class MyClass {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
[Link](i);
}
}
}
Output

104
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Volvo
BMW
Ford
Mazda

Jump Statements in Java


Jump statements are used to unconditionally transfer program control from one point to elsewhere in
the program. Jump statements are primarily used to interrupt loop or switch-case
instantly. Java supports three jump statements: break, continue, and return.
Break Statement
The break statement is extensively used in loops and switch statement. It
immediately terminates the loop or the switch statement, by passing the

105
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
remaining statement. The control then passes to the statement that immediately
follows the loop or the switch statement.
Example
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
[Link]( x );
106
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link]("\n");
}
}
}
Output
10
20

Example
public class BreakExample{
public static void main(String args[]){
for(int i=0;i<=100;i++){
if(i==10){ //exit loop when i is equals to 10
107
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
break;
}
[Link]("Value of i is: " + i);
}
}
}
Output
Value of i is: 0
Value of i is: 1
Value of i is: 2
Value of i is: 3
Value of i is: 4
Value of i is: 5
108
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Value of i is: 6
Value of i is: 7
Value of i is: 8
Value of i is: 9

Continue Statement
The continue statement is used to continue the loop with its next iteration. In other words, it skips any
remaining statements in the current iteration and immediately passes the control to the next iteration.
Example
public class ContinueExample{
public static void main(String args[]){
for (int i=0; i<=5; i++)
{

109
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
if (i==2)
{
continue; //skips the rest of the statement
}
[Link](i+" ");
}
}
}

Output:
01345
The above output dislays all the numbers except 2. When the control statement is encountered, it
jumps to the next iteration, skipping the statements for current iteration. It simply skips the rest of the
code whenever “continue” construct is used.
110
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Return Statement
The return statement is used to transfer the control out of the method explicitly. It transfers the control
back to the caller and terminates the method in which it is present. When the return statement is
encountered in the main()method, it transfers the control back to the Java run-time system and
terminates the program execution.
Example
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


[Link](myMethod(3));
111
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
}
}

Output:
8

112
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

113
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER SEVEN

JAVA CONSTRUCTORS AND DESTRUCTORS

7.1 CONSTRUCTORS
Constructors in Java are special types of methods that are used to initialize the objects of the class.
Constructors are called at the time of object creation of class. Just like methods, although they hold a
set of lines of code they are quite different from them. Constructors have the same name as the Java
class but it does not have any return type. In Java, a new() keyword to used to create an object and
every time a new object is created and one constructor is called. The constructor is called after the
memory is allocated to the object. At the time of object creation, constructors are used to initializing
the values of class variables to either default or the desired ones. If the user does not create any
constructor in the program, Java itself creates a default constructor for it and assign default values to
the different objects like for numeric default value is 0, for a character (‘\0’) and reference variables as

114
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
null. Like methods, constructors can be overloaded, i.e. a single class can have many constructors if all
of them have a unique signature.
Syntax: class ClassName {
ClassName() {
}
}
Java allows two types of constructors namely:
1. No argument or Default Constructors
2. Parameterized Constructors

No Argument or Default Constructors


If you don’t implement any constructor in your class, the Java compiler inserts default constructor
into your code on your behalf. You will not see the default constructor in your source code(the .java
file) as it is inserted during compilation and present in the bytecode (.class file).
115
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Eaxample

// Create a MyClass class


public class MyClass {
int x;
// Create a class constructor for the MyClass class
public MyClass() {
x = 5;
}
public static void main(String[] args) {
MyClass myObj = new MyClass();
[Link](myObj.x);
}

116
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
}
Output: 5

Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a
constructor in the same way that they are added to a method, just declare them inside the parentheses
after the constructor's name.
Example
public class Car {
String model;
int maxSpeed;
public Car(String model, int maxSpeed){
[Link] = model;
117
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link] = maxSpeed;
}
public static void main(String[] args) {
Car bugatti = new Car("Bugatti Veyron", 378);
[Link]([Link]);
[Link]([Link]);
}
}

7.2 CONSTRUCTOR OVERLOADING


Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
118
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Example
you have 2 pet cats at home. You got one of them as a kitten. But the second one you took in from the
street when it was already grown, and you don't know exactly how old it is.
public class Cat {
String name;
int age;
// For the first cat
public Cat(String name, int age) {
[Link] = name;
[Link] = age;
}
// For the second cat
public Cat(String name) {
119
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
[Link] = name;
}
public static void main(String[] args) {
Cat smoke = new Cat("Smoke", 5);
Cat streetCatNamedBob = new Cat("Bob");
}
}

Basic Rules for writing Constructor in Java:


1. It is not necessary to write a constructor in your program.
2. By default, the compiler creates constructor at run=time.
3. The name of the constructor should be the same as the name of the class.
4. You can write multiple constructors for a single class object in Java.
120
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

7.3 DESTRUCTOR
Destructor is a method called when the destruction of an object takes place. “ The main goal of the
destructor is to free up the allocated memory and also to clean up resources like the closing of open
files, closing of database connections, closing network resources, etc,.When the objects are created
they are stored in the heap memory. These are accessible by main or child threads. So when these
objects are no more used by the main thread or its child threads they become eligible for garbage
collection and the memory which was acquired now becomes available by new objects being created.
Before an object is a garbage collected by the garbage collector the JRE (Java Runtime Environment)
calls the finalize() method to close the input-output streams, the database connections, network
connections, etc. Note that the finalize method called is protected. Why finalize is protected because it
can be either called by the base class or derived class? finalize method is present in the Object class.

121
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Thus in case you want to call this finalize method from other objects you can change this protected to
public.

Example
public class Animal{
public static void main(String[] args) {
Animal lion = new Animal();
[Link]("Main is completed.");
}
protected void finalize() {
[Link]("Rest in Peace!");

122
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
}
}

Output

Main is completed.

123
Fundamentals of Java Programming language 1

A
Copyright © A. Ayinla 2

All Right Reserved


Introductionto No part of this book ma
transmitted in any form
photocopying or otherw

Professional Practice publisher in writing.

First Published in 201

& Code of Ethicsin IT Published by:


Power Print Ltd.
No 22 Opo-Malu Road, I
08028237916, 080-34947

ISBN:

Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261

124

You might also like