KEMBAR78
OOPJAVA Preelim | PDF | Java Virtual Machine | Object Oriented Programming
0% found this document useful (0 votes)
28 views104 pages

OOPJAVA Preelim

The document outlines a course on Object Oriented Programming (JAVA) at Laguna University, detailing its vision and mission to produce well-rounded individuals. It includes a comprehensive course description, intended learning outcomes, assessment criteria, and a structured table of contents covering various modules on Java programming. Key topics include the basics of Java, programming methodologies, and the structure of Java programs, emphasizing the importance of object-oriented programming principles.

Uploaded by

ascanojellie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views104 pages

OOPJAVA Preelim

The document outlines a course on Object Oriented Programming (JAVA) at Laguna University, detailing its vision and mission to produce well-rounded individuals. It includes a comprehensive course description, intended learning outcomes, assessment criteria, and a structured table of contents covering various modules on Java programming. Key topics include the basics of Java, programming methodologies, and the structure of Java programs, emphasizing the importance of object-oriented programming principles.

Uploaded by

ascanojellie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Object Oriented Programming

(JAVA)

Numeriano B. Aguado
VISION

Laguna University shall be a socially responsive educational institution


of choice providing holistically developed individuals
in the Asia-Pacific Region

MISSION

Laguna University is committed to produce academically prepared


and technically skilled individuals who are socially
and morally upright
Course Code: IT 2207 - Object Oriented Programming (JAVA)

Course Description: The course introduce the students to object-oriented


programming; object-oriented design, encapsulation and information hiding;
classes, subclasses, and inheritance; polymorphism; class hierarchies;
collection classes and iteration protocols; fundamental design pattern, using
APIs events and exemptions. Programming exercises are done using Java.
Course Intended Learning Outcomes (CILO):
At the end of this course, the students should be able to:
1. acquire knowledge about Java language programming concepts and
techniques;
2. describe and compare structure of Java language with other
programming languages;
3. appreciate the beauty of object-oriented programming capabilities of
Java language compared with other OOP languages;
4. develop interest in designing and creating object-oriented program;
5. practice and show mastery in designing, writing and creating Java
object-oriented program.

Course Requirements:
▪ Quiz - 20%
▪ Laboratory Exercise - 20%
▪ Recitation/Attendance - 20%
▪ Major Exams (ME) - 40%
Periodic Grade 100%

Prelim Grade (PG) = (AT x 60%) + (ME x 40%)


Midterm Grade (MG) = ((AT x 60%) + (ME x 40%)) x 70%)+(PG x 30%)
Final Grade = ((AT x 60%) + (ME x 40%)) x 70%)+(MG x 30%)
Table of Contents

Module 1: Overview of Java Programming Language 1

Introduction 1
Learning Objectives 1
Lesson 1: What is Java 2
Lesson 2: Processing of Java Program 10
Lesson 3: Programming with the Problem Analysis,
Coding, and Execution Cycle 12
Lesson 4: Programming Methodologies 14

MODULE 2: Java Program Editors 19


Introduction 19
Learning Objectives 19
Lesson 1: Program Editors 20

MODULE 3: Basic Elements of Java 27


Introduction 27
Learning Objectives 28
Lesson 1: Basic of Java Program 28
Lesson 2: Variables in Java 34
Lesson 3: Data Types in Java 40
Lesson 4: Operators in Java 42
Lesson 5: Input (read) Statement 57
Lesson 6: Package, Classes, Methods and the import Statement 59
Lesson 7: Creating a Java Application Program 61

MODULE 4: Objects and Input/Output 66


Introduction 66
Learning Objectives 67
Lesson 1: Objects and Reference Variables 68
Lesson 2: Input/Output 71
Lesson 3: Parsing numeric strings 79
Lesson 4: File I/O in Java 83
MODULE 1
OVERVIEW OF JAVA PROGRAMMING
LANGUAGE

Introduction

Internet activities is so popular now a days. It is considered to be a part of life to most


people if not all. Students regularly “surf” the internet and use computers to design
their classroom projects. Generally people use the internet to look up information and
to communicate with each other.

These internet activities are all made possible by the availability of different software,
known as computer programs. Software is developed by using programming
languages. The JAVA programming language is especially well suited for the
development of software to accomplished specific desired tasks. The main objective
of this module is to teach students how to write programs in Java Programming
language.

It is useful to understand the basics of language programming: basic terminologies,


and different components of a computer, which most of you are familiar or acquainted
with. Before we begin programming we have to understand Java language overview

Learning Outcomes

At the end of this module, students should be able to:

1. Understand what Java Programming Language is;


2. Learn about evolution of programming languages;
3. Examine high-level programming language;
4. Understand the different program editors;
5. Rediscover compiler and what it does;
6. Learn what an algorithm is and explore problem solving techniques;

1
7. Become familiar with structured and object-oriented programming
design methodologies.

Lesson 1. What is Java (Javapoint, n.d.)

Java is an object-oriented, class-based, concurrent, secured and general-purpose


computer-programming language. Java is a programming language and a platform.
Java is a high level, robust, object-oriented and secure programming language.

Platform: Any hardware or software environment in which a program runs, is known


as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.

❖ History of Java

The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry
at the time. The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital devices
such as set-top boxes, televisions, etc. However, it was suited for internet
programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions, etc. There are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers
called Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-
top boxes.

2
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was
.gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

❖ Evolution of Programming Languages

The most basic computer language is machine language. It provides program


instructions in bits, though most computers perform the same kinds of operations, the
designers of different CPUs sometimes choose different sts of binary codes to perform
those operations. Because of this, the machine language of one computer is not
necessarily the same as the machine language of another computer. The only
uniformity and similarity among computers, all data are stored and manipulated as a
binary code.

Please visit this site for more information about evolution of programming languages:
https://www.extremetech.com/computing/91572-the-evolution-of-computer-languages-
infographic#:~:text=Programming%20languages%2C%20believe%20it%20or,%2Dcard%2Dprog
rammable%20Jacquard%20loom.&text=LISP%20(LISt%20Processor)%2C%20ALGOL,say%2C%
20the%20rest%20is%20history.

❖ Features of Java

The primary objective of Java programming language creation was to make it


portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this language.
Java is guaranteed to be Write Once, Run Anywhere.

Java is −

✓ Object Oriented − In Java, everything is an Object. Java can be easily


extended since it is based on the Object model.

✓ Platform Independent − Unlike many other programming languages


including C and C++, when Java is compiled, it is not compiled into platform
specific machine, rather into platform independent byte code. This byte code

3
is distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.

✓ Simple − Java is designed to be easy to learn. If you understand the basic


concept of OOP Java, it would be easy to master.

✓ Secure − With Java's secure feature it enables to develop virus-free, tamper-


free systems. Authentication techniques are based on public-key encryption.

✓ Architecture-neutral − Java compiler generates an architecture-neutral


object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.

✓ Portable − Being architecture-neutral and having no implementation


dependent aspects of the specification makes Java portable. Compiler in Java
is written in ANSI C with a clean portability boundary, which is a POSIX subset.

✓ Robust − Java makes an effort to eliminate error prone situations by


emphasizing mainly on compile time error checking and runtime checking.

✓ Multithreaded − With Java's multithreaded feature it is possible to write


programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.

✓ Interpreted − Java byte code is translated on the fly to native machine


instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.

✓ High Performance − With the use of Just-In-Time compilers, Java enables


high performance.

✓ Distributed − Java is designed for the distributed environment of the internet.

✓ Dynamic − Java is considered to be more dynamic than C or C++ since it is


designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.

4
❖ Structure of Java Program

Java is an object-oriented programming, platform independent, and secure


programming language that makes it popular. Using the Java programming language,
we can develop a wide variety of applications. So, before diving in depth, it is necessary
to understand the basic structure of Java program in detail. In this section, we have
discussed the basic structure of a Java program. At the end of this section, you will
able to develop the Hello world Java program, easily. Let's see which elements are
included in the structure of a Java program. A typical structure of a Java program
contains the following elements:

o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors

Figure 1.1 Structure of Java Program


Source: (Javapoint, n.d.)

5
➢ Documentation Section

The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes
the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the program.
Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the
documentation section, we use comments. The comments may be single-line, multi-
line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//). For


example:

1. //First Java Program

o Multi-line Comment: It starts with a /* and ends with */. We write between
these two symbols. For example:
1. /*It is an example of
2. multiline comment*/

o Documentation Comment: It starts with the delimiter (/**) and ends with */.
For example:
1. /**It is an example of documentation comment*/

➢ Package Declaration

The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed. Note that
there can be only one package statement in a Java program. It must be defined before
any class and interface declaration. It is necessary because a Java class can be placed
in different packages and directories based on the module they are used. For all these
classes package belongs to a single parent directory. We use the keyword package to
declare the package name. For example:

1. package javatpoint; //where javatpoint is the package name

6
2. package com.javatpoint; //where com is the root directory and javatpoint
is the subdirectory

➢ Import Statements

The package contains the many predefined classes and interfaces. If we want to use
any class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to import
the class. It is written before the class declaration and after the package statement.
We use the import statement in two ways, either import a specific class or import all
classes of a particular package. In a Java program, we can use multiple import
statements. For example:

1. import java.util.Scanner; //it imports the Scanner class only


2. import java.util.*; //it imports all the class of the java.util package

➢ Interface Section

It is an optional section. We can create an interface in this section if required. We use


the interface keyword to create an interface. An interface is a slightly different from
the class. It contains only constants and method declarations. Another difference is
that it cannot be instantiated. We can use interface in classes by using
the implements keyword. An interface can also be used with other interfaces by using
the extends keyword. For example:

1. interface car
2. {
3. void start();
4. void stop();
5. }

➢ Class Definition

In this section, we define the class. It is vital part of a Java program. Without the class,
we cannot create any Java program. A Java program may conation more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a

7
Java program. It contains information about user-defined methods, variables, and
constants. Every Java program has at least one class that contains the main() method.
For example:

1. class Student //class definition


2. {
3. }

➢ Class Variables and Constants

In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters. It is used
during the execution of the program. We can also decide and define the scope of
variables by using the modifiers. It defines the life of the variables. For example:

1. class Student //class definition


2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }

➢ Main Method Class

In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class. Inside the main
method, we create objects and call the methods. We use the following statement to
define the main() method:

1. public static void main(String args[])


2. {
3. }

8
For example:

1. public class Student //class definition


