OOPJAVA Preelim
OOPJAVA Preelim
(JAVA)
Numeriano B. Aguado
VISION
MISSION
Course Requirements:
▪ Quiz - 20%
▪ Laboratory Exercise - 20%
▪ Recitation/Attendance - 20%
▪ Major Exams (ME) - 40%
Periodic Grade 100%
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
Introduction
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.
Learning Outcomes
1
7. Become familiar with structured and object-oriented programming
design methodologies.
❖ 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.
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.
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
Java is −
3
is distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
4
❖ Structure of Java Program
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
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 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:
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:
➢ Interface Section
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:
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:
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:
8
For example:
You can read more about the Java main() method here.
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:
When we follow and use the above elements in a Java program, the program looks
like the following.
CheckPalindromeNumber.java
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:
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.
✓ 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.
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.)
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:
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
15
create objects. For example, to create an Employee object, there should be an
Employee class.
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.
16
Assessment Task 1-1
75 0.20
95 0.35
85 0.15
65 0.30
17
Assessment Task 1-2
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
References
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
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.
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.
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
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
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:
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
Before we start learning Java, let us get familiar with common java terms.
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.
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:
❖ JVM Architecture
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.
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.
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.
JDK: JDK is a superset of JRE, it contains everything that JRE has along with
development tools such as compiler, debugger etc.
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.
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.
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.
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.
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.
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;
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.
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.
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.
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.
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.
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.
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
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:
✓ size: 8 bytes
Example:
class JavaExample {
public static void main(String[ ] args) {
double num = -42937737.9d;
System.out.println(num);
}
}
Output:
-4.29377379E7
float:
39
Output:
19.98
boolean:
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
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
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.
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.
42
Example of Arithmetic Operators
Output:
num1 + num2: 120
num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0
2) Assignment Operators
43
Example of Assignment Operators
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)
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 - -
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.
Output:
b1 && b2: false
b1 || b2: true
!(b1 && b2): true
46
5) Comparison (Relational) operators
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.
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
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
result = ~num1;
System.out.println("~num1: "+result);
50
System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}
Output:
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
result = ~num1;
System.out.println("~num1: "+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.
Output:
num2: 200
num2: 100
Check out these related java programs:
53
Operator Precedence in Java
Unary Operators
++ – – ! ~
Multiplicative
* /%
Additive
+ –
Shift
<< >> >>>
Relational
> >= < <=
Equality
== !=
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
|
Logical AND
&&
Logical OR
||
Ternary
?:
Assignment
= += -= *= /= %= > >= < <= &= ^= |=
54
Type Conversion
Syntax:
(dataTyopeName) (expression)
Example:
(int) (7.9) = 7
(double) (25) = 25.0
(double) (15 / 2 ) = 7.0
• 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
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
Using the class, we first we create an input stream object and associate it with the
standard input device.
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
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);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
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.
In Java, class is a broadly used term. The term class is used to:
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.
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 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.
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).
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:
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
*********************************************
* 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
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.
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.
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
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.).
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.
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.
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.
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.
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 –
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.
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.
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.
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
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.).
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.
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:
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.
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.
• s – formats strings
• d – formats decimal integers
• f – formats the floating-point numbers
• t– formats date/time values
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.
2. Line Separator
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:
'baeldung'
72
'BAELDUNG'
Also, to specify a minimum length, we can specify a width:
' baeldung'
If we need to left-justify our string, then we can use the ‘-‘ flag:
'baeldung '
Even more, we can limit the number of characters in our output by specifying
a precision:
6. Char Formatting
System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');
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:
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:
10,000
10.000
System.out.printf("%f%n", 5.1473);
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);
'5.15e+00'
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.
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:
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:
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:
Like time formatting, we have special formatting characters for date formatting:
So, if we wanted to show the day of the week, followed by the month:
76
To have our results all in numeric format, we can replace the ‘A', ‘B', ‘Y ‘ letters with
‘d', ‘m', ‘y':
22.11.18
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.
String str="1122";
int inum = Integer.valueOf(str);
This method also allows first character of String to be a minus ‘-‘ sign.
String str="-1122";
int inum = Integer.valueOf(str);
Lets see the complete code for conversion using this method.
78
Example of Java Convert String to int example using Integer.valueOf(String)
//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.
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:
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;
81
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}
Read File
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);
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);
}
}
}
}
In this lesson we will see two ways to read a file using BufferedReader.
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;
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader("B:\\myfile.txt"));
}
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
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.
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.
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;
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();
}
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");
}
}
}
}
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;
In this lesson we will learn how to append content to a file in Java. There are two ways
to append:
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.
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");
88
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
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();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:
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.
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.
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
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.
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:
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:
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
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.
Congratulations!
96