Java A Detailed Approach to Practical Coding (Step-By-Step Java Book 2)
Java A Detailed Approach to Practical Coding (Step-By-Step Java Book 2)
Nathan Clark
© Copyright 2018 Nathan Clark. All rights reserved.
No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of
the publisher, except in the case of brief quotations embodied in critical
reviews and certain other noncommercial uses permitted by copyright law.
Every effort has been made to ensure that the content provided herein is
accurate and helpful for our readers at publishing time. However, this is not
an exhaustive treatment of the subjects. No liability is assumed for losses or
damages due to the information provided.
Any trademarks which are used are done so without consent and any use of
the same does not imply consent or permission was gained from the owner.
Any trademarks or brands found within are purely used for clarification
purposes and no owners are in anyway affiliated with this work.
Books in this Series
Table of Contents
Introduction
1. Methods
2. Working with Arrays
3. Working with Numbers
4. Working with Strings
5. Classes and Objects
6. Inheritance
7. Polymorphism
8. Inner Classes
9. Anonymous Classes
10. Interfaces
11. File I/O Operations
12. Exception Handling
13. Logging in Java
Conclusion
About the Author
Introduction
This book is the second book in the Step-By-Step Java series. If you are
new to Java programming and you haven’t read the first book, I highly
suggest you do so first. It covers the fundamentals of getting started with
Java and takes you step by step through writing your very first program.
Methods are used to define a set of logical statements together. These sets
of statements are used for a defined purpose. For example, if you wanted to
add a set of numbers, you could define a method and then call that method
whenever you wanted to add numbers.
The general syntax of a method is shown below.
Returndatatype methodname(parameters)
{
//Block of code
return datavalue
}
In the above program, we are making the method more dynamic by having
the ability to pass any set of the values to the method.
With this program, the output is as follows:
The sum of the numbers is 7
In the above code, the arraysize is the number of elements that can be
defined for the array. Let’s now look at an example of how we can define an
array in Java.
Example 6: The following program shows how to work with arrays and
display the elements of the array.
public class Demo
{
public static void main(String args[])
{
// Declaring the Array
int[] arr=new int[3];
We can also define an array of different data types, other than the integer
data type. Let’s look at another example where we can define an array of
strings.
Example 7: The following program is used to showcase how to work with
string arrays.
public class Demo
{
public static void main(String args[])
{
// Declaring the Array
String[] arr=new String[3];
In the above definition, the values for the array are defined in the
parenthesis { }. Let’s now look at an example of this.
Example 10: The following program is shows how to iterate through the
elements of the array.
public class Demo
{
public static void main(String args[])
{
int[] arr=new int[5];
for(int i=0;i<5;i++)
arr[i]=i;
for(int i=0;i<5;i++)
System.out.println("The value of arr[" + i + "] is " +arr[i]);
}
}
Example 12: The following program shows how to iterate through a two
dimensional array.
public class Demo
{
public static void main(String args[])
{
int[][] arr = new int[3][2];
// Defining the multidimensional array
arr[0][0] = 1;
arr[0][1] = 2;
arr[1][0] = 3;
arr[1][1] = 4;
arr[2][0] = 5;
arr[2][1] = 6;
Table 1: Numbers
Data Type Description
int This data type is used to define a signed integer that
has a range of values from -2,147,483,648 to
2,147,483,647
short This data type is used to define a signed integer that
has a range of values from -32,768 to 32,767
long This data type is used to define a signed long
integer that has a range of values from
-9223372036854775808 to 9223372036854775807
float This data type is used to define a single-precision
floating point type that has a range of values from
-3.402823e38 to 3.402823e38
double This data type is used to define a double-precision
floating point type that has a range of values from
-1.79769313486232e308 to 1.79769313486232e308
Example 14: The following program shows the basic use of numbers in
Java.
public class Demo
{
public static void main(String args[])
{
// Defining a int number
int a = -10;
// Defining a short number
short c = 30;
// Defining a long number
long d = -10000;
// Defining a ulong number
float g = 12.22F;
// Defining a double number
double h = 33.3333;
There are a variety of functions available in Java that allow you to work
with numbers. Let’s look at them in more detail.
Table 2: Number Functions
Function Description
Abs() This is used to return the absolute value of a
number
Ceiling() This returns the smallest integral value that is
greater than or equal to the specified decimal
number
Floor() This returns the largest integer that is less than or
equal to the specified decimal number
Max() This function returns the maximum of two numbers
Min() This function returns the minimum of two numbers
Pow() This returns a number raised to the specified power
Round() This rounds a decimal value to the nearest integral
value
Sqrt() This function returns the square root of a number
Sin() This returns the Sine value of a particular number
Tan() This returns the Tangent value of a particular
number
Cos() This returns the Cosine value of a particular number
Example 15: The following program is used to showcase the abs function.
public class Demo
{
public static void main(String args[])
{
// Defining a number
int a = 1000;
Example 21: The following program is used to show the round function.
public class Demo
{
public static void main(String args[])
{
double a=2.2;
Example 24: The following program is used to showcase the tan function.
public class Demo
{
public static void main(String args[])
{
double a=45;
There are a variety of functions available in Java to work with strings. Let’s
look at them in more detail.
Example 27: The following program is used to show the length function.
public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The length of the string is " + str.length());
}
}
With the above program:
We are using the ‘length’ method to get the length of the string.
With this program, the output is as follows:
The length of the string is 11
Where:
‘classname’ is the name given to the class.
The class modifier is the visibility given to either the member or
function of a class, which can be private, public or protected.
We then define the various data members of a class, each of which
can have a data type.
We then have the functions of the class, each of which can accept
parameters and also return values of different data types.
Let’s look at a quick definition of a class.
class Student
{
public int studentID;
public String studentName;
}
In the above code the ‘student1’ is the variable, which of the type ‘Student’.
We have now defined values to the properties. Let’s look at an example of
how to define classes and objects.
Example 36: The following program shows how to use classes and
objects.
// Here we are defining the class
class Student
{
public int studentID;
public String studentName;
}
Example 37: The following program is used to show how to use member
functions.
// Here we are defining the class
class Student
{
public int studentID;
public String studentName;
stud.studentID=1;
stud.studentName="John";
Now let’s look at a way we can use member functions to take values from
the main program.
Example 38: The following program shows how to use member functions
in another way.
// Here we are defining the class
class Student
{
public int studentID;
public String studentName;
stud.Input(1,"John");
stud.studentID=1;
stud.studentName="John";
One can also define multiple classes in a program and make use of those
classes. Let’s look at an example of this.
class Employee
{
public int EmployeeID;
public String EmployeeName;
public void Display()
{
System.out.println("The ID of the employee is "+this.EmployeeID);
System.out.println("The Name of the employee is "+this.EmployeeName);
}
}
stud.Input(1,"John");
stud.Display();
5.3 Constructors
Constructors are special methods in a class that are called when an object of
the class is created. The constructor has the name of the class.
The syntax of the constructor method is shown below.
public classname()
{
// Define any code for the constructor
}
Here the ‘static’ keyword is used to showcase that a static member is being
defined. If you want to initialize the static data member, this can be done
outside of the class as follows:
datatype classname::staticmembername = value;
public Student()
{
System.out.println("The constructor is being called");
this.studentID = 1;
this.studentName = "Default";
}
We have looked at classes and objects in the previous chapter, and have
seen how to define classes with properties and functions. Before we jump
into class inheritance, let’s quickly revisit how a typical class looks like.
Example 46: The following program is used to show how to use a simple
class.
// Here we are defining the class
class Student
{
public int studentID;
public String studentName;
public void Display()
{
System.out.println("The ID of the student is " + this.studentID);
System.out.println("The Name of the student is " + this.studentName);
}
}
Where:
The ‘Derived class’ is the class that will inherit the properties of the
other class, which is known as the ‘Base class’.
The ‘extends’ keyword is used to denote inheritance.
So if we had a base class with a property and a function as shown below:
Base class
{
Public or protected Property1;
}
And we define the derived class from the base class, the derived class will
have access to the property.
Note that the property and function needs to have the access modifier as
either public or protected. This is discussed in greater detail in the “Access
modifiers” section.
Derived class extends Base Class
{
// No need to define property1, it will automatically inherit these.
}
So now we have seen how we can use derived and base classes and this is
known as inheritance.
And we define the derived class from the base class, the derived class will
have access to the property and the method as well.
Note that the property and method needs to have the access modifier as
public or protected. As mentioned, this is discussed in greater detail in the
“Access modifiers” section.
Derived class extends Base Class
{
// No need to define property1 and Method1, it will automatically inherit these.
}
Example 48: The following program shows how to use an inherited class
with functions.
class Person
{
public String Name;
public int ID;
public void Display()
{
System.out.println("The ID of the person is " + this.ID);
System.out.println("The Name of the person is " + this.Name);
}
}
We can also redefine the Display function in the Student class. Looking at
the above example, you will notice that the Display function in the Person
class has the display text as ID and name of the Person. But suppose we
wanted to have the display name as Student ID and Student name in the
student class, we can do this by redefining the Display function.
So let’s look at an example of this.
public Person()
{
System.out.println("This is the Person class constructor");
}
}
public Student()
{
System.out.println("This is the Student class constructor");
}
}
From the program output, we can see that the base class constructor gets
called first and then the derived class constructor.
7. Polymorphism
Polymorphism refers to classes, in which base and derived classes can have
the same functions with the same names. But which gets called depends on
the type of class from which the function gets called.
So let’s say that we have a base class as defined below.
class baseclassA
{
MethodA() { }
}
If we then call FunctionA, the program would actually call FunctionA that
is defined in the derived class and not the one in the base class.
objA.FucntionA();
But now let’s look at the same example and make a slight tweak to it. This
time, we will create a type of the base class to reference an object of the
derived class.
In Java, we have the ability to define one class inside of another. The
embedded class acts like a property of the outer class. The embedded class
is also known as the inner class.
The following code shows the way inner classes can be defined.
Class outer
{
Class Inner
{
}
}
Let’s look at the first example of how we can define inner classes.
We can also create an instance of the inner object from within the main
program. The next example shows how we can achieve this.
Example 54: This program shows how to create an object of the inner
class from the main program.
class Outer
{
class Inner
{
public int innerID;
}
public void DisplayInner()
{
Inner inobj=new Inner();
inobj.innerID=1;
System.out.println("The value of the ID of the inner class is "+inobj.innerID);
}
}
Outer.Inner.innerID=2;
System.out.println("The value of the inner id is "+ Outer.Inner.innerID);
}
}
Anonymous classes help to define a class and initiate it at the same time.
This is good if we want to use a class only once. Anonymous classes are
useful for defining local classes, which are not needed at the global level.
The anonymous class must implement an interface or an abstract class.
The general syntax of this is given below.
new interface-or-class-name() { class-body }
Let’s look at another example, but this time let’s also add properties to the
class.
It is important that the classes need to ensure that all methods that are
declared in the interface are defined accordingly. Let’s now look at an
example of how interfaces can be used.
We can also make a class inherit multiple interfaces at one time. Let’s look
at an example of this.
Example 60: The following program showcases how classes can use
multiple interfaces.
interface DisplayInterface
{
public void Display();
}
interface DisplayNameInterface
{
public void DisplayName();
}
Properties can also be define in interfaces, but they need to be either static
or final. Let’s look at an example of this.
interface DisplayNameInterface
{
public void DisplayName();
}
Interfaces can also extend each other just like classes. Let’s look at an
example of this.
Java has a variety of classes that can be used in File I/O operations. It is
important for any programming language to have the support for File I/O
operations and Java has that support built-in. There are various classes that
are available in Java that work with files. Let’s look at the first class, which
is the ‘File’ class.
Example 63: The following program shows the way to use the file class.
import java.io.File;
Example 64: The following program is used to showcase the way to use
list files in a directory.
import java.io.File;
Example 65: The following program shows how to use the file class to get
file details.
import java.io.File;
Example 66: The following program is used to showcase the way to use
the FileOutputStream class.
import java.io.*;
Example 67: The following program shows the way to use the
FileInputStream class.
import java.io.*;
Example 69: The following program is used to showcase how to use the
DataOutputStream class.
import java.io.*;
If you now open the Sample.txt you will have the character ‘B’ written to
the file.
Example 70: The following program shows the way to use the
DataInputStream class.
import java.io.*;
The above program will read the first byte from the Sample.txt file.
Example 71: The following program is used to showcase the way to use
the FileWriter class.
import java.io.*;
With this program, the output will be as below. However, the output
depends on the contents of the file.
Hello World
12. Exception Handling
Example 73: The following program showcases the way to use the
Exception handling blocks.
import java.io.*;
Table 4: Exceptions
Exception Description
IOException This is used to handle I/O errors
IndexOutOfBoundsException This is used to handle errors
generated when a method refers to
an array index out of range
NullPointerException This is used to handle errors
generated from referencing a null
object
System.DivideByZeroException This is used to handle errors
generated from dividing a
dividend with zero
OutOfMemoryException This is used to handle errors
generated from insufficient free
memory
StackOverflowError This is used to handle errors
generated from stack overflow
This means we could have written our earlier program in the following way.
Example 74: The following program is used to showcase the way to use
the in-built exceptions.
import java.io.*;
We can also use multiple catch blocks. The catch blocks would be
evaluated in sequential order, to determine which would be the best fit. An
example is shown below.
Example 75: The following program shows how to use multiple catch
blocks.
import java.io.*;
Example 76: The following program is used to showcase the way to use
finally block.
import java.io.*;
Logging allows us to write data to the console in order to see the way the
program behaves as it executes. Logging can be used by incorporating the
‘java.util.logging.Logger’ class.
There are different log levels present. The log levels define the severity of a
message. The ‘level’ class is used to define which messages should be
written to the log. The following list shows the various log levels in
descending order:
SEVERE (highest)
WARNING
INFO
CONFIG
FINE
FINER
FINEST
Let’s look at a simple example first of how we would define and use a
logger for a class.
Example 77: The following program is used to showcase the way to use
the logger class.
import java.util.logging.Level;
import java.util.logging.Logger;
Let’s look at another example. But this time, we will see how we can pass
parameters to the logging method.
Example 78: The following program shows the way to use the logging
method with parameters.
import java.util.logging.Level;
import java.util.logging.Logger;
class Person
{
public String Name;
public int age;
}
Example 79: The following program shows how to use the logging
method with multiple parameters.
import java.util.logging.Level;
import java.util.logging.Logger;
class Person
{
public String Name;
public int age;
}
This has brought us to the end of this guide, but it doesn’t mean your Java
education should end here. If you enjoyed this guide, be sure to continue
your journey with the next book in the series, which looks at more
advanced topics and techniques while still being beginner friendly.
Lastly, this book was written not only to be a teaching guide, but also a
reference manual. So remember to always keep it near, as you venture
through this wonderful world of programming.
Good luck and happy programming!
About the Author