2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }

You can read more about the Java main() method here.

➢ Methods and behavior

In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions
execute at runtime and perform the specified task. For example:

1. public class Demo //class definition


2. {
3. public static void main(String args[])
4. {
5. void display()
6. {
7. System.out.println("Welcome to javatpoint");
8. }
9. //statements
10. }
11. }

When we follow and use the above elements in a Java program, the program looks
like the following.

CheckPalindromeNumber.java

1. /*Program name: Palindrome*/


2. //Author's name: Mathew

9
3. /*Palindrome is number or string that will remains the same
4. When we write that in reverse order. Some example of
5. palindrome is 393, 010, madam, etc.*/
6. //imports the Scanner class of the java.util package
7. import java.util.Scanner;
8. //class definition
9. public class CheckPalindromeNumber
10. {
11. //main method
12. public static void main(String args[])
13. {
14. //variables to be used in program
15. int r, s=0, temp;
16. int x; //It is the number variable to be checked for palindrome
17. Scanner sc=new Scanner(System.in);
18. System.out.println("Enter the number to check: ");
19. //reading a number from the user
20. x=sc.nextInt();
21. //logic to check if the number id palindrome or not
22. temp=x;
23. while(x>0)
24. {
25. r=x%10; //finds remainder
26. s =(s*10)+r;
27. x=x/10;
28. }
29. if(temp==s)
30. System.out.println("The given number is palindrome.");
31. else
32. System.out.println("The given number is not palindrome.");
33. }
34. }

Output:

10
Lesson 2. Processing of Java Program (Malik, n.d.)

Java has two types of programs – applications and applets. The following is an example
of Java application program:

//My First Program


public class MyFirstJavaProgram {
public static void main(String[ ] args) {
System.out.println(“My First java Program!”);
}
}
If you run or execute the program code, it will display the following line on you screen:

My First Java Program!


It is noted that computer understand only machine language, therefore, before we run
the program successfully, the program code must be first translated into machine
code. So in this section we will review the steps required to execute the program
written in Java.

The flowchart below illustrates how program is executed:

Figure 1.2 Processing of Java Program


(Source: Malik, n.d.)

11
The following steps are carried on first before the program executes and display its
output:

✓ Step 1. Use text editor like Notebook or other IDEs available to write your Java
program code following the rules or syntax of the language. The program is
called source program. The program must be saved in a text file named
ClassName.java, where the ClassName is the name of the Java class contained
in the file. For example, in the Java program written above, in the name (public)
class containing the Java program is MyFirstJavaProgram. So the program
must be saved as MyFirstJavaProgram.java if not so we will get an error.

Source Program is a program written in a high level language.

✓ Step 2. Program must be written I a correct syntax before it is compiled or


translated into a program equivalent bycode. The compiler checks the source
program for syntax error/s and if no error found the compiler translate the
source code into a bycode otherwise it will move back to editor to correct
syntax. Once it is OK the the program is saved in the file with an extension of
.class. It will store in a file as MyFirstJavaProgram.class by the compiler.

✓ Step 3. To run the Java application program, the .class file must be loaded into
computer memory. The program is automatically loaded and is done by Java
loader.

✓ Step 4. The next step is to run the Java program. In addition to connecting the
bytecode from various classes, the loader also loads your Java program’s
bytecode into main memory. As the classes are loaded the bytecode verifier
verifies that the bytecode for the class is valid and does not violate Java’s
security restrictions.

✓ Step 5. Finally, a program called interpreter translates each bytecode


instruction into our computer’s machine language and then execute it.

Interpreter: a program that reads and translates each bytecode instruction into
your computer’s machine language for execution.

12
Lesson 3. Programming with the Problem Analysis,
Coding, and Execution Cycle (Malik, n.d.)

Programming is a process of problem solving. Different people use different


techniques to solve problems. Several problems are already outlined and easy to
follow. They solve the problem ang give insight into how the solution was reached.
Such problem techniques can be easily modified if the domain of the problem changes.

To be a skillful problem solver, and to become a skillful programmer, an individual


must use good problem-solving techniques. One common problem-solving
technique includes analyzing a problem, outlining the problem requirements, and
designing steps, called an algorithm, to solve the problem.

Algorithm: A step-by-step problem-solving process in which a solution is arrived at in


a finite amount of time.

In the programming environment, the problem-solving process involves the following


steps:
1. Analyze the problem and outline the problem requirements and its solutions;
2. Design an algorithm to solve the problem;
3. Implement the algorithm in the programming language, --such as Java;
4. Verify if the algorithm works;
5. Maintain the program by using and improving it, and modifying it if the
problem domain changes.

To develop a program to solve problem, one must start analyzing the problem, the
outlining the problem and the options for solution. The design the algorithm, write the
program instructions in a high-level language, or code the program, and enter the
program into a computer system.

13
Analyzing the problem is the most important step in the process. This step requires
the we do the following:

1. Thoroughly understand the problem;


2. Know the problem requirements. Requirements can include whether the
program requires interaction with the user, whether it manipulates data,
whether it produces output and what the output looks like. If the program
manipulates data, one must know what the data are and how they are
represented. To do this, you need to look at sample data.
3. If the program produces output, one should know how the results should be
generated and formatted.
4. If the problem is complex, divide the problem into subproblems and repeat
steps 1 and 2 by analyzing each subproblem and understanding each
subproblem’s requirements. Also should know how the subproblems relate to
each other.
5. Design an algorithm to solve the problem. Once the algorithm is done, check
its correctness. Use sample data to check, use mathematical analysis to test
its correctness. Integrate subproblem solution if there is.
6. Once done with the algorithm, convert it into a high-level language. Use IDE to
enter it into computer following the correct syntax. Compile the program code
to check its correctness syntactically.
7. Execute the program.

Lesson 4. Programming Methodologies (Pediaa, 2019)

Two of the most popular approaches to programming design are the Structured
approach and the Object-Oriented approach.

14
➢ Difference Between Structured and Object-Oriented Programming (Pediaa,

2019)
The main difference between structured and object-oriented programming is
that structured programming is a programming paradigm which divides the code into
modules or function; it allows developing a program using a set of modules or
functions, while object oriented programming is a programming paradigm based on
the concept of objects, which contain data in the form of fields known as attributes,
and code in the form of procedures known as methods; it allows constructing a
program using a set of objects and their interactions.

• Structured Programming
Structured Programming divides a program into a set of functions or
modules. Modular programming is another name for this. These functions have
statements embraced inside curly braces. Each of these functions performs a
subtask. Usually, as each function represents a specific functionality, it is easier
for the programmer to test and debug the code, but this can differ depending on
the program. C language and Pascal are two common structured programming
languages.

In the structured programming C, the user can create his own user-defined
functions. The main function calls the other functions. It indicates the execution
of the program. When there is a function call, the control is passed to that
function. After completing the function, the control passes back to the main
program. Moreover, a variable inside a function is a local variable, and global
variables are accessible by all the functions.

• Object-Oriented Programming

Object-oriented programming allows the programmer to represent real-world


scenarios using objects. An object is any entity that has states and behaviors.
States represent the attributes or data of an object, whereas the methods
represent the behaviors of objects. Student, Employee, Book etc. are objects.
These objects interact with other objects by passing messages. Furthermore,
a class is a blueprint for creating an object. It is necessary to have a class to

15
create objects. For example, to create an Employee object, there should be an
Employee class.

Figure 1.3 Class and Objects samples


Source: (Pediaa, 2019)

In addition to classes and objects, there are four major pillars in OOP. They are
as follows.
Encapsulation – Binds or combines properties and methods into a
single unit
Inheritance – Allows a class to use properties and methods of an
already existing class
Polymorphism – Allows an object to perform in multiple ways –
Overloading and overriding are two ways of achieving polymorphism.
Abstraction – Hides the internal details and displays only the
functionalities to the user – Moreover, abstract classes and interfaces
help to achieve abstraction.

Overall, object-oriented programming makes it easier to develop the program.


Furthermore, it provides data security, maintainability and code reusability.

16
Assessment Task 1-1

Test your knowledge.


Give and discuss in writing your answer to the following questions:

1. Why do you need to translate a program written in a high level


language into machine language?
2. Why would you prefer to write s program on high level language
rather than aa machine language?
3. What are the advantages of problem analysis and algorithm design
over directly writing a program in a high level language?
4. Design an algorithm to find the weighted average of four scores.
The four test scores and their respective weights are given in the
following format:

Test score1 weightTestScore1


….
…..
For example, a simple data is as follows:

75 0.20
95 0.35
85 0.15
65 0.30

17
Assessment Task 1-2

Test your knowledge.


Give and discuss in writing your answer to the following questions:

5. To make profit, the price of the items sold in a furniture store are
marked up by 80%. After making up the prices each item is put on
sale at a discount of 10%. Design an algorithm to find the selling
price of an item sold at the furniture store. What information do you
need to find the selling price?
6. Suppose that the cost of sending an international fax is calculated
as follows: Service charges 3.00, (0.20 per page for the first 10
pages, and 0.10 for each additional page). Design an algorithm that
ask the user to enter the number of pages to be faxed. The
algorithm then uses the number of pages to calculate the amount
due.

18
Summary

We have discussed about software using Java programming languages. We have


learned that JAVA programming language is especially well suited for the
development of software to accomplished specific desired tasks. It was
presented to you on how this module taught us and students on how to write
programs in Java Programming language.

It was stated how it is useful to understand the basics of language programming:


basic terminologies, and different components of a computer, which most of you
are familiar or acquainted with.

References

Javapoint. (2021). Retrieved 7 January 2021, from https://www.javatpoint.com/java-


tutorial
Malik, D.S. (n.d.). Java Programming: From Problem Analysis to Program Design. 5th
Edition, Cengage Learning Asia Pte Ltd.

Pediaa (2019). Retrieved 7 January 2021, from https://pediaa.com/what-is-the-


difference-between-structured-and-object-oriented-
programming/#Structured%20Programm

19
MODULE 2
JAVA PROGRAM EDITORS

Introduction

Java is one of the leading programming languages. Widely employed for developing
robust and secure desktop apps, enterprise applications, mobile apps, and web
applications.

For us to be able to write Java program codes, Text editors are needed. There are
various available text editors that we can use like Notepad, Notepad++, and the like.
However, we can use a lot more editor which are commonly called Integrated
Development Environment (IDE) available in the Internet. They may be commercial or
Open Source application which are most often free for use.

