Programming With Java
Programming With Java
Fundamentals of
Programming with Java
1
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER ONE
2
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
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
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.
6
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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.
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
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
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 ( )
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
10
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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.
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
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.
13
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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.
A
Copyright © A. Ayinla 2
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
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER TWO
18
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
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
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
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
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
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
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.
.Class file
(byte code) 26 JVM
Output
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
27
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
28
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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.
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
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
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
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";
A
Copyright © A. Ayinla 2
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;
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
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
A
Copyright © A. Ayinla 2
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.
Example:
37
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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);
}
38
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
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;}
}
A
Copyright © A. Ayinla 2
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.
A
Copyright © A. Ayinla 2
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
43
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
44
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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;}
46
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
48
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
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
51
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
import [Link];
53
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
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
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
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.
A
Copyright © A. Ayinla 2
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.
A
Copyright © A. Ayinla 2
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
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
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
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
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
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);
[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
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
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.
A
Copyright © A. Ayinla 2
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.
66
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
a / b = 2
a % b = 2
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
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;
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Output
var using =: 4
var using +=: 8
var using *=: 32
71
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Example
75
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
}
}
A
Copyright © A. Ayinla 2
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
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.
78
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
80
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
/= Division assignment
%= Modulus assignment
83
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER SIX
84
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Output:
x is greater than y
Nested if statement
87
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
88
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Statement 3; //executed when no matching condition found
}
Example
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
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
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
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Output
Friday
A
Copyright © A. Ayinla 2
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
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
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
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
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:
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
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
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Volvo
BMW
Ford
Mazda
105
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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 {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
[Link]( x );
106
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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
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
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
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;
}
A
Copyright © A. Ayinla 2
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
CHAPTER SEVEN
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
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
A
Copyright © A. Ayinla 2
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
Eaxample
116
Fundamentals of Java Programming language 1
A
Copyright © A. Ayinla 2
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
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]);
}
}
A
Copyright © A. Ayinla 2
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
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");
}
}
A
Copyright © A. Ayinla 2
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
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
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
ISBN:
Typesetting by:
By Al’amanah Internationa
Opo-Malu Road, Ilorin,
080-54646357/070-36261
124