Eclipse, IntelliJ IDEA, and NetBeans are the big three IDEs designed for Java program
development. Moreover, there are numerous other IDEs for developing apps effectively
used for Java.

Learning Outcomes

At the end of this module, students should be able to:

1. Learn the different text editors for Java;


2. Understand how these editors are use;
3. Compare and examine the capabilities these IDEs;
4. Familiarize with the different IDEs; and
5. Use independently the IDE of their choice.

20
Lesson 1. Program Editors (Hackr.io, 2021)

Program editors are commonly used in writing programming code. 4They are called
Integrated Development Environment (IDE). Java is one of the leading programming
languages. Widely employed for developing robust and secure desktop apps,
enterprise applications, mobile apps, and web applications.

There is a multitude of free Java IDEs available for working with Java. While Eclipse,
IntelliJ IDEA, and NetBeans are the big three of Java, there are numerous other IDEs
for developing apps effectively using Java.

1. Eclipse

Platform – Linux/macOS/Solaris/Windows
First Released – November 2001 1

A dedicated Java IDE, Eclipse gets listed as one of the big three of Java IDEs. The
modern integrated development environment is available in both desktop and cloud
editions. The cloud edition of the Eclipse, named Eclipse Che, allows programmers to
develop apps via a web browser.

Both editions of the Eclipse IDE equips with required/additional functionality utilizing
plugins. There is an array of plugins available for the IDE on the Eclipse Marketplace.
To facilitate the incremental compilation of Java code, Eclipse comes with a custom
compiler.

For Java programmers looking to develop specific functionality for Eclipse, a PDE
(Plugin Development Environment) is available. To help Java developers hasten the
application development, Eclipse flaunts powerful tools for charting, modelling,
reporting, and testing.

Eclipse supports application development in several programming languages via


plugins. C, C++, Clojure, Groovy, Haskell, JavaScript, Julia, Perl, PHP, Ruby, Rust, and
Scala are some of the various programming languages supported by Eclipse.

21
Features:
• a runtime core,
• a collection of libraries,
• a modelling and control language,
• a development environment,
• interfaces for embedding into host environments,
• interfaces to third-party solvers.

2. NetBeans

Platform – Linux/macOS/Solaris/Windows
First Released – 1997 2

Another name in the big three of Java IDEs is NetBeans. It is also free java ide.
NetBeans is the official IDE for Java 8. The open-source IDE facilitates Java
programmers to build desktop, mobile, and web applications by offering a range of
potent tools and features.

In addition to being available for a variety of platforms, NetBeans also comes in a


feature-limited OS-independent version. Each novel version of the NetBeans boasts
an improved and reworked Java editor.

By highlighting Java code syntactically and semantically, it makes it easier for Java
programmers to build custom software apps. Inbuilt tools in NetBeans makes it
possible to refactor the code as well as writing bug-free code.

To design and develop GUIs for Java SE, a GUI Builder is put on offer by NetBeans.
The dedicated Java IDE is available in 28 different languages. NetBeans has
extensions available for working in C, C++, HTML5, JavaScript, PHP, and other
programming languages.

Features:
• Cross-platform support
• Multiple language support
• Visual debugger
• NetBeans Profiler
• Static analysis tools
• Project management

22
• Code editor
• Batch code analyzers
• Code converters

3. IntelliJ IDEA

Platform – Linux/macOS/Windows
First Released – January 2001 3

IntelliJ IDEA is one of the big three of Java IDEs. It is available in 2 different editions,
an Apache 2 Licensed community edition, and a proprietary commercial edition. To
allow developers to dive deeper into the Java code, IntelliJ IDEA boasts cross-language
refactoring and data flow analysis features.

Other features offered by IntelliJ IDEA that eases the life of a Java developer are chain
completion, language injection, smart completion, and static member completion.

In addition to supporting Java and a galore of Java frameworks, IntelliJ IDEA also
provides support for other JVM-based programming languages, such as Kotlin.

Features:
• Smart completion
• Chain completion
• Static members completion
• Data flow analysis
• Language injection
• Cross-language refactorings
• Detecting duplicates
• Inspections and quick-fixes

4. JCreator

Platform – Linux (via Wine)/Windows


First Released – N/A

Developed by Xerox Software, JCreator is yet another lightweight Java IDE. JCreator
flaunts an interface much similar to Microsoft’s Visual Studio. It is available in three
distinct variants; Lite Edition, Pro Edition, and Life-Pro Edition.

23
Unlike leading Java IDEs that are developed using Java, JCreator is developed entirely
in C++. Furthermore, it doesn’t require a JRE for executing Java code. For this
particular reason, the developer community advocates that JCreator is faster than
most conventional Java-based IDEs.

The paid version of JCreator comes with Ant support, code wizards, and a debugger.
Unlike the leading Java IDEs, JCreator has no advanced features. Also, extensibility via
3rd-party plugins is unavailable. On the flip side, it is small and fast, making it ideal
for newbies starting with Java.

Features:

• Selection Margin
• Line Numbers & File Difference
• Color Syntax Selection
• Undo & Redo Functions
• Visible Tabs & Spaces
• Search & Replace Engine
• Automatic Indention
• Text Formatting Capabilities
• Advanced Editing Commands
• Comment Selections
• Code Folding
• Block Selection
• Colored Bracket Matching
• Code Templates
• Word Wrap
• Spellcheck
• Tabbed Documents
• Docked Toolbars & Workspaces
• Full-Screen Mode
• Intelligent Docking Assistants
• File Templates
• Workspace Structure
• Mounted Projects
• Virtual Folders-Based Projects

24
• File Properties Viewer
• Integrated CVS
• Class & Interface Wizard
• Implement Interface Wizard
• Insert Bean Methods
• Project/Folder/File Building
• Execute & Build Project
• JDK Tools
• JDK Profiles
• JDK Debugger
• Classpath Management
• Libraries
• Code Identifier
• Code Completion
• Code Refractory
• Optimize Imports
• Import Suggestion
• User Class Coloring
• Source Code Navigation
• Runtime Configurations
• Java Console

As we can see, there are abundant of IDE options available for Java developers,
ranging from fully-featured commercial software to free and open-source ones. The
selection of the Java IDE depends on your current project and personal preference.
For our practices we will use Elipse as a standard for our Java Programming Language
class. The more a developer knows, the better options there are to choose from. Which
Java IDE do you think is the best?

For download and installation to your computer, please visit the IDE home pages and
download the application.

25
Assessment Task 2

Test your skill.


Given the different IDEs, you are given the task written below:

1. Download and install one IDE of your choice for you to use in our
Java programming course. Please consider creating a work place
folder, where you are to save all your projects and programs to do
in our course. Be sure to configure the PATH accordingly.
Note: ask your instructor of what IDE you are to install. This is
important so as to use a standard IDE in your class.

Summary

We were introduced the different IDEs we are free to use. These are useful in the
development of Java program as we were told for us to be able to write Java program
codes, Text editors are needed. As discussed, aside from the various available text
editors that we can use like Notepad, Notepad++, we can use a lot more editor which
are commonly called Integrated Development Environment (IDE) available in the
Internet. They may be commercial or Open Source application which are most often
free for use.

Reference

Hacker.io. (2021). Most Popular Java IDE for Coding. Retrieved 7 January 2021, from
https://hackr.io/blog/best-java-ides

26
MODULE 3
BASIC ELEMENTS OF JAVA

Introduction

In this Module we learn the basics of Java. As we begin learning the Java programming
language, two basic question naturally arises: First, what is a computer program? Next
is, what is programming? To answer, a computer program or program, is a sequence
of statements intended to accomplish a task. Programming, on the other hand is a
process of planning and creating a program.

Those declaration tells the truth, but not the whole truth, about programming. It might
take an entire book to give a satisfactory explanation of programming. An analogy
might help us gain a better understanding of the nature of programming, thus we will
use topic on which almost everyone has some knowledge…cooking. A recipe is also a
program and everyone with some cooking experience can agree on the following:

• It is easier to follow a recipe than to create one;


• There are bad and good recipes;
• Some recipes are easy to follow and some that are hardly to follow;
• Some recipes produce reliable results and some are not;
• To create good new recipes, we must have significant knowledge and
understanding of cooking.

The points cited above can also be applied in programming. Let us take the cooking
analogy. As there are many ways to learn cooking, there are also several ways to learn
programming. Learning a programming is like learning to become a chef.

A chef cannot be a good chef by just merely reading the recipes. The same is true in
programming. We must have the fundamental knowledge of the language, we are able
to execute and test the program we wrote to make sure that each program we do does
what it is supposed to do.

27
Learning Outcomes

At the end of this module, students should be able to:

1. Become familiar with the basic components of Java program such as


methods, special symbols, and identifiers;
2. Explore primitive data types;
3. Understand arithmetic operators;
4. Examine how program evaluates arithmetic expressions including mixed
expressions;
5. Learn about type casting;
6. Understand how to input data into memory by using input statements;
7. Examine ways to output using output statements;
8. Learn how to import packages and why they are necessary;
9. Learn how to understand correct syntax and discover how to create Java
application program.

Lesson 1. Basic of Java Program (Singh, n.d.)

Before we start learning Java, let us get familiar with common java terms.

• Java Virtual Machine (JVM)


This is generally referred as JVM. Before, we discuss about JVM lets see the
phases of program execution. To recall, the phases are as follows: we write the
program, then we compile the program and finally we run the program.
1. Writing of the program is of course done by java programmer like you
and me.
2. Compilation of program is done by javac compiler, javac is the primary
java compiler included in java development kit (JDK). It takes java
program as input and generates java bytecode as output.
3. In third phase, JVM executes the bytecode generated by compiler. This
is called program run phase.

28
Now that we understood that the primary function of JVM is to execute the
bytecode produced by compiler. Each operating system has different JVM, however
the output they produce after execution of bytecode is same across all operating
systems. That is why we call java as platform independent language.

• bytecode
As discussed above, javac compiler of JDK compiles the java source code into
bytecode so that it can be executed by JVM. The bytecode is saved in a .class
file by compiler.

• Java Development Kit (JDK)


While explaining JVM and bytecode, we used the term JDK. As the name suggests
this is complete java development kit that includes JRE (Java Runtime
Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program we would need JDK installed on
our computer.

• Java Runtime Environment (JRE)


JRE is a part of JDK which means that JDK includes JRE. When you have JRE
installed on your system, you can run a java program however you won’t be able
to compile it. JRE includes JVM, browser plugins and applets support. When you
only need to run a java program on your computer, you would only need JRE.

These are the basic java terms that confuses beginners in java. For complete
java glossary refer this link:
https://docs.oracle.com/javase/tutorial/information/glossary.html

❖ Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java

Java is a high level programming language. A program written in high level language
cannot be run on any machine directly. First, it needs to be translated into that
particular machine language. The javac compiler does this thing, it takes java
program (.java file containing source code) and translates it into machine code
(referred as byte code or .class file).

29
Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your
computer) and the machine language for JVM is byte code. This makes it easier for
compiler as it has to generate byte code for JVM rather than different machine code
for each type of machine. JVM executes the byte code generated by compiler and
produce output. JVM is the one that makes java platform independent.

So, now we understood that the primary function of JVM is to execute the byte code
produced by compiler. Each operating system has different JVM, however the
output they produce after execution of byte code is same across all operating
systems. Which means that the byte code generated on Windows can be run on Mac
OS and vice versa. That is why we call java as platform independent language. The
same thing can be seen in the diagram below:

Figure 3.1. Different Operating systems with different JVM


Source: (Singh, n.d.)

❖ JVM Architecture

Figure 3.2. JVM Architecture


Source: (Singh, n.d.)

30
• How JVM works:

Class Loader: The class loader reads the .class file and save the byte code in
the method area.

Method Area: There is only one method area in a JVM which is shared among all
the classes. This holds the class level information of each .class file.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a
Class object for each .class file.

Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing
temporary variables.

PC Registers: This keeps the track of which instruction has been executed and
which one is going to be executed. Since instructions are executed by threads,
each thread has a separate PC register.

Native Method stack: A native method can access the runtime data areas of the
virtual machine.

Native Method interface: It enables java code to call or be called by native


applications. Native applications are programs that are specific to the hardware
and OS of a system.

Garbage collection: A class instance is explicitly created by the java code and
after use it is automatically destroyed by garbage collection for memory
management.

• JVM Vs JRE Vs JDK

JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine (JVM), class libraries, and other files excluding
development tools such as compiler and debugger which means you can run the
code in JRE but you can’t develop and compile the code in JRE.

31
JVM: As we discussed above, JVM runs the program by using class, libraries and
files provided by JRE.

Figure 3.3. JRE Architecture


Source: (Singh, n.d.)

JDK: JDK is a superset of JRE, it contains everything that JRE has along with
development tools such as compiler, debugger etc.

Figure 3.4. JRE Architecture


Source: (Singh, n.d.)

Simple Java Program:

public class MyFirstJavaProgram {


public static void main(String[ ] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

Output:
This is my first program in java

32
➢ Closer look to the First Java Program

Now that we have understood how to run a java program, let have a closer look at the
program we have written above.

public class MyFirstJavaProgram {

This is the first line of our java program. Every java application must have at least one
class definition that consists of class keyword followed by class name. When we say
keyword, it means that it should not be changed, we should use it as it is. However,
the class name can be anything.

We have made the class public by using public access modifier, we need to know
now that a java file can have any number of classes but it can have only one public
class and the file name should be same as public class name.

public static void main(String[ ] args) {

This is our next line in the program, let us break it down to understand it:
public: This makes the main method public that means that we can call the method
from outside the class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can
run our program.

(String[ ] args): Used for command line arguments that are passed as strings.

System.out.println("This is my first program in java");


This method prints the contents inside the double quotes into the console and inserts
a newline after.

33
Lesson 2. Variables in Java (Singh, n.d.)

A variable is a name which is associated with a value that can be changed. For
example when we write int i=10; here variable name is i which is associated with
value 10, int is a data type that represents that this variable can hold integer values.

Variable is name of reserved area allocated in memory. In other words, it is a name


of memory location. It is a combination of "vary + able" that means its value can be
changed.

➢ How to Declare a variable in Java

To declare a variable, follow this syntax:

data_type variable_name = value;

here value is optional because in java, you can declare the variable first and then
later assign the value to it.

For example: Here num is a variable and int is a data type. We will discuss the data
type in next so do not worry too much about it, just understand that int data type
allows this num variable to hold integer values.

int num;
Similarly, we can assign the values to the variables while declaring them, like this:

char ch = 'A';
int number = 100;

or we can do it like this:

char ch;
int number;
...
ch = 'A';
number = 100;

34
➢ Variables naming convention in java
1. Variables naming cannot contain white spaces, for example: int num ber =
100; is invalid because the variable name has space in it.
2. Variable name can begin with special characters such as $ and _
3. As per the java coding standards the variable name should begin with a
lower case letter, for example int number; For lengthy variables names that
has more than one words do it like this: int smallNumber; int bigNumber;
(start the second word with capital letter).
4. Variable names are case sensitive in Java.

➢ Types of Variables in Java

There are three types of variables in Java.


1. Local variable
2. Static (or class) variable
3. Instance variable

Figure 3.5. Java Data Types


Source: (Singh, n.d.)
Static (or class) Variable

Static variables are also known as class variable because they are associated with
the class and common for all the instances of class. For example, If we create three
objects of a class and access this static variable, it would be common for all, the

35
changes made to the variable using one of the object would reflect when we access it
through other objects.

Example of static variable

public class StaticVarExample {


public static String myClassVar="class or static variable";

public static void main(String args[ ]){


StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);

//changing the value of static variable using obj2


obj2.myClassVar = "Changed Text";

//All three will display "Changed Text"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}

Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text

36
As we can see all three statements displayed the same output irrespective of the
instance through which it is being accessed. That’s is why we can access the static
variables without using the objects like this:

System.out.println(myClassVar);

Do note that only static variables can be accessed like this. This does not apply for
instance and local variables.

Instance variable

Each instance(objects) of class has its own copy of instance variable. Unlike static
variable, instance variables have their own separate copy of instance variable. We
have changed the instance variable value using object obj2 in the following program
and when we displayed the variable using all three objects, only the obj2 value got
changed, others remain unchanged. This shows that they have their own copy of
instance variable.

Example of Instance variable

public class InstanceVarExample {


String myInstanceVar="instance variable";

public static void main(String args[]){


InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();

System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
obj2.myInstanceVar = "Changed Text";
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
}
}

37
Output:
instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable

These variables are declared inside method of the class. Their scope is limited to
the method which means that we cannot change their values and access them outside
of the method.

In this example, we have declared the instance variable with the same name as local
variable, this is to demonstrate the scope of local variables.

Example of Local variable

public class VariableExample {


// instance variable
public String myVar="instance variable";

public void myMethod(){


// local variable
String myVar = "Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

/* We are calling the method, that changes the


* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/

38
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}

Output:
Calling Method
Inside Method
instance variable

If we had not declared the instance variable and only declared the local variable
inside method then the statement System.out.println(obj.myVar); would have
thrown compilation error. As you cannot change and access local variables outside the
method.

Lesson 3. Data Types in Java (Singh, n.d.)

Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values. In java we have two categories of data
types:
1) Primitive data types 5-8
2) Non-primitive data types 9-10
– Arrays and Strings are non-primitive data types.
Here we will discuss primitive data types and literals in Java.

39
Table 3.1 Java Data Types (Singh, n.d.)

Java is a statically typed language. A language is statically typed, if the data type of
a variable is known at compile time. This means that you must specify the type of
the variable (Declare the variable) before you can use it.

In the previous topic about Java Variables, we learned how to declare a variable, lets
recall it:

int num;

So in order to use the variable num in our program, we must declare it first as shown
above. It is a good programming practice to declare all the variables ( that you are
going to use) in the beginning of the program.

1) Primitive data types

In Java, we have eight primitive data types:


• boolean, • long,
• char, • float
• byte, • double.
• short,
• int,

40
Java developers included these data types to maintain the portability of java as the
size of these primitive data types do not change from one operating system to another.

• byte, short, int and long data types are used for storing whole numbers.
• float and double are used for fractional numbers.
• char is used for storing characters(letters).
• boolean data type is used for variables that holds either true or false.

byte:

This can hold whole number between -128 and 127. Mostly used to save memory and
when you are certain that the numbers would be in the limit specified by byte data
type.
✓ Default size of this data type: 1 byte.
✓ Default value: 0

Example:
class JavaExample {
public static void main(String[ ] args) {
byte num;
num = 113;
System.out.println(num);
}
}

Output:
113

Try the same program by assigning value assigning 150 value to variable num, you
would get type mismatch error because the value 150 is out of the range of byte
data type. The range of byte as I mentioned above is -128 to 127.

short:

This is greater than byte in terms of size and less than integer. Its range is -32,768
to 32767.

37
✓ Default size of this data type: 2 byte

short num = 45678;

int:

Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
✓ Default size: 4 byte
✓ Default value: 0

Example:
class JavaExample {
public static void main(String[ ] args) {
short num;
num = 150;
System.out.println(num);
}
}

Output:
150

The byte data type could not hold the value 150 but a short data type can because it
has a wider range.

long:

Used when int is not large enough to hold the value, it has wider range than int
data type, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
✓ size: 8 bytes
✓ Default value: 0

38
Example:
class JavaExample {
public static void main(String[ ] args) {
long num = -12332252626L;
System.out.println(num);
}
}

Output:
-12332252626

double:

Sufficient for holding 15 decimal digits

✓ size: 8 bytes

Example:
class JavaExample {
public static void main(String[ ] args) {
double num = -42937737.9d;
System.out.println(num);
}
}

Output:
-4.29377379E7
float:

Sufficient for holding 6 to 7 decimal digits


✓ size: 4 bytes
class JavaExample {
public static void main(String[ ] args) {
float num = 19.98f;
System.out.println(num);
}
}

39
Output:
19.98
boolean:

holds either true of false.

class JavaExample {
public static void main(String[ ] args) {
boolean b = false;
System.out.println(b);
}
}

Output:
False

char:

holds characters.

✓ size: 2 bytes

class JavaExample {
public static void main(String[ ] args) {
char ch = 'Z';
System.out.println(ch);
}
}

Output:
Z

❖ Literals in Java

A literal is a fixed value that we assign to a variable in a Program.

40
int num=10;
Here value 10 is a Integer literal.

char ch = 'A';
Here A is a char literal

➢ Integer Literal

Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;

➢ Float Literals

Used for data type float and double.


double num1 = 22.4;
float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.

➢ Char and String Literal

Used for char and String type.


char ch = 'Z';
String str = "BeginnersBook";

Lesson 4. Operators in Java (Singh, n.d.)

One of the most important features of a computer is its ability yo calculate. We use
operands and operator in an expression. An operator is a character that represents
an action, for example + is an arithmetic operator that represents addition.

There are two types of expression: a) unary and b) binary


• Unary – an expression that uses unary operator where an operator has only
one operand, situated either on its left or right.

41
• Binary – an expression that uses binary operator where an operator has two
operands placed on both its sides.
• Ternary - the only JavaScript operator that takes three operands: a condition
followed by a question mark ( ? ), then an expression to execute if the
condition is true followed by a colon ( : ), and finally the expression to execute
if the condition is false.

Types of Operator in Java

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators

Table 3.2 Arithmetic Operators (Singh, n.d.)

42
Example of Arithmetic Operators

public class ArithmeticOperatorDemo {


public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

System.out.println("num1 + num2: " + (num1 + num2) );


System.out.println("num1 - num2: " + (num1 - num2) );
System.out.println("num1 * num2: " + (num1 * num2) );
System.out.println("num1 / num2: " + (num1 / num2) );
System.out.println("num1 % num2: " + (num1 % num2) );
}
}

Output:
num1 + num2: 120
num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0

2) Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=


num2 = num1 would assign value of variable num1 to the variable.
num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1

43
Example of Assignment Operators

public class AssignmentOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);

num2 += num1;
System.out.println("+= Output: "+num2);

num2 -= num1;
System.out.println("-= Output: "+num2);

num2 *= num1;
System.out.println("*= Output: "+num2);

num2 /= num1;
System.out.println("/= Output: "+num2);

num2 %= num1;
System.out.println("%= Output: "+num2);
}
}

Output:
= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

44
3) Auto-increment and Auto-decrement Operators (Unary Operators)

Table 3.3 Unary Operators (Singh, n.d.)

The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
• incrementing/decrementing a value by one
• negating an expression
• inverting the value of a boolean

++ and - -

num++ is equivalent to num=num+1;


num - - is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

public class AutoOperatorDemo {


public static void main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
System.out.println("num1++ is: "+num1);
System.out.println("num2-- is: "+num2);
}
}

Output:
num1++ is: 101
num2-- is: 199

45
4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.

Table 3.4 Logical Operators (Singh, n.d.)

Let’s say we have two boolean variables b1 and b2.


b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false
and it would return false if b1 is true.

Example of Logical Operators

public class LogicalOperatorDemo {


public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;
System.out.println("b1 && b2: " + (b1&&b2));
System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}
}

Output:
b1 && b2: false
b1 || b2: true
!(b1 && b2): true

46
5) Comparison (Relational) operators

Table 3.5 Comparison Operators (Singh, n.d.)

We have six relational operators in Java: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.

Example of Relational operators

Note: This example is using if-else statement which is our next lesson, if you are
finding it difficult to understand then refer if-else .
public class RelationalOperatorDemo {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
System.out.println("num1 and num2 are equal");
}
else{
System.out.println("num1 and num2 are not equal");
}
if( num1 != num2 ){
System.out.println("num1 and num2 are not equal");
}
else{

47
System.out.println("num1 and num2 are equal");
}
if( num1 > num2 ){
System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}
if( num1 >= num2 ){
System.out.println("num1 is greater than or equal to num2");
}
else{
System.out.println("num1 is less than num2");
}
if( num1 < num2 ){
System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}
if( num1 <= num2){
System.out.println("num1 is less than or equal to num2");
}
else{
System.out.println("num1 is greater than num2");
}
}
}

Output:
num1 and num2 are not equal
num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2

48
6) Bitwise Operators

Table 3.6 Bitwise Operators (Singh, n.d.)

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.

num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if
both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010
because in the binary form of num1 and num2 only second last bits are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if
either bit is 1, else it returns 0. In our case it would return 31 which is 00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they
are not equal, else it returns 0. In our example it would return 29 which is equivalent
to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In
our example it would return -12 which is signed 8 bit equivalent to 11110100

49
num1 << 2 is left shift operator that moves the bits to the left, discards the far left
bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is
equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift operator
that is the reason bits are moving two places to the left side. We can change this
number and bits would be moved by the number of bits specified on the right side of
the operator. Same applies to the right side operator.

num1 >> 2 is right shift operator that moves the bits to the right, discards the far right
bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent
to 00000010

Example of Bitwise Operators

public class BitwiseOperatorDemo {


public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


System.out.println("num1 & num2: "+result);

result = num1 | num2;


System.out.println("num1 | num2: "+result);

result = num1 ^ num2;


System.out.println("num1 ^ num2: "+result);

result = ~num1;
System.out.println("~num1: "+result);

result = num1 << 2;

50
System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}
Output:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.


num1 & num2 compares corresponding bits of num1 and num2 and generates
1 if both bits are equal, else it returns 0. In our case it would return: 2 which is
00000010 because in the binary form of num1 and num2 only second last bits
are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates
1 if either bit is 1, else it returns 0. In our case it would return 31 which is
00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates
1 if they are not equal, else it returns 0. In our example it would return 29 which
is equivalent to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to
0. In our example it would return -12 which is signed 8 bit equivalent to
11110100

51
num1 << 2 is left shift operator that moves the bits to the left, discards the
far left bit, and assigns the rightmost bit a value of 0. In our case output is 44
which is equivalent to 00101100

Example of Bitwise Operators

public class BitwiseOperatorDemo {


public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


System.out.println("num1 & num2: "+result);

result = num1 | num2;


System.out.println("num1 | num2: "+result);

result = num1 ^ num2;


System.out.println("num1 ^ num2: "+result);

result = ~num1;
System.out.println("~num1: "+result);

result = num1 << 2;


System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}

Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

52
7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the
result.

Syntax:
variable num1 = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to the
variable num1 else the second value is assigned to the num1.

Example of Ternary Operator

public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}

Output:
num2: 200
num2: 100
Check out these related java programs:

53
Operator Precedence in Java

This determines which operator needs to be evaluated first if an expression has


more than one operator. Operator with higher precedence at the top and lower
precedence at the bottom.

Unary Operators
++ – – ! ~
Multiplicative
* /%
Additive
+ –
Shift
<< >> >>>
Relational
> >= < <=
Equality
== !=
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
|
Logical AND
&&
Logical OR
||
Ternary
?:
Assignment
= += -= *= /= %= > >= < <= &= ^= |=

54
Type Conversion

When evaluating an arithmetic expression especially mixed expression especially


when operators used a mixed operands, the integer value is treated as a floating-point
value with a zero decimal. When the result value is treated as another data type we
called it as implicit type coercion. To avoid it we convert using the Java explicit type
conversion using a cast operator, known as type conversion or type casting.

Syntax:

(dataTyopeName) (expression)

Example:

(int) (7.9) = 7
(double) (25) = 25.0
(double) (15 / 2 ) = 7.0

Things to Remember before with Java Programming:

• Store data into the computer’s memory with Named Constants and
Variables
o instruct the computer to allocate memory;
o include statements in the program to put the data into the
allocated memory.
• Put data into the variables with either of the two cited below
o Use an assignment statement
o Use input (read) statements
• Declare and initialize variables

Lesson 5. Input (read) Statement (Malik, n.d.)

In this section we learn how to put data into a variables from a standard input device
using Java’s input (or read) statement (Malik, n.d.).

55
✓ Reading Data Using the Scanner class

The Scanner class is used to get user input, and it is found in


the java.util package.

Using the class, we first we create an input stream object and associate it with the
standard input device.

Syntax: Scanner object var = new Scanner (System.in);

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings (W3schools, 2018)

Example

import java.util.Scanner; // Import the Scanner class


class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a
Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output
user input
}

To read other types, look at the table below:

56
Table 3.7 Input Types (Singh, n.d.)

In the example below, we use different methods to read data of various types:

Example

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

57
Lesson 6. Package, Classes, Methods and the import
Statement (Malik, n.d.)

Only a small number of operations, such as arithmetic and assignment operations, are
explicitly defined in Java. Many of the methods and identifiers needed to run a Java
program are provided as a collection of libraries, called packages.

A package is a collection of related classes. moreover, every package has a name.

In Java, class is a broadly used term. The term class is used to:

✓ create Java programs, either application or applet;


✓ group a set of related operations;
✓ allow users to create their own data types.

A lot of operations can be done and customized by users. These operations is


implemented using the Java mechanism of methods. Method is a set of instructions
designed to accomplish a specific task. If, for example, the name of the method
implementing the operation of one number raised to the power of another is pow. This
and other mathematical methods are contained in the class Math. The name of the
package containing the class Math is java.lang.
The package java.util contains Scanner class. The class contains the methods shown
in Table 4.6.

To make use of the existing classes, methods and identifiers, we must tell the program
which package contains the appropriate information. The import statement helps us
to do this. To import the contents of a package is:
Syntax: import packageName.*;

Example:

import java.util.*;

To import a specific class from a package, we can specify the name of the class in
place of the * (asterisk).

58
Example:

import.util.Scanner;

if we use the character * to import, the compiler determines the relevant class/es
use in the program.

Lesson 7. Creating a Java Application Program (Malik, n.d.)


In this lesson we are to learn how to create a complete Java application program. The
basic unit of a Java program is called class. A Java application program is defined as
a collection of one or more classes, while a class is a collection of methods and data
members. As previously defined, method is a set of instructions designe to perform a
specific task. A lot of methods are written and stored as part of java packages, they
called standard or predefined methods. To accomplish more tasks of your own need,
programmers must learn to write their own mthods.

One of the classes in Java application program must have the method called main. If
the program has only one class, it should contain the method main.

Statements to declare memory spaces (named constant, and variables), statements


to create input stream objects, statements to manipulate data (such as assignments),
and statement to input data will be placed within the class.

Statements to declare named constants and input stream objects are usually placed
outside the method main, and statements to declare variables are usually placed
within the method main. Statement to manipulate data and input and output
statements are placed within the method main.

Syntax of a class to create a Java application program is:

public class ClassName {


classMembers
}

59
A ClassName is a user-defined Java identifier; classMembers consists of the data
members and methods (such as the method main). In Java, public and class are
reserved words. (typically, the name of a class begin with an uppercase letter).

Syntax of the method main is:

public static void main(String[ ] srgs)


{
Statement 1
.
.
Statement n
}
Because the programming instructions are located in the method main, let us have a
bit of discussion about his.

The basic parts of the method main are heading and the body.

The first line of the method main is: public static void main(String[ ] args) called
heading.

The statements enclosed in curly braces { and } form the body of the method main.
The body of the main method consists of two types pf statements:

✓ Declaration statements where we declare variables


✓ Executable statements where performances like calculation, manipulation of
data, create output, accept input, and the like are done.

Note: all variables or identifiers can be declare anywhere within the method, but they
must be declared before they can be used.

60
Assessment Task 3

Test your knowledge.


Answer to the following:

1. Write a program that produces the following output:

*********************************************
* Programming Assessment 3 *
* Object-Oriented Programming 2 *
* Programmer: (your full name) *
* Date Submitted: enter date *
********************************************

2. Write a program that prompts the user to input the elapsed time
for an event in second. The program then outputs the elapsed time
in hours, minutes, and seconds. For example: if the elapse time is
9630 seconds, then the output is 2:40:30).
3. To make a profit, a local store marks up the prices of its items by a
certain percentage. Where a Java program that reads the original
price of the item sold, the percentage of the marked-up price, and
the sales tax rate. The program then outputs the original price of
the item, the marked-up percentage of the item, the store’s selling
price of the item, the sales tax rate, the sales tax, and the final
price of the item. (The final price of the item is the selling price plus the sales tax).
4. Write a program that prompts the user to input the amount of rice,
in pounds, in a bag. The program outputs the number of bags
needed to store one metric ton of rice.

61
Assessment Task 3

Test your knowledge.


Answer to the following:

5. Suppose x, y and z are int variables and w and t are double


variables. What is the value of each variable after the last
statement executes?
x = 17;
y = 15;
x = x + y / 4;
z = x % 3 + 4;
w = 17 / 3 + 6.5;
t = x / 4.0 + 15 % 4 – 3.5;

6. Suppose x and y and z are int variables and x = 25 and y = 35.


What is the output of each of the following statements?
a) System.out.println(x + ‘ ‘ + y);
b) System.out.println(x + “ “ + y);

62
Summary

We have learned from this Module the basics of Java. We have been introduced to the
Java programming language, where two question are considered: they are: “what is a
computer program?” And “what is programming?” it was clarified that a computer
program or program, is a sequence of statements intended to accomplish a task.
Programming, on the other hand is a process of planning and creating a program.

An analogy was also considered to help us understand the nature of programming. It


is like cooking. A recipe is like a program and everyone with some cooking experience
can agree and follow.

We were also advised and taught that a chef cannot be a good chef by just merely
reading the recipes which is true to programming. We must have the fundamental
knowledge of the language, we are able to execute and test the program we wrote to
make sure that each program we do does what it is supposed to do.

References

Malik, D.S. (n.d.). Java Programming: From Problem Analysis to Program Design. 5th
Edition, Cengage Learning Asia Pte Ltd.

Singh, C. (n.d.). Introduction to Java programming. Retrieved 7 January 2021, from


https://beginnersbook.com/2013/05/java-introduction/

W3schools. (n.d.). Java User Input (Scanner class). (2021). Retrieved 12 January 2021,
from https://www.w3schools.com/java/java_use

63
MODULE 4
OBJECTS AND INPUT/OUTPUT

Introduction

We were introduced to the Basic Elements of Java programs, including some symbols
and identifiers, primitive data types, operators and its order of precedence. We were
also briefly introduced to class Scanner for inputting data into a program, and general
rules on java programming and its structure.

In this module, we will be introduced to objects, more about input and output and how
to use predefined methods in Java programs. We will also learn some details on how
to use class String to process strings.

Learning Outcomes

At the end of this module, students should be able to:

1. Learn about objects and reference variables;


2. Explore how to use predefined methods in a program;
3. Become familiar with class String;
4. Learn how to format output using the method printf;
5. Learn how to use input and output dialog boxes in a program;
6. Become familiar with the String and method format;
7. Examine ways to output using output statements; and
8. Learn debugging by understanding error messages.

64
Lesson 1. Objects and Reference Variables (Malik, n.d.)

Three terms that we will encounter repeatedly are variables, reference variables, and
objects. To be familiar with these terms, we are to define and to see their differences.

Reference variables are variables that store the address of a memory space. In Java,
any variable declared using a class is a reference variable (Malik, n.d.).

Consider the following statements:

Int x;
String str;
x = 45;
str = “Java Programming”;

Here variable str is a reference variable since it was declared using class String,
hence str is a reference variable of a String type.

Figure 4.1 Example program illustration


Source: (Malik, n.d.)

The memory space 2500, where the string (literal) “Java Programming” is stored is
called a String object. We call string object as instance of the class String as illustrated
in Figure 4.2.

Figure 4.2 Example program illustration


Source: (Malik, n.d.)

65
Difference Between Reference and Object in Java (Ask any Difference, n.d.)

Objects and References are both terms associated with a ‘class’ in the java
programming language. A class is a blueprint or a template that provides instructions
on how to create objects. The object established itself on this structure, and the
necessary fields according to that class template are filled.

A memory reference, is simply as the name states, a reference to the memory slot.
The user can use the memory reference to find out the address of where the object is
stored.

The difference between an object and a reference is that, an object is an instance


of a class, and is stored in a certain memory slot. A ‘reference’ points to the place
where the ‘objects’ variables and methods are stored.

Table 4.1 Comparison Table Between Reference and Object in Java (Malik, n.d.)

66
What is Reference in Java?

A reference is something that provides the address to the place where the object
memory has been allocated.

The object is never directly used; we instead assign reference variables, which
indirectly act as a middle man, between the object being called and the object stored
in the memory.

Java also allows for 4 different types of references –

1. Strong Reference.
2. Weak Reference.
3. Soft Reference.
4. Phantom Reference

A reference is created within the format for the creation of an object from a class –

ClassName reference_variable = new ClassName(with parameter);

Here the ‘reference_variable’ is the value assigned to the reference. This value
cannot be changed, and it is of one data type only. However, an important thing to
note about references is that the same references can be assigned to multiple objects
if needed.

What is Object in Java?


An object is simply an instance of the class. It represents the structure of the class
and follows the blueprint instructions for all the elements present within it, such as
methods and variables.

Objects are seen to have states and behaviors. Here, states are an ‘abstract’ entity,
which contain all the properties of the objects, as well as the values of those
properties. Simply put, a state for a human being would be – name, race, age etc.

Behaviors binds the structure of the object. They bind the relationships between the
attributes, so as to allow the object to perform functions/operations when it is called.

67
In simple terms, we could say that for a human being, the behaviors would be- cooking
food, walking, talking etc.

The ‘Object’ is created using 3 distinguishable steps-


1. Declaration
2. Instantiation
3. Initialization
In the first step, declaration, a variable name of object type is declared, which goes
onto become the reference for the object memory.

In the second step, instantiation, we have a keyword, namely ‘new’, which is used to
create the object.

In the third step, initialization, we have the ‘new’ keyword which is followed by a
‘constructor’, which has the same name as the class from which the object is being
created, along with parameters. This calls the constructor to help us initialize the new
object that we are creating.

The compiled format for creating the object is as such –

ClassName reference_variable = new ClassName(with parameter) ;

Here, the reference is created using ‘reference_variable’, and ClassName(with


parameter) is to call the constructor.

Example – Person stu1 = new Person();

Here, Person refers to the class, stu1 is the value of the reference variable that points
to the new object being created, and Person() is the constructor

Main Differences Between Reference and Object in Java


• An object is an instance derived from the structure of a class. A
reference is just a variable that points to the location of the object in
memory.
• An object is created with a certain format – “ClassName
reference_variable = new ClassName(with parameter);”. A reference
is created alongside the object creation, within the format.

68
• An object contains elements such as variables and methods, as well as
states and behaviors. A reference simply contains a sequence of bits.
• An object is never directly seen within the program, instead, the
reference variable is assigned, and a reference to the object is created.
• An object is a real – world entity that holds some memory. A reference
has no real meaning and its behavior is the same as that of a name of a
person.

Objects and references are both intertwined when it comes to their functioning. An
object cannot be directly seen or assigned, so instead we use reference to allocate a
name or a variable that acts as a middle man.

Reference allows us to indirectly call the object, as it knows the address of where the
object is stored. Whilst creating an object, we can see that the reference is created
right alongside it, and as it is a basic and simple format, so it saves time and is
efficient.

Lesson 2. Input/Output

A program performs three basic operations: it gets data into the program; it
manipulates the data; and it outputs the result. Because we are writing programs for
input/output (I/O) its quite xcomplex, Java offers extensive support for I/O operations
by providing substantial number of I/O classes, such as the class Scanner (Malik, n.d.).

In this lesson we will be introduced how to do some operations in I/O, we will:


1. Learn how to format output using the method printf;
2. Learn the ways to input data and how to output results;
3. Learn how to format the output of decimal numbers to specific number
of decimal places.
4. Learn how to instruct the program to read data from, or write output to
a file.

69
Formatting output with printf
In this lesson, we'll demonstrate different examples of formatting with
the printf() method. The method is part of the java.io.PrintStream class and provides
String formatting similar to the printf() function in C.

1. Syntax (Baeldung, 2018)

We can use one of the following PrintStream methods to format the output:

System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);

We specify the formatting rules using the format parameter. Rules start with
the ‘%' character.

Let's look at a quick example before we dive into the details of the various formatting
rules:

System.out.printf("Hello %s!%n", "World");

This produces the following output:

Hello World!
As shown above, the format string contains plain text and two formatting rules. The
first rule is used to format the string argument. The second rule adds a newline
character to the end of the string.

1.1 Format Rules

Let's have a look at format string more closely. It consists of literals and format
specifiers. Format specifiers include flags, width, precision, and conversion
characters in the following sequence:

%[flags][width][.precision]conversion-character
Specifiers in the brackets are optional.

70
Internally, printf() uses the java.util.Formatter class to parse the format string and
generate the output. Additional format string options can be found in the Formatter
Javadoc.

1.2. Conversion Characters

The conversion-character is required and determines how the argument is


formatted. Conversion characters are only valid for certain data types. Some common
ones are:

• s – formats strings
• d – formats decimal integers
• f – formats the floating-point numbers
• t– formats date/time values

We'll explore these and a few others later in the article.

1.3. Optional Modifiers

The [flags] define standard ways to modify the output and are most common for
formatting integers and floating point numbers.

The [width] specifies the field width for outputting the argument. It represents the
minimum number of characters written to the output.

The [.precision] specifies the number of digits of precision when outputting


floating-point values. Additionally, we can use it to define the length of a substring to
extract from a String.

2. Line Separator

To break the string into separate lines, we have a %n specifier:

System.out.printf("baeldung%nline%nterminator");

71
The code snippet above will produce the following output:

baeldung
line
terminator
The %n separator printf() will automatically insert the host system's native line
separator.

3. Boolean Formatting

To format boolean values, we use the %b format. It works the following way: If the
input value is true, the output is true. Otherwise, the output is false.

So, if we do:

System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");
Then we'll see:

false
FALSE
TRUE
true
Notice that we can use %B for uppercase formatting.

4. String Formatting

To format a simple string, we'll use the %s combination. Additionally, we can make
the string uppercase:

printf("'%s' %n", "baeldung");


printf("'%S' %n", "baeldung");
And the output is:

'baeldung'

72
'BAELDUNG'
Also, to specify a minimum length, we can specify a width:

printf("'%15s' %n", "baeldung");


Which gives us:

' baeldung'

If we need to left-justify our string, then we can use the ‘-‘ flag:

printf("'%-10s' %n", "baeldung");


And the output is:

'baeldung '

Even more, we can limit the number of characters in our output by specifying
a precision:

System.out.printf("%2.2s", "Hi there!");


The first ‘x' number in %x.ys syntax is the padding. ‘y' is the number of chars. For our
example here, the output is Hi.

6. Char Formatting

The result of %c is a Unicode character:

System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');

The capital letter C will uppercase the result:

s
S
But, if we give it an invalid argument, then Formatter will
throw IllegalFormatConversionException.

73
6. Number Formatting
6.1. Integer Formatting
The printf() method accepts all the integers available in the language; byte, short, int,
long and BigInteger if we use %d:

System.out.printf("simple integer: %d%n", 10000L);

With the help of the ‘d' character, we'll have:

simple integer: 10000

In case we need to format our number with the thousands separator, we can use
the ‘,' flag. And we can also format our results for different locales:

System.out.printf(Locale.US, "%,d %n", 10000);


System.out.printf(Locale.ITALY, "%,d %n", 10000);

As we see, the formatting in the US is different than in Italy:

10,000
10.000

6.2. Float and Double Formatting

To format a float number, we'll need the ‘f' format:

System.out.printf("%f%n", 5.1473);

Which will output:

5.147300

Of course, the first thing that comes to mind is to control the precision:

System.out.printf("'%5.2f'%n", 5.1473);

Here we define the width of our number as 5, and the length of the decimal part is 2:

' 5.15'

74
Here we have one space padding from the beginning of the number to support the
predefined width.

To have our output in scientific notation, we just use the ‘e' conversion character:

System.out.printf("'%5.2e'%n", 5.1473);

And the result is the following:

'5.15e+00'

7. Date and Time Formatting

For date and time formatting, the conversion string is a sequence of two characters:
the ‘t' or ‘T' character and the conversion suffix. Let's explore the most common
time and date formatting suffix characters with the examples.

Definitely, for more advanced formatting we can use DateTimeFormatter which has
been available since Java 8.

7.1. Time Formatting

First, let's see the list of some useful suffix characters for Time Formatting:

• ‘H', ‘M', ‘S' – characters are responsible for extracting the hours, minutes
and second from the input Date
• ‘L', ‘N' – to represent the time in milliseconds and nanoseconds accordingly
• ‘p' – adds am/pm formatting
• ‘z' – prints out the timezone offset

Now, let's say we wanted to print out the time part of a Date:

Date date = new Date();


System.out.printf("%tT%n", date);

The code above along with ‘%tT' combination produces the following output:

13:51:15

75
In case we need more detailed formatting, we can call for different time segments:

System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date,


date);

Having used ‘H', ‘M', and ‘S' we get:

hours 13: minutes 51: seconds 15

Though, listing date multiple times is a pain. Alternatively, to get rid of multiple
arguments, we can use the index reference of our input parameter which is 1$ in
our case:

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n",


date);

Here we want as an output the current time, am/pm, time in milliseconds,


nanoseconds and the timezone offset:

13:51:15 pm 061 061000000 +0400

7.2. Date Formatting

Like time formatting, we have special formatting characters for date formatting:

• ‘A' – prints out the full day of the week


• ‘d' – formats a two-digit day of the month
• ‘B' – is for the full month name
• ‘m' – formats a two-digit month
• ‘Y' – outputs a year in four digits
• ‘y' – outputs the last two digits of the year

So, if we wanted to show the day of the week, followed by the month:

System.out.printf("%1$tA, %1$tB %1$tY %n", date);

Then using ‘A', ‘B', and ‘Y', we'd get:

Thursday, November 2018

76
To have our results all in numeric format, we can replace the ‘A', ‘B', ‘Y ‘ letters with
‘d', ‘m', ‘y':

System.out.printf("%1$td.%1$tm.%1$ty %n", date);

Which will result in:

22.11.18

Lesson 3. Parsing numeric strings (Malik, n.d.)

A string consisting of only an integer or a floating-point number, optionally preceded


by a minus sign, is called numeric string. For example. The following are numeric
strings:
“6723”
“-823”
“345.78”
“-782.675”
To process strings as numbers, we first must convert them into numeric form. Java
provided special methods to convert numeric strings into their equivalent numeric
form.
1. To convert string consisting of integer to a value of type int, we use this
syntax: Integer.parseInt(strExpresssion)
• Integer.parseInt(“6723”) = 6723
• Integer.parseInt(“-823”) = -823
2. To convert string consisting of a floating-point number to a value of type
float, we use the syntax: syntax: Float.parseFloat(strExpresssion)
• Float.parseFloat(“34.56”) = 34.56
• Float.parseFloat(“-542.97”) = -542.97
3. To convert string consisting of a floating-point number to a value of type
double, we use the syntax: syntax:
Double.parseDouble(strExpresssion)
• Double.parseDouble(“345.76”) = 345.78
• Double.parseDouble(“-782.873”) = -782.873

77
Note that Integer, Float, and Double are classes that contain methods to convert a
numeric string into number. These classes are called wrapper class. Moreover,
parseInt is a method od class Integer, similarly paseFloat is a method of the class Float
and parseDouble is a method of class Double.

Convert String to int using Integer.valueOf(String)

Integer.valueOf(String) works same as Integer.parseInt(String). It also converts a


String to int value. However there is a difference between
Integer.valueOf() and Integer.parseInt(), the valueOf(String) method returns an object
of Integer class whereas the parseInt(String) method returns a primitive int value. The
output of the conversion would be same whichever method you choose. This is how it
can be used:

String str="1122";
int inum = Integer.valueOf(str);

The value of inum would be 1122.

This method also allows first character of String to be a minus ‘-‘ sign.

String str="-1122";
int inum = Integer.valueOf(str);

Value of inum would be -1122.

Similar to the parseInt(String) method it also throws NumberFormatException when


all the characters in the String are not digits. For example a String with value “11aa22”
would throw an exception.

Lets see the complete code for conversion using this method.

78
Example of Java Convert String to int example using Integer.valueOf(String)

public class JavaExample{


public static void main(String args[]){
//String with negative sign
String str="-234";

//An int variable


int inum = 110;

/* Convert String to int in Java using valueOf() method


* the value of variable inum2 would be negative after
* conversion
*/
int inum2 = Integer.valueOf(str);

//Adding up inum and inum2


int sum = inum+inum2;

//displaying sum
System.out.println("Result is: "+sum);
}
}

Output:

79
Convert a String to int with leading zeroes

In this example, we have a string made up of digits with leading zeroes, we want to
perform an arithmetic operation on that string retaining the leading zeroes. To do this
we are converting the string to int and performing the arithmetic operation, later we
are converting the output value to string using format() method.

public class JavaExample{


public static void main(String args[]){
String str="00000678";
/* String to int conversion with leading zeroes
* the %08 format specifier is used to have 8 digits in
* the number, this ensures the leading zeroes
*/
str = String.format("%08d", Integer.parseInt(str)+102);
System.out.println("Output String: "+str);
}
}
Output:

80
Lesson 4. File I/O in Java (Beginnersbook, n.d.)
The tutorials are explained with the help of very basic and simple examples so that
even a beginner can learn with ease. I will continue to write more tutorials on I/O and
will add the links below.

Create File

In this lesson we will see how to create a file in Java using createNewFile() method.
This method creates an empty file, if the file doesn’t exist at the specified location and
returns true. If the file is already present then this method returns false. It throws:

IOException – If an Input/Output error occurs during file creation. SecurityException –


If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to the file.

Example code:
The below code would create a txt file named “newfile.txt” in C drive. You can change
the path in the below code in order to create the file in different directory or in different
drive.

package beginnersbook.com;
import java.io.File;
import java.io.IOException;

public class CreateFileDemo


{
public static void main( String[] args )
{
try {
File file = new File("C:\\newfile.txt");
/*If file gets created then the createNewFile()
* method would return true or if the file is
* already present it would return false
*/
boolean fvar = file.createNewFile();
if (fvar){
System.out.println("File has been created successfully");
}
else{
System.out.println("File already present at the specified
location");
}
} catch (IOException e) {

81
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}

Read File

How to read file in Java – BufferedInputStream


In this example we will see how to read a file in Java
using FileInputStream and BufferedInputStream. Here are the detailed steps that
we have taken in the below code:
❖ Created a File instance by providing the full path of the file(which we will read)
during File Object creation.
❖ 2) Passed the file instance to the FileInputStream which opens a connection to
the actual file, the file named by the File object file in the file system.
❖ Passed the FileInputStream instance to BufferedInputStream which creates
a BufferedInputStream and saves its argument, the input stream in, for later
use. An internal buffer array is created and stored in buf using which the read
operation gives good performance as the content is readily available in the
buffer.
❖ Used while loop to read the file. Method available() is used for checking the
end of the file as it returns 0 when the pointer reaches to the end of the file.
Read the file content using read() method of FileInputStream.

package beginnersbook.com;
import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
//Specify the path of the file here
File file = new File("C://myfile.txt");
BufferedInputStream bis = null;
FileInputStream fis= null;

try
{
//FileInputStream to read the file
fis = new FileInputStream(file);

/*Passed the FileInputStream to BufferedInputStream


*For Fast read using the buffer array.*/
bis = new BufferedInputStream(fis);

82
/*available() method of BufferedInputStream
* returns 0 when there are no more bytes
* present in the file to be read*/
while( bis.available() > 0 ){
System.out.print((char)bis.read());
}

}catch(FileNotFoundException fnfe)
{
System.out.println("The specified file not found" + fnfe);
}
catch(IOException ioe)
{
System.out.println("I/O Exception: " + ioe);
}
finally
{
try{
if(bis != null && fis!=null)
{
fis.close();
bis.close();
}
}catch(IOException ioe)
{
System.out.println("Error in InputStream close(): " +
ioe);
}
}
}
}

How to read file in Java using BufferedReader

In this lesson we will see two ways to read a file using BufferedReader.

❖ Method 1: Using readLine() method of BufferedReader class.


public String readLine() throws IOException
It reads a line of text.

❖ Method 2: Using read() method


public int read() throws IOException
It reads a character of text. Since it returns an integer value, it needs to be
explicitly cast as char for reading the content of file.

83
Complete example

Here I have two txt files myfile.txt and myfile2.txt. In order to demonstrate both the
ways to read file. I’m reading first file using readLine() method while the second file
is being read using read() method.

package beginnersbook.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileDemo {


public static void main(String[] args) {

BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader("B:\\myfile.txt"));

//One way of reading the file


System.out.println("Reading the file using readLine() method:");
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();
}

br2 = new BufferedReader(new FileReader("B:\\myfile2.txt"));

//Second way of reading the file


System.out.println("Reading the file using read() method:");
int num=0;
char ch;
while((num=br2.read()) != -1)
{
ch=(char)num;
System.out.print(ch);
}

}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try {
if (br != null)
br.close();
if (br2 != null)

84
br2.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
}
}

Write/Append File

How to write to a file in java using FileOutputStream

Earlier we saw how to create a file in Java. In this lesson we will see how to write to a
file in java using FileOutputStream. We would be using write()
method of FileOutputStream to write the content to the specified file. Here is the
signature of write() method.

public void write(byte[ ] b) throws IOException

It writes b.length bytes from the specified byte array to this file output stream. As you
can see this method needs array of bytes in order to write them into a file. Hence we
would need to convert our content into array of bytes before writing it into the file.

Complete Code: Writing to a File

In the below example we are writing a String to a file. To convert the String into an
array of bytes, we are using getBytes() method of String class.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileDemo {


public static void main(String[] args) {
FileOutputStream fos = null;
File file;
String mycontent = "This is my Data which needs" +
" to be written into the file";
try {
//Specify the file path here
file = new File("C:/myfile.txt");
fos = new FileOutputStream(file);

85
/* This logic will check whether the file
* exists or not. If the file is not found
* at the specified location it would create
* a new file*/
if (!file.exists()) {
file.createNewFile();
}

/*String content cannot be directly written into


* a file. It needs to be converted into bytes
*/
byte[] bytesArray = mycontent.getBytes();

fos.write(bytesArray);
fos.flush();
System.out.println("File Written Successfully");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
}
}

❖ How to write to file in Java using BufferedWriter

Earlier we discussed how to write to a file using FileOutputStream. In this lesson we


will see how to write to a file using BufferedWriter. We will be using write() method
of BufferedWriter to write the text into a file. The advantage of using BufferedWriter is
that it writes text to a character-output stream, buffering characters so as to provide
for the efficient writing (better performance) of single characters, arrays, and strings.

Complete example: Write to file using BufferedWriter

In this example we have a String mycontent and a file myfile.txt in C drive. We are
writing the String to the File with the help of FileWriter and BufferedWriter.

86
package beginnersbook.com;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileDemo {


public static void main(String[] args) {
BufferedWriter bw = null;
try {
String mycontent = "This String would be written" +
" to the specified File";
//Specify the file name and path here
File file = new File("C:/myfile.txt");

/* This logic will make sure that the file


* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file);


bw = new BufferedWriter(fw);
bw.write(mycontent);
System.out.println("File written Successfully");

} catch (IOException ioe) {


ioe.printStackTrace();
}
finally
{
try{
if(bw!=null)
bw.close();
}catch(Exception ex){
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}

❖ Append to a file in java using BufferedWriter, PrintWriter, FileWriter

In this lesson we will learn how to append content to a file in Java. There are two ways
to append:

1) Using FileWriter and BufferedWriter: In this approach we will be having the


content in one of more Strings and we will be appending those Strings to the

87
file. The file can be appended using FileWriter alone however
using BufferedWriter improves the performance as it maintains a buffer.
2) Using PrintWriter: This is one of best way to append content to a file.
Whatever you write using PrintWriter object would be appended to the File.

1) Append content to File using FileWriter and BufferedWriter

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class AppendFileDemo
{
public static void main( String[] args )
{
try{
String content = "This is my content which would be appended " +
"at the end of the specified file";
//Specify the file name and path here
File file =new File("C://myfile.txt");

/* This logic is to create the file if the


* file is not already present
*/
if(!file.exists()){
file.createNewFile();
}

//Here true is to append the content to file


FileWriter fw = new FileWriter(file,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();

System.out.println("Data successfully appended at the end of file");

88
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:

Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my fileThis is my content which


would be appended at the end of the specified file

2) Append content to File using PrintWriter

PrintWriter gives you more flexibility. Using this you can easily format the content
which is to be appended to the File.

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class AppendFileDemo2
{
public static void main( String[] args )
{
try{
File file =new File("C://myfile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");

89
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();

System.out.println("Data successfully appended at the end of file");

}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}

Output:

Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my file


This is first line
This is the second line
This is third line
Delete/Rename File

❖ How to delete file in Java – delete() Method

In this lesson we will see how to delete a File in java. We will be using
the delete() method for file deletion.

90
public boolean delete()
This method returns true if the specified File deleted successfully otherwise it
returns false.

Here is the complete code:

import java.io.File;
public class DeleteFileJavaDemo
{
public static void main(String[] args)
{
try{
//Specify the file name and path
File file = new File("C:\\myfile.txt");
/*the delete() method returns true if the file is
* deleted successfully else it returns false
*/
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete failed: File didn't delete");
}
}catch(Exception e){
System.out.println("Exception occurred");
e.printStackTrace();
}
}
}

Output:

myfile.txt is deleted!
❖ How to rename file in Java – renameTo() method

Earlier we saw how to create, read, write, append to a file in java. In this lesson we
will see how to rename a file in java using renameTo() method.

public boolean renameTo(File dest)

It returns true if the file is renamed successfully else it returns false. It throws
NullPointerException – If parameter dest is null.

91
Complete Example:

import java.io.File;
public class RenameFileJavaDemo
{
public static void main(String[] args)
{
//Old File
File oldfile =new File("C:\\myfile.txt");
//New File
File newfile =new File("C:\\mynewfile.txt");
/*renameTo() return boolean value
* It return true if rename operation is
* successful
*/
boolean flag = oldfile.renameTo(newfile);
if(flag){
System.out.println("File renamed successfully");
}else{
System.out.println("Rename operation failed");
}
}
}

Output:
File renamed successfully

92
Assessment Task 4

Test your knowledge.


Give and discuss in writing your answer to the following questions:

1. Write a program that prompts the user to enter the weight of a person in
kilograms and output the equivalent weight in pounds. Output both the
weights rounded to two decimal places. (Note that 1 kilogram = 2.2
pounds). Format your output with two decimal places.

2. The manager of a basketball stadium wants you to write a program that


calculates the total ticket sales after each game. There are four types of
tickets – box, sideline, premium, and general admission. After each game,
data is stored in a file in the following forms:
ticketPrice numberOfTicketsSold
…….
Sample data are shown below:
250 5750
100 28000
50 35750
25 18750
The first line indicates that the box ticket price is 250 pesos and that 5750
Tickets were sold at that price. Output the number of the tickets sold and
the total sale amount. Format your output with two decimal places.

93
3. Write a program that calculates and prints the monthly paycheck
for an employee. The net pay is calculated after taking the
following deductions:

Income tax: 15%


Value added tax 3.5%
Social Security Service 5.75%
Medicare/Philhealth 2.75%
Coop 5%
Loan 75 pesos

Your program should prompt the user to print the gross amount of
the employee name. the output will be stored in a file. Format your
output to have two decimal places. A simple output follows:

Juan dela Cruz


Gross Income: PhP 3575.00
Income tax: PhP 536.25
Value added tax: PhP 125.13
Social Security Service: PhP 205.56
Medicare/Philhealth: PhP 98.31
Coop: PhP 178.75
Loan: PhP 75.00
Net Pay: PhP 2356.00

94
4. Three employees in a company are up for a special pay increase. You
are given a file say Ch3_Ex7Data.txt, with the following data:
Penduko Pedro 65789.87 5
Kagalakan Maria 75892.56 6
Mandirigma Mario 74900.50 6.1

Each input line consists of and employee’s last name, first name,
current salary, and percent pay increase. For example in the first input
line, the last name of the employee is Penduko, first name is Pedro,
the current salary is 65789.87, and the pay increase is 5%. Write a
program that reads from the specified file and store the output in the
following form: firstName, lastName, updatedSalary. Format the
output of decimal numbers to two decimal places,

Summary

Module 4 touched and introduced the I/O functionalities that we should apply and use
as we create programs in Java language. We learned about objects, more about input
and output and how to use predefined methods in Java programs. We will also learn
some details on how to use class String to process strings.

95
References

Ask Any Difference. (2021). Retrieved 13 January 2021, from


https://askanydifference.com/difference-between-reference-and-object-in-java/

Baeldung.2021. Retrieved 13 January 2021, from https://www.baeldung.com/java-


printstream-printf

Java I/O tutorial with examples. (2021). Retrieved 13 January 2021, from
https://beginnersbook.com/java-io-tutorial-with-examples/

Malik, D.S. (n.d.) Java Programming: From Problem Analysis to Program Design. 5th
Edition, Cengage Learning Asia Pte Ltd.

- END OF MODULE FOR PRELIMINARY TERM PERIOD –


SUBMISSION OF THE ASSESSMENT AND EXAMINATION FOR PRELIM
PERIOD WILL BE ANNOUNCED VIA iLearnU LMS or GC
MAKE SURE TO CHECK THE DATES AND NOT FORGET TO TAKE IT AS
SCHEDULED

Congratulations!

96

You might also like