Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

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)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

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)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Java

A Detailed Approach to Practical


Coding

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.

An important aspect of this series, and your learning experience, is learning


by doing. Practical examples are proven to be the best way to learn a
programming language, which is why I have crammed as many examples
into this guide as possible. I have tried to keep the core of the examples
similar, so the only variable is the topic under discussion. This makes it
easier to understand what we are implementing. As you progress through
the chapters, remember to follow along with the examples and try them
yourself.
In this intermediate level guide we will delve more into further concepts of
Java. With each topic we will look at a detailed description, proper syntax
and numerous examples to make your learning experience as easy as
possible. Java is a wonderful programming language and I trust you will
enjoy this book as much as I enjoyed writing it.
So without further ado, let’s get started!
1. Methods

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 code:


The method can have an optional return type. Hence if the method is
intended to return a value to the main calling program, you could
define the type of the data value being returned.
You can also define optional parameters which can be sent to the
method. This is useful for making the method more dynamic in
nature.
Next you have the return statement to return the data value, if a value
needs to be return by the method.
Let’s now look at a simple example of how to define a method and call the
method accordingly.

Example 1: The following program is used to showcase how to use


methods.
public class Demo
{
// This is the main entry point of the Java program
static void AddNumbers()
{
int i=3;
int j=4;
System.out.println("The sum of the numbers is "+(i+j));
}
public static void main(String args[])
{
// Calling the Add method
AddNumbers();
}
}

In the above program we are:


Defining a method called ‘AddNumbers’ which has the purpose of
adding 2 integer numbers.
Next we call the ‘AddNumbers’ method in the main calling program.
With this program, the output is as follows:
The sum of the numbers is 7

Now let’s look at an example of how to pass parameters to a method.

Example 2: The following program is used to show how to use methods


with parameters.
public class Demo
{
// This is the main entry point of the Java program
static void AddNumbers(int i,int j)
{
System.out.println("The sum of the numbers is "+(i+j));
}
public static void main(String args[])
{
// Calling the Add method
AddNumbers(3,4);
}
}

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

Now let’s look at an example of how to pass parameters to a method and


also return a value to the main calling program.

Example 3: The following program shows how to use methods with


parameters and a return type.
public class Demo
{
// This is the main entry point of the Java program
static int AddNumbers(int i,int j)
{
return (i+j);
}
public static void main(String args[])
{
// Calling the Add method
System.out.println("The sum of the numbers is "+AddNumbers(3,4));
}
}

In the above program we are:


Defining the ‘AddNumbers’ method to return an integer datatype.
We then use the return statement to return the sum to the main calling
program.
With this program, the output is as follows:
The sum of the numbers is 7

1.1 Recursive Methods


You can also define recursive methods in which the method keeps on
calling itself iteratively. A good example of this is the implementation of
the factorial series as shown below.

Example 4: The following program is used to showcase how to use


recursive methods.
public class Demo
{
static int factorial(int num)
{
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
public static void main(String args[])
{
System.out.println("The factorial of 6 is " + factorial(6));
}
}

With this program, the output is as follows:


The factorial of 6 is 720
2. Working with Arrays

Arrays are used to define a collection of values of a similar datatype. The


definition of a data type is shown below.
datatype[] arrayname= new datatype[arraysize]

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 5: The following program is used to showcase how to work with


arrays.
public class Demo
{
public static void main(String args[])
{
// Declaring the Array
int[] arr=new int[3];

// Defining the elements of the array


arr[0]=1; // The first element of the array
arr[1]=2; // The second element of the array
arr[2]=3; // The third element of the array
}
}

Now with the above program:


We are defining an integer array which has a size of 3.
The first item in the array starts with the 0 index value.
Each value of the array can be accessed with its corresponding index
value. Each value of the array is also known as the element of the
array.
Let’s now look at an example of how we can display the values of the array.

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];

// Defining the elements of the array


arr[0]=1; // The first element of the array
arr[1]=2; // The second element of the array
arr[2]=3; // The third element of the array

// Displaying the elements of the array


System.out.println("The first element of the array is "+arr[0]);
System.out.println("The second element of the array is "+arr[1]);
System.out.println("The third element of the array is "+arr[2]);
}
}

With this program, the output is as follows:


The first element of the array is 1
The second element of the array is 2
The third element of the array is 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];

// Defining the elements of the array


arr[0]="First"; // The first element of the array
arr[1]="Second"; // The second element of the array
arr[2]="Third"; // The third element of the array

// Displaying the elements of the array


System.out.println("The first element of the array is "+arr[0]);
System.out.println("The second element of the array is "+arr[1]);
System.out.println("The third element of the array is "+arr[2]);
}
}

With the above program we are:


First defining the array to be of the ‘string’ type.
Then defining the elements of the array, each of which is of the
‘string’ type.
With this program, the output is as follows:
The first element of the array is First
The second element of the array is Second
The third element of the array is Third
We can also carry out normal operations with the elements of the array, as
we would normally do with ordinary variables. Let’s look at an example of
how we can work with the elements of the array.

Example 8: The following program shows how to work with arrays


elements with standard operators.
public class Demo
{
public static void main(String args[])
{
// Declaring the Array
String[] arr=new String[3];

// Defining the elements of the array


arr[0]="First"; // The first element of the array
arr[1]="Second"; // The second element of the array
arr[2]="Third"; // The third element of the array

int[] team=new int[3];


team[0]=1;
team[1]=2;
team[2]=3;

System.out.println("The combination of the first array is "+arr[0]+arr[1]+arr[2]);

System.out.println("The combination of the second array is "+team[0]+team[1]+team[2]);


}
}

Things to note about the above program:


Here we are defining 2 arrays. One is of the ‘integer’ type and the
other is of the ‘string’ type.
You can see that we are able to perform the + operation on both
arrays. For the integer array, it will add all the numbers together. And
for the string array, it will concatenate the strings.
With this program, the output is as follows:
The combination of the first array is FirstSecondThird
The combination of the second array is 123

2.1 Initializing Arrays


Arrays can also be initialized when they are defined. The syntax for the
array definition is given below.
Datatype[] arrayname={value1,value2…valueN-1}

In the above definition, the values for the array are defined in the
parenthesis { }. Let’s now look at an example of this.

Example 9: The following program is used to showcase how to initialize


arrays.
public class Demo
{
public static void main(String args[])
{
int[] arr={1,2,3};

System.out.println("The first element of the array is "+arr[0]);


System.out.println("The second element of the array is "+arr[1]);
System.out.println("The third element of the array is "+arr[2]);
}
}

With this program, the output is as follows:


The first element if the array is 1
The second element if the array is 2
The third element if the array is 3
2.2 Going through the Elements of the Array
When an array has a number of elements, we can use the loops available in
Java to iterate through the elements of the array. Let’s look at an example of
how to iterate through the elements of an array.

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]);
}
}

With the above program we are:


Now using a ‘for’ loop to initialize the elements of the array. Here we
are using ‘i’ as the index identifier and then assigning the value to the
elements of the array accordingly.
Then we are performing the same method when it comes to
displaying the elements of the array.
With this program, the output is as follows:
The value of arr[0] is 0
The value of arr[1] is 1
The value of arr[2] is 2
The value of arr[3] is 3
The value of arr[4] is 4

2.3 Multidimensional Arrays


We can also define multidimensional arrays which have different
dimensions. The most common form of a multidimensional array is the 2
dimensional array. The table below shows how the array is structured if the
following array is defined.
arr[3][2]

Where 3 is the number of rows and 2 is the number of columns. So the


array can have a maximum of 6 values.
Column 0 Column 1
Row 0 1 2
Row 1 3 4
Row 2 5 6

Example 11: The following program is used to showcase how to define 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;
// Displaying the multidimensional array
System.out.println("The value of arr[0][0] is " + arr[0][0]);
System.out.println("The value of arr[0][1] is " + arr[0][1]);
System.out.println("The value of arr[1][0] is " + arr[1][0]);
System.out.println("The value of arr[1][1] is " + arr[1][1]);
System.out.println("The value of arr[2][0] is " + arr[2][0]);
System.out.println("The value of arr[2][1] is " + arr[2][1]);
}
}

With this program, the output is as follows:


The value of arr[0][0]1
The value of arr[0][1]2
The value of arr[1][0]3
The value of arr[1][1]4
The value of arr[2][0]5
The value of arr[2][1]6

It becomes easier to use loops when iterating through multi-dimensional


arrays, in the same we do for normal arrays. Let’s see how we can do this,
but this time around since we have 2 dimensions we also need to use nested
‘for’ loops to iterate through all the elements of the array.

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;

// Displaying the multidimensional array


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
System.out.println("Value at arr["+i+"]["+j+"] is " + arr[i][j]);
}
}
}
}

Things to note about the above program:


The first loop, in which ‘i’ is the identifier, is used to access the first
dimension of the array.
The second loop, in which ‘j’ is the identifier, is used to access the
second dimension of the array.
With this program, the output is as follows:
Value at arr[0][0] is 1
Value at arr[0][1] is 2
Value at arr[1][0] is 3
Value at arr[1][1] is 4
Value at arr[2][0] is 5
Value at arr[2][1] is 6
2.4 Arrays as Parameters
Arrays can also be passed as parameters to functions, and accessed like
normal variables. Let’s look at an example of how we can achieve this.

Example 13: The following program is used to showcase how to pass


arrays as parameters.
public class Demo
{
static void Display(int[] arr)
{
System.out.println("The value of the first element is "+arr[0]);
System.out.println("The value of the second element is "+arr[1]);
System.out.println("The value of the third element is "+arr[2]);
}
public static void main(String args[])
{
int[] arr=new int[3];
arr[0]=1;
arr[1]=2;
arr[2]=3;

// Calling the method with an array parameter


Display(arr);
}
}

With this program, the output is as follows:


The value of the first element is 1
The value of the second element is 2
The value of the third element is 3
3. Working with Numbers

We have already looked at numbers in Book 1, but let’s have a refresher on


the different types of numbers available in Java.

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;

// Displaying the numbers


System.out.println("The int value is "+a);
System.out.println("The short value is "+c);
System.out.println("The long value is "+d);
System.out.println("The float value is "+g);
System.out.println("The double value is "+h);
}
}

With the above program we are:


Defining variables which are of different number types. Here you can
see that you can define variables to be of different types.
We then assign values to the variables depending on the type assigned
to the variable.
With this program, the output is as follows:
The int value is -10
The short value is 30
The long value is -10000
The float value is 12.22
The double value is 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

3.1 Abs Function


This function is used to return the absolute value of a number. Let’s now
look at an example of this function.

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;

// Using the abs function


System.out.println("The value after applying the function is " + Math.abs(a));
}
}

With this program, the output is as follows:


The value after applying the function is 1000

3.2 Ceiling Function


This function returns the smallest integral value that is greater than or equal
to the specified decimal number. Let’s look at an example of this.

Example 16: The following program is used to showcase the ceiling


function.
public class Demo
{
public static void main(String args[])
{
// Defining a number
double a = 10.10;

// Using the ceil function


System.out.println("The value after applying the function is " + Math.ceil(a));
}
}

With this program, the output is as follows:


The value after applying the function is 11.0

3.3 Floor Function


This function returns the largest integer that is less than or equal to the
specified decimal number. Let’s have a look at an example of this function.

Example 17: The following program is used to showcase the floor


function.
public class Demo
{
public static void main(String args[])
{
// Defining a number
double a = 10.10;

// Using the floor function


System.out.println("The value after applying the function is " + Math.floor(a));
}
}

With this program, the output is as follows:


The value after applying the function is 10.0

3.4 Max Function


This function is used to return the maximum value of two numbers. Let’s
now look at an example of this function.

Example 18: The following program shows the max function.


public class Demo
{
public static void main(String args[])
{
double a=10;
double b=20;
// Using the max function
System.out.println("The value after applying the function is " + Math.max(a,b));
}
}

With this program, the output is as follows:


The value after applying the function is 20.0

3.5 Min Function


This function is used to return the minimum value of two numbers. Let’s
look at an example of this.

Example 19: The following program is used to showcase the min


function.
public class Demo
{
public static void main(String args[])
{
double a=10;
double b=20;

// Using the min function


System.out.println("The value after applying the function is " + Math.min(a,b));
}
}

With this program, the output is as follows:


The value after applying the function is 10.0

3.6 Pow Function


This function returns a specified number raised to the specified power. Let’s
have a quick look at an example of this function.

Example 20: The following program is used to showcase the pow


function.
public class Demo
{
public static void main(String args[])
{
int a=2;
int b=4;

// Using the pow function


System.out.println("The value after applying the function is " + Math.pow(a,b));
}
}

With this program, the output is as follows:


The value after applying the function is 16

3.7 Round Function


This function Rounds a decimal value to the nearest integral value. Let’s
look at an example of this in action.

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;

// Using the round function


System.out.println("The value after applying the function is " + Math.round(a));
}
}

With this program, the output is as follows:


The value after applying the function is 2

3.8 Sqrt Function


This function returns the square root of a number. Below is a short example
of this function.

Example 22: The following program is used to showcase the sqrt


function.
public class Demo
{
public static void main(String args[])
{
double a=4;

// Using the sqrt function


System.out.println("The value after applying the function is " + Math.sqrt(a));
}
}

With this program, the output is as follows:


The value after applying the function is 2.0

3.9 Sin Function


This function returns the sine value of a specified number. Let’s look at an
example of this.
Example 23: The following program shows the sin function.
public class Demo
{
public static void main(String args[])
{
double a=45;

// Using the sine function


System.out.println("The value after applying the function is " + Math.sin(a));
}
}

With this program, the output is as follows:


The value after applying the function is 0.8509035245341184

3.10 Tan Function


This function returns the tangent value of a specified number. Let’s have a
look at an example of the function.

Example 24: The following program is used to showcase the tan function.
public class Demo
{
public static void main(String args[])
{
double a=45;

// Using the tan function


System.out.println("The value after applying the function is " + Math.tan(a));
}
}

With this program, the output is as follows:


The value after applying the function is 1.6197751905438615

3.11 Cos Function


This function returns the cosine value of a specified number. Let’s now look
at an example of this function.

Example 25: The following program shows the cos function.


public class Demo
{
public static void main(String args[])
{
double a=45;

// Using the cos function


System.out.println("The value after applying the function is " + Math.cos(a));
}
}

With this program, the output is as follows:


The value after applying the function is 0.5253219888177297
4. Working with Strings

A string is nothing more than a sequence of characters that is terminated by


the null character, to denote that the string has indeed been terminated. In
Java a string is denoted by the string data type. Let’s revisit how to define a
string in Java via an example.

Example 26: The following program is used to showcase strings in Java.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The value of the string is " + str);
}
}

With the above program:


We are first defining a variable ‘str’ to be of the ‘string’ type.
Then we assign a string of “Hello World” to the ‘str’ variable.
Finally we output the value to the console accordingly.
With this program, the output is as follows:
The value of the string is Hello World

There are a variety of functions available in Java to work with strings. Let’s
look at them in more detail.

Table 3: String Functions


Function Description
length() This is used to return the length of the string
toLowerCase() This function returns the string in lower case
toUpperCase() This function returns the string in upper case
contains() This is used to check the existence of another string
endsWith() This is used to check if the string ends with a
particular string value
indexOf() This is used to get the index value of a character in
the string
replace() This is used to replace a character in the original
string
substring() This is used to return a substring from the original
string
compareTo() This compares an instance with a specified string
and indicates whether this instance precedes,
follows, or appears in the same position in the sort
order as the specified string

4.1 Length Function


This function is used to return the length of the string. Let’s look at an
example of this function.

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

4.2 toLowerCase Function


This function returns the string in lower case. Let’s now look at a simple
example of this.

Example 28: The following program shows the toLowerCase function.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The lower case of the string is " + str.toLowerCase());
}
}

With this program, the output is as follows:


The lower case of the string is hello world

4.3 toUpperCase Function


This function returns the string in upper case. Let’s quickly look at an
example of this.

Example 29: The following program showcases the toUpperCase


function.
public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The upper case of the string is " + str.toUpperCase());
}
}

With this program, the output is as follows:


The lower case of the string is HELLO WORLD

4.4 Contains Function


This function is used to check the existence of another string, and returns
True or False. Below is an example of this function.

Example 30: The following program is used to showcase the contains


function.
public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("Does the string contain Hello - " + str.contains("Hello"));
}
}

With this program, the output is as follows:


Does the string contain Hello - True
4.5 endsWith Function
This function can be used to check whether a string ends with a particular
string value. Let’s now look at a simple example of this function.

Example 31: The following program showcases the endsWith function.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("Does the string end with World - " + str.endsWith("World"));
}
}

With this program, the output is as follows:


Does the string end with World - true

4.6 indexOf Function


This function is used to get the index of a character in a string. Let’s have a
look at an example of this.

Example 32: The following program shows the indexOf function.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The index value of e is " + str.indexOf('e'));
}
}
With this program, the output is as follows:
The index value of e is 1

4.7 Replace Function


This function is used to replace a character in the original string. Below
we’ll look at an example of this function.

Example 33: The following program shows the replace function.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The replaced string is " + str.replace("World","Again"));
}
}

With this program, the output is as follows:


The value of the string is Hello Again

4.8 Substring Function


This function is used to return a substring from the original string. Let’s
look at a quick example of this function.

Example 34: The following program showcases the substring function.


public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello World";
System.out.println("The substring is " + str.substring(0,5));
}
}

With this program, the output is as follows:


The value of the string is Hello

4.9 compareTo Function


This function compares an instance with a specified string, and then
indicates whether this instance precedes, follows or appears in the same sort
order position as the specified string.
If the value is less than zero it means that the destination string
precedes the value.
If the value is greater than zero it means that the destination string
follows the value.
If the value is equal to zero then this instance has the same position in
the sort order as the value.
Let’s now look at an example of this function.

Example 35: The following program is used to showcase the compareTo


function.
public class Demo
{
public static void main(String args[])
{
// Defining the string
String str="Hello";

System.out.println("The output of the compareTo function is " + str.compareTo("Hello"));


}
}

With this program, the output is as follows:


The output of the compareTo function is 0
5. Classes and Objects

A class is used to represent entities. For example, suppose we wanted to


represent a student using Java. We can do this with the help of a class. The
student will then be in the form of a class and can have something known as
properties. These properties can be StudentID, StudentName or anything
else that can be used to define the student. The class can also have methods,
which can be used to manipulate the properties of the student. Hence there
can be a method which can be used to define the values of the properties,
and another to display the properties of the student.

The syntax for the definition of a class is:


Class classname
{
Class modifier Data type Class members;
Class modifier Data type Class functions;
}

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;
}

So in the above code we have:


A class with the name of ‘Student’.
Two properties; an integer type named ‘studentID’ and a string type
named ‘studentName’.
In order to define a student with values, we need to define an object for the
class. To define an object, we just need to ensure we define the type as that
of the class. This is done via the following code.
Student student1;

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;
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();

// Here we are assigning values to the properties of the object


stud.studentID=1;
stud.studentName="John";

// Here we are displaying the property values of the object


System.out.println("The ID of the student is "+stud.studentID);
System.out.println("The Name of the student is "+stud.studentName);
}
}

With the above program:


We have defined a class called ‘Student’ outside of the main
program.
The ‘Student’ class has 2 properties. They both have the public
modifier, which we will look at in more detail a bit later.
We then defined an object called ‘stud’, which is of the type
‘Student’.
We then assign a value of 1 to ‘studentID’ and John to
‘studentName’.
We then display the values to the console.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

5.1 Member Functions


Member functions can be used to add additional functionality to a class. A
member function can be used, for example, to output the values of the
properties. This means that you don’t need to add code every time you want
to display the values, you can just invoke the function.
Now let’s look at an example of how we can use member functions.

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;

public void Display()


{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();

stud.studentID=1;
stud.studentName="John";

// Here we are calling the method


stud.Display();
}
}

With the above program:


We are now defining a member function called ‘Display()’ which
outputs the ‘studentID’ and ‘studentName’ to the console.
We can then call the member function from the object in the main
program.
Note that in the ‘Display’ method we make use of the ‘this’ keyword.
This keyword is a special keyword that can be used to point to the
current object.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is 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;

public void Display()


{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}

public void Input(int id, String name)


{
this.studentID = id;
this.studentName = name;
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();

stud.Input(1,"John");

// Here we are calling the method


stud.Display();
}
}

Now with the above program:


We are defining a member function called ‘Input()’ which takes in 2
values and assigns them to the ‘studentID’ and ‘studentName’
properties, respectively.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

5.2 Class Modifiers


Class modifiers can be used to define the visibility of properties and
methods in a class. Below are the various modifiers available.
Private – With this modifier, the properties and methods are only
available to the class itself.
Protected - With this modifier, the properties and methods are only
available to the class itself and subclasses derived from the class.
Public - With public, the properties and methods are available to all
classes.
Let’s look at an example of private modifiers in action.
Example 39: The following program shows private access modifiers with
an error condition.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;

public void Display()


{
// Here we are defining a class method
System.out.println("The ID of the student is " + this.studentID);
System.out.println("The Name of the student is " + this.studentName);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();

stud.studentID=1;
stud.studentName="John";

// Here we are calling the method


stud.Display();
}
}

With this program, the output is as follows:


Error:(22, 13) java: studentID has private access in Student
Since the access modifier is private, it can only be accessed by the class
itself and hence you will get all these errors. The way to resolve this is to
define the program as follows:

Example 40: The following program is used to showcase how to use


private access modifiers.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public void Display()
{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}
public void Input(int id, String name)
{
this.studentID = id;
this.studentName = name;
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.Input(1,"John");

// Here we are calling the method


stud.Display();
}
}
Now with the above program we are:
Defining the properties as private and the methods as public. This is
the normal practice for classes.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

One can also define multiple classes in a program and make use of those
classes. Let’s look at an example of this.

Example 41: The following program showcases how to use multiple


classes.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public void Display()
{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}
public void Input(int id, String name)
{
this.studentID = id;
this.studentName = name;
}
}

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);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();

stud.Input(1,"John");
stud.Display();

Employee emp=new Employee();


emp.EmployeeID=2;
emp.EmployeeName="Mark";
emp.Display();
}
}

Now with the above program:


We are defining two classes. The one being ‘Employee’ and the other
‘Student’, and we can use both of these classes in the main program.
With this program, the output is as follows:
The ID of the student is 1
The name of the student is John
The ID of the Employee is 2
The name of the Employee is Mark
We can also define multiple objects of a class. Let’s look at an example of
this.

Example 42: The following program is used to showcase how to define


multiple objects.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public void Display()
{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}
public void Input(int id, String name)
{
this.studentID = id;
this.studentName = name;
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.Input(1,"John");
stud.Display();

Student stud1=new Student();


stud1.Input(2,"Mark");
stud1.Display();
}
}

With this program, the output is as follows:


The ID of the student is 1
The Name of the student is John
The ID of the student is 2
The Name of the student is Mark

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
}

Let’s look at an example of how we can use constructors.

Example 43: The following program shows how to define constructors.


// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public void Display()
{
// Here we are defining a class method
System.out.println("The ID of the student is "+this.studentID);
System.out.println("The Name of the student is "+this.studentName);
}
public void Input(int id, String name)
{
this.studentID = id;
this.studentName = name;
}
public Student()
{
System.out.println("The constructor is being called");
this.studentID=1;
this.studentName="Default";
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.Display();
}
}

With the above program:


We are now defining a constructor, which is a method with the same
name as the class.
In the constructor, we are initializing the fields of the object to default
values.
With this program, the output is as follows:
The constructor is being called
The ID of the student is 1
The Name of the student is Default
As we can see from the output, the constructor gets called when the object
is created and assigns the default values to the properties of the class.

5.4 Parameterized Constructors


It is also possible to pass in parameters to the constructor like with any
other ordinary function.
The syntax of the constructor method with parameters is shown below.
classname(parameters)
{
// Use the parameters accordingly.
}

Let’s look at an example on how we can use parameterized constructors.

Example 44: The following program shows how to work with


parameterized constructors.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public void Display()
{
// Here we are defining a class method
System.out.println("The ID of the student is " + this.studentID);
System.out.println("The Name of the student is " + this.studentName);
}
public void Input(int id, String name)
{
this.studentID = id;
this.studentName = name;
}
public Student()
{
System.out.println("The constructor is being called");
this.studentID = 1;
this.studentName = "Default";
}

public Student(int id, String Name)


{
this.studentID = id;
this.studentName = Name;
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student(1,"John");
stud.Display();
}
}

With the above program:


We are defining a constructor that takes in parameters.
We are then assigning the parameters to the properties in the
constructor.
Note that we can define multiple constructors for a class. So in the
above program, we have constructors with no parameters and
constructors with parameters.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

5.5 Static Members


Static members are used to define values that should remain the same
across all objects of a class. Since classes have properties that are separate
for each object, we could occasionally have the need for properties that
never change. This can be done with static members.
The syntax of static member definitions is shown below.
Class classname
{
static datatype staticmembername
}

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;

Let’s look at an example of how we can achieve all of this.

Example 45: The following program is used to showcase how to work


with static members.
// Here we are defining the class
class Student
{
private int studentID;
public String studentName;
public static int Counter=0;

public void Display()


{
// Here we are defining a class method
System.out.println("The ID of the student is " + this.studentID);
System.out.println("The Name of the student is " + this.studentName);
}

public Student()
{
System.out.println("The constructor is being called");
this.studentID = 1;
this.studentName = "Default";
}

public Student(int id, String Name)


{
this.studentID = id;
this.studentName = Name;
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student(1,"John");
Student.Counter++;
stud.Display();
System.out.println("The number of students is "+Student.Counter);
}
}

With the above program:


We have now defined a field of the class named ‘counter’. This is
defined as a static member.
Note that in the main program, when we try to access the ‘counter’
property, we don’t do this via the object but through the class itself.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John
The number of students is 1
6. Inheritance

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);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.studentID=1;
stud.studentName="John";
stud.Display();
}
}

With the above program:


We have a class called ‘Student’ that has 2 members. The one being
‘StudentID’ and the other ‘StudentName’.
We then define a member function called ‘Display()’, which outputs
the studentId and studentName to the console.
We can then call the member function from the object in the main
program.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

6.1 What is Inheritance?


Inheritance is a concept wherein we can define a class to inherit the
properties and methods of another class. This helps in not having the need
to define the class again or having the properties and methods defined
again.
Let’s say that we had a class called Person, which had a property of Name
and a method of Display. Then via inheritance we can define a class called
Student, which could inherit the Person class. The Student class would
automatically get the ID member and the Display function. The Student
class could then define its own additional members if required.
To define an inherited class, we use the following syntax.
Derived class extends Base class

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.
}

Now let’s look at a simple example of inheritance via code.

Example 47: The following program is used to showcase how to use a


simple inherited class.
class Person
{
public String Name;
}
class Student extends Person
{
public int ID;
public void Display()
{
System.out.println("The ID of the student is " + this.ID);
System.out.println("The Name of the student is " + this.Name);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();
}
}

With the above program:


We are defining a class called ‘Person’, which has one member called
‘Name’.
We then use inheritance to define the ‘Student’ class. Notice that we
now define another property called ‘ID’.
In the ‘Display’ function, note that we can use the ‘Name’ property
without the need for defining it in the ‘Student’ class again.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John

So now we have seen how we can use derived and base classes and this is
known as inheritance.

6.2 Methods in Derived Classes


We can also define methods that can be inherited from the base class. Let’s
see how we can achieve this.
So if we had a base class with a property and a method as shown below.
Base class
{
Public or protected Property1;
Public or protected Method1;
}

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.
}

Now let’s look at an example where we can use functions in derived


classes.

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);
}
}

class Student extends Person


{
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();
}
}

With this program, the output is as follows:


The ID of the person is 1
The Name of the person is John

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.

Example 49: The following program showcases how to use an inherited


class with redefined 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);
}
}

class Student extends Person


{
public void Display()
{
System.out.println("The ID of the student is " + this.ID);
System.out.println("The Name of the student is " + this.Name);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();
}
}

With the above program:


Note that we are using the ‘new’ keyword for the Display function in
the Student class. Only then will the derived class Display be called.
With this program, the output is as follows:
The ID of the student is 1
The name of the student is John

6.3 Constructors and Derived Classes


In the earlier chapters we saw how constructors work, and that the base and
derived classes can define constructors. If both of them derive constructors,
then the order of calling would be that the base class constructors are called
first and then the derived class constructors.
Let’ look at an example of this in action.

Example 50: The following program is used to showcase how to use


constructors in base and derived classes
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);
}

public Person()
{
System.out.println("This is the Person class constructor");
}
}

class Student extends Person


{
public void Display()
{
System.out.println("The ID of the student is " + this.ID);
System.out.println("The Name of the student is " + this.Name);
}

public Student()
{
System.out.println("This is the Student class constructor");
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();
}
}

With this program, the output is as follows:


This is the Person class constructor
This is the Student class constructor
The ID of the student is 1
The Name of the student is John

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() { }
}

And we have the derived class as shown below.


Class derivedclass extends baseclassA
{
MethodA() { }
}

Then in the main program, we define the object as follows:


derivedclass objA;

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();

Let’s look at an example to understand this a bit better.

Example 51: The following program is used to show a simple example of


polymorphism.
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);
}
}

class Student extends Person


{
public void Display()
{
System.out.println("The ID of the student is " + this.ID);
System.out.println("The Name of the student is " + this.Name);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();

Person per=new Person();


per.ID=2;
per.Name="Mark";
per.Display();
}
}

With the above program:


We now have 2 separate classes. The first is ‘Person’ and the second
is the ‘Student’ derived class.
We then have 2 objects, one defined per class.
When we call the Display method, we can see that the method gets
called depending on which class the variable is defined as.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John
The ID of the Person is 2
The Name of the Person is Mark

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.

Example 52: The following program showcases another example of


polymorphism.
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);
}
}

class Student extends Person


{
public void Display()
{
System.out.println("The ID of the student is " + this.ID);
System.out.println("The Name of the student is " + this.Name);
}
}

public class Demo


{
public static void main(String args[])
{
// Here we are creating an object of the class
Student stud=new Student();
stud.ID=1;
stud.Name="John";
stud.Display();

Person per=new Student();


per.ID=2;
per.Name="Mark";
per.Display();
}
}

With this program, the output is as follows:


The ID of the student is 1
The Name of the student is John
The ID of the student is 2
The Name of the student is Mark
8. Inner Classes

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.

Example 53: The following program is used to showcase a simple


example of inner classes.
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);
}
}

public class Demo


{
public static void main(String args[])
{
Outer obj=new Outer();
obj.DisplayInner();
}
}

With the above program:


We are creating an outer class called ‘Outer’.
Then we define an inner class called ‘Inner’, which contains a
property called ‘InnerID’.
From the outer class, in the ‘DisplayInner’ method, we make an
object out of the class and display the value of the InnerID property.
With this program, the output is as follows:
The value of the ID of the inner class is 1

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);
}
}

public class Demo


{
public static void main(String args[])
{
Outer obj=new Outer();
obj.DisplayInner();

Outer.Inner inobj = obj.new Inner();


inobj.innerID=2;
System.out.println("The value of the inner id is "+ inobj.innerID);
}
}

With the above program:


We are first creating an object of the outer class in the main program.
Then we create an object of the inner class using the ‘new’ keyword
on the outer object.
With this program, the output is as follows:
The value of the ID of the inner class is 1
The value of the inner id is 2

8.1 Static Inner Classes


The inner classes can also be static in nature. So instead of creating an
object of the inner class, we can reference its properties via the class name.
The syntax for doing this is shown below.
class outer
{
static class Inner
{
}
}

Let’s now look at an example to demonstrate.

Example 55: The following program is used to showcase an example of


static inner classes.
class Outer
{
static class Inner
{
static public int innerID;
}
public void DisplayInner()
{
Inner.innerID=1;
System.out.println("The value of the ID of the inner class is "+Inner.innerID);
}
}

public class Demo


{
public static void main(String args[])
{
Outer obj=new Outer();
obj.DisplayInner();

Outer.Inner.innerID=2;
System.out.println("The value of the inner id is "+ Outer.Inner.innerID);
}
}

With the above program:


We are creating a static inner class, which has a static inner property
of ‘InnerID’.
We then use the class reference to reference the InnerID property.
With this program, the output is as follows:
The value of the ID of the inner class is 1
The value of the inner id is 2
9. Anonymous Classes

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 }

Here we need to provide the implementation of every method in the


interface or the abstract class. The best way to understand this is to see it
through an example.

Example 56: The following program is used to show how to use


anonymous classes.
abstract class Person
{
abstract public void Display();
}

public class Demo


{
public static void main(String args[])
{
Person per=new Person()
{
public void Display()
{
System.out.println("This is the Display method");
}
};
per.Display();
}
}

The following things should be noted about of the above program:


We first declared an abstract class named ‘Person’. This class has one
abstract method called ‘Display’.
We then created a new ‘Person’ object in the main method.
But in addition to creating the object, we also defined the
implementation of the ‘Display’ method.
And finally we call the object’s ‘Display’ method.
With this program, the output is as follows:
This is the Display method

Let’s look at another example, but this time let’s also add properties to the
class.

Example 57: The following program showcases how to use anonymous


classes with properties.
abstract class Person
{
abstract public void Display();
}

public class Demo


{
public static void main(String args[])
{
Person per=new Person()
{
String Name="John";
public void Display()
{
System.out.println("The name of the person is "+this.Name);
}
};
per.Display();
}
}

With the above program:


We define a property in the anonymous class, called ‘Name’.
We then reference this in the ‘Display’ method.
With this program, the output is as follows:
The name of the person is John

We can also create anonymous classes from interfaces. We will be looking


at Interfaces in more detail in the subsequent chapter. But for now, let’s go
through an example of what this would look like.

Example 58: The following program shows how to use anonymous


classes with properties.
interface DisplayInterface
{
public void Display();
}

public class Demo


{
public static void main(String args[])
{
DisplayInterface per=new DisplayInterface()
{
public void Display()
{
System.out.println("This is the Display method");
}
};
per.Display();
}
}

In the above program, note the following:


Here we are defining an interface called ‘DisplayInterface’.
We then create an object out of this interface and implement the
‘Display’ method.
Lastly we call the ‘Display’ method accordingly.
With this program, the output is as follows:
This is the Display method
10. Interfaces

An interface is defined as a contract that is implemented by the class and


available for use by other classes. An interface contains only the declaration
of the functions. The methods are defined by the classes that inherit them.
The definition of an interface is shown below.
interface interfacename
{
// interface methods declaration
}

Then the necessary class should implement the interface accordingly.


class classname implements interfacename
{
// interface method definition
}

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.

Example 59: The following program is used to showcase how to use


interfaces.
interface DisplayInterface
{
public void Display();
}

class Person implements DisplayInterface


{
public String Name;
public void Display()
{
System.out.println("The name of the person is "+ this.Name);
}
}

public class Demo


{
public static void main(String args[])
{
Person per=new Person();
per.Name="John";
per.Display();
}
}

With the above program:


We are first defining an interface called ‘DisplayInterface’, which
contains a ‘Display’ method.
We are then defining a ‘Person’ class, which implements the
‘DisplayInterface’.
Since the ‘DisplayInterface’ is being implemented, the ‘Display’
method needs to be defined by the ‘Person’ class.
With this program, the output is as follows:
The name of the Person is John

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();
}

class Person implements DisplayInterface,DisplayNameInterface


{
public String firstName;
public String lastName;
public void DisplayName()
{
System.out.println("The name of the person is " + (this.firstName+this.lastName));
}
public void Display()
{
System.out.println("The first name of the person is "+ this.firstName);
System.out.println("The last name of the person is "+ this.lastName);
}
}

public class Demo


{
public static void main(String args[])
{
Person per=new Person();
per.firstName="John";
per.lastName="Carter";
per.Display();
per.DisplayName();
}
}

With the above program:


We have defined 2 interfaces. One being ‘DisplayInterface’ and the
other ‘DisplayNameInterface’.
The ‘Person’ class takes on both the interfaces and also defines the
methods of the interfaces accordingly.
With this program, the output is as follows:
The first name of the person is John
The last name of the person is Carter
The name of the person is JohnCarter

Properties can also be define in interfaces, but they need to be either static
or final. Let’s look at an example of this.

Example 61: The following program is used to shows how to use


properties in interfaces.
interface DisplayInterface
{
static int count=1;
public void Display();
}

interface DisplayNameInterface
{
public void DisplayName();
}

class Person implements DisplayInterface,DisplayNameInterface


{
public String firstName;
public String lastName;
public void DisplayName()
{
System.out.println("The name of the person is " + (this.firstName+this.lastName));
}
public void Display()
{
System.out.println("The first name of the person is "+ this.firstName);
System.out.println("The last name of the person is "+ this.lastName);
}
}

public class Demo


{
public static void main(String args[])
{
Person per=new Person();
per.firstName="John";
per.lastName="Carter";
per.Display();
per.DisplayName();
System.out.println("The value of count is "+per.count);
}
}

With this program, the output is as follows:


The first name of the person is John
The last name of the person is Carter
The name of the person is JohnCarter
The value of count is 1

Interfaces can also extend each other just like classes. Let’s look at an
example of this.

Example 62: The following program is used to showcase how to use


properties in interfaces.
interface TotalMarks
{
public void Calculate();
}

interface DisplayInterface extends TotalMarks


{
public void Display();
}

class Student implements DisplayInterface


{
public String Name;
public int marks1;
public int marks2;
private int total;
public void Calculate()
{
total=this.marks1+this.marks2;
}
public void Display()
{
System.out.println("The name of the student is " + this.Name);
System.out.println("The total marks is "+this.total);
}
}

public class Demo


{
public static void main(String args[])
{
Student st=new Student();
st.Name="John";
st.marks1=10;
st.marks2=10;
st.Display();
}
}
With the above program, take note of the following:
We first define an interface called ‘TotalMarks’, which has a
‘Calculate’ display method.
We then define an interface called ‘DisplayInterface’, which extends
the ‘TotalMarks’ interface.
Finally we make a ‘Student’ class and ensure that it implements the
‘DisplayInterface’. Since the ‘DisplayInterface’ extends the
‘TotalMarks’, the ‘Student’ class has to implement the methods in
both interfaces.
With this program, the output is as follows:
The name of the student is John
The total marks is 0
11. File I/O Operations

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.

11.1 File Class


This class can be used to work with files on the local system. There are
many methods available to work with files. Let’s look at an example of how
to work with this class.

Example 63: The following program shows the way to use the file class.
import java.io.File;

public class Demo


{
public static void main(String args[])
{
String path="H:\\Sample.txt";

File file = new File(path);


System.out.println("Can we read the file " + file.canRead());
}
}

Note the following things about the above program:


First we have to ensure that we import the library ‘java.io.File’,
because this is where the file methods are present.
We then use the ‘File’ class to create a new file based on the path
provided.
The ‘File’ class provides a property called ‘canRead’, which can
return true or false based on whether the file can be read or not.
With this program, the output is as follows:
Can we read the file true
Drive type:Fixed

11.2 Listing All Files in a Directory


We can also use the File class to list all files in a particular directory. Let’s
look at an example of this.

Example 64: The following program is used to showcase the way to use
list files in a directory.
import java.io.File;

public class Demo


{
public static void main(String args[])
{
File f=new File("H:\\Sample");
String filenames[]=f.list();
for(String filename:filenames)
{
System.out.println(filename);
}
}
}

With the above program, we are doing the following:


First we are creating a new ‘File’ object that points to our directory.
Next we use the ‘list’ method to get a list of files, which gets returned
as an array.
For each file name in the array, we then display the file name.
With this program, the output is as below. The output will vary from system
to system. An example output is shown below.
App_Data
aspnet_client
Bin
Default.html
Home.aspx
Home.aspx.cs
packages.config
Start.aspx
Start.aspx.cs
web.config

11.3 Getting File Details


The file details, such as the path of the file, can also be obtained with the
File class. Let’s look at an example on this.

Example 65: The following program shows how to use the file class to get
file details.
import java.io.File;

public class Demo


{
public static void main(String args[])
{
File f=new File("H:\\Sample\\Default.html");
System.out.println(f.getAbsolutePath());
System.out.println(f.getParent());
}
}
With this program, the output is as shown below. The output will again vary
depending on your system. An example output is shown below.
H:\Sample\Default.html
H:\Sample

11.4 FileOutputStream Class


This class can be used to write the contents to a file. Note that this class
works with the file in bytes. The general syntax when creating a new object
of this class is given below.
FileOutputStream fileobj = new FileOutputStream("nameoffile")

Let’s now look at an example of how to use the FileOutputStream class.

Example 66: The following program is used to showcase the way to use
the FileOutputStream class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileOutputStream fp=new FileOutputStream("H:\\Sample.txt");
String str="Hello World";

// We need to convert the string to bytes


byte arr[]=str.getBytes();
fp.write(arr);
fp.close();
System.out.println("Written to the file successfully");
}
catch(IOException exp)
{
System.out.println("An exception has occured");
}
}
}

With the above program:


We are opening the file “Sample.txt”.
We want to store the text “Hello World” in the file, but first we need
to convert the string to a series of bytes.
We then use the ‘write’ method of the ‘FileOutputStream’ class to
write the bytes to the file.
Now if you open the Sample.txt file, you will see the “Hello World” text in
the file.

11.5 FileInputStream Class


This class can be used to read the contents of a file in bytes. Note that this
class works with the file in bytes. The general syntax when creating a new
object of this class is given below.
FileInputStream fileobj = new FileInputStream("nameoffile")

Let’s now look at an example of how to use the FileInputStream class.

Example 67: The following program shows the way to use the
FileInputStream class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileOutputStream fp = new FileOutputStream("H:\\Sample.txt");
String str = "Hello World";

// We need to convert the string to bytes


byte arr[] = str.getBytes();
fp.write(arr);
fp.close();
System.out.println("Written to the file successfully");

FileInputStream fpin = new FileInputStream("H:\\Sample.txt");


int i = 0;
while ((i = fpin.read()) != -1)
{
System.out.print((char) i);
}
fpin.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

With the above program:


We are first writing data to the file.
Then we use the ‘FileInputStream’ class to start reading from the file.
We use the ‘read’ method to read the bytes one by one.
We then convert them to characters and then display it to the console.
With this program, the output is as follows:
Written to the file successfully
Hello World

11.6 SequenceInputStream Class


This class can be used to read the contents from multiple streams at a time
in a sequence. Let’s look at an example of how to use the
SequenceInputStream class.

Example 68: The following program showcases how to use the


SequenceInputStream class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileInputStream input1=new FileInputStream("H:\\Sample.txt");
FileInputStream input2=new FileInputStream("H:\\Sample1.txt");
SequenceInputStream in=new SequenceInputStream(input1, input2);
int i;
while((i=in.read())!=-1)
{
System.out.print((char)i);
}
in.close();
input1.close();
input2.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

With the above program:


We are first writing data to the file.
Then we use the ‘FileInputStream’ class to start reading from the file.
We use the ‘read’ method to read the bytes one by one.
Lastly, we convert them to characters and then display it to the
console.
With this program, the output is as below. The output will depend on the
contents in the sample and sample1.txt file. In our example, the sample.txt
file contains “This is the first stream” and the sample1.txt file contains
“This is the second stream”. So based on this, the output will be:
This is the first streamThis is the second stream

11.7 DataOutputStream Class


The Java DataOutputStream class allows an application to write primitive
data types to the output stream in a machine-independent way. Let’s look at
an example of how to use the DataOutputStream class.

Example 69: The following program is used to showcase how to use the
DataOutputStream class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileOutputStream file = new FileOutputStream("H:\\Sample.txt");
DataOutputStream data = new DataOutputStream(file);
data.writeInt(66);
data.flush();
data.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

If you now open the Sample.txt you will have the character ‘B’ written to
the file.

11.8 DataInputStream Class


The DataInputStream class allows an application to read primitive Java data
types from the Input stream in a machine-independent way. Let’s now look
at an example of how this works.

Example 70: The following program shows the way to use the
DataInputStream class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
InputStream input = new FileInputStream("H:\\Sample.txt");
DataInputStream inst = new DataInputStream(input);
char i;
i=(char)inst.read();
System.out.println(i);
inst.close();
input.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

The above program will read the first byte from the Sample.txt file.

11.9 FileWriter Class


The Java FileWriter class is used to write character-oriented data to a file. It
is character-oriented classes which are used for file handling in Java. Let’s
now look at an example of how to use this class.

Example 71: The following program is used to showcase the way to use
the FileWriter class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("H:\\Sample.txt");
fw.write("Hello World");
fw.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

In the above program we are:


Creating a new ‘FileWriter’ object and specifying the location of the
file.
Then we write ‘Hello World’ to the file.
With this program, if you open the Sample.txt file, you will see the ‘Hello
World’ string.

11.10 FileReader Class


The FileReader class is used to read character-oriented data from a file. As
mentioned, it is character-oriented classes which are used for file handling
in Java. Let’s now look at an example of the FileReader class.

Example 72: The following program showcases how to use the


FileReader class.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("H:\\Sample.txt");
char[] arr=new char[100];
fr.read(arr);
int len=arr.length;
for(int i=0;i<len;i++ )
System.out.print(arr[i]);
fr.close();
}
catch (IOException exp)
{
System.out.println(exp.getMessage());
}
}
}

With this program, the output will be as below. However, the output
depends on the contents of the file.
Hello World
12. Exception Handling

Not all programs that we develop can be guaranteed to be foolproof, and


errors can crop up when a program is being used. Sometimes the user can
enter a wrong input that we didn’t anticipate, and that could cause an error
in the program as well.
Normally when an error occurs, the program could terminate, leading to a
poor user experience. It would be considerably better if the program can
take care of the error on its own and proceed ahead, without impacting the
functionality of the program.
This is where exception handling comes in. Exception handling is the
ability of the program to catch errors or exceptions, take care of them, and
proceed ahead with the normal running of the program.
Exceptions are implemented by using the statements below:
try - A try block identifies a block of code in which the exception can
occur. We place the block of code in the try block.
catch - This block is used to handle the exception if it occurs.
finally - The finally block is used to execute a given set of statements,
whether an exception is thrown or not.
The syntax for how we use the above statements is shown below.
try
{
//Code block that can cause the exception
}
catch( ExceptionName e1 )
{
// error handling code
}
finally
{
// statements to be executed
}
Now let’s look at a simple example of using the try catch block.

Example 73: The following program showcases the way to use the
Exception handling blocks.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
int[] arr=new int[3];
arr[4]=1;
}
catch (Exception exp)
{
System.out.println("An exception has occured");
}
}
}

With the above program we are:


Creating a ‘try, catch’ block.
In the ‘try’ block, we are performing an illegal operation. Ideally the
array only has 3 values, but we are trying to access a value that
cannot be defined in the array.
If we did not have the ‘try, catch’ block, the code would just
terminate. But the ‘catch’ block will get the error and display it in the
console.
With this program, the output is as follows:
An exception has occurred
12.1 Built-in Exceptions
You can also use the pre-built exceptions available in Java to catch errors.
Some of the available exceptions are given below.

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.*;

public class Demo


{
public static void main(String args[])
{
try
{
int[] arr=new int[3];
arr[4]=1;
}
catch (ArrayIndexOutOfBoundsException exp)
{
System.out.println("An exception has occurred");
}
}
}

With this program, the output is as follows:


An exception has occurred

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.*;

public class Demo


{
public static void main(String args[])
{
try
{
int[] arr=new int[3];
arr[4]=1;
FileInputStream fp=new FileInputStream("H:\\Sample.txt");
}
catch (IOException exp)
{
System.out.println("An IOException has occured");
}
catch (ArrayIndexOutOfBoundsException exp)
{
System.out.println("An ArrayIndexOutOfBoundsException has occurred");
}
}
}

With the above program, the following points should be noted:


If the ‘try’ block code throws multiple exceptions, then we can define
multiple ‘catch’ blocks to handle those exceptions.
Each ‘catch’ block will be evaluated when an exception is thrown.
With this program, the output is as follows:
An ArrayIndexOutOfBoundsException has occurred

12.2 Finally Block


The finally block is a special block that is executed when an exception
occurs. This is used to clean up any files that may be open, or close any
open database connections. Here, cleanup code is executed. Let’s look at an
example of using the finally block.

Example 76: The following program is used to showcase the way to use
finally block.
import java.io.*;

public class Demo


{
public static void main(String args[])
{
try
{
int[] arr=new int[3];
arr[4]=1;
FileInputStream fp=new FileInputStream("H:\\Sample.txt");
}
catch (IOException exp)
{
System.out.println("An IOException has occured");
}
catch (ArrayIndexOutOfBoundsException exp)
{
System.out.println("An ArrayIndexOutOfBoundsException has occurred");
}
finally
{
System.out.println("Cleaning all resources");
}
}
}

With this program, the output is as follows:


An ArrayIndexOutOfBoundsException has occurred
Cleaning all resources
13. Logging in Java

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;

public class Demo


{
private static final Logger LOGGER = Logger.getLogger( Demo.class.getName() );
public static void main(String args[])
{
LOGGER.log(Level.INFO, "Hello logging");
}
}

The following needs to be noted about the above program:


First we need to ensure that we import the ‘java.util.logging’
package. This has the necessary classes for logging.
At the top of the class, we define a static identifier for the logger. The
parameter is the class name.
We then start logging and set the logging level accordingly in the
main method.
With this program, the output is as follows:
Oct 27, 2017 1:46:58 PM Demo main
INFO: Hello logging

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;
}

public class Demo


{
private static final Logger LOGGER = Logger.getLogger( Demo.class.getName() );
public static void main(String args[])
{
LOGGER.log(Level.INFO , "Logging started");

Person per=new Person();


per.Name="John";
per.age=30;
LOGGER.log(Level.INFO,"Person Name {0}",per.Name);
}
}

With this program, the output is as follows:


Oct 27, 2017 1:54:40 PM Demo main
INFO: Logging started
Oct 27, 2017 1:54:40 PM Demo main
INFO: Person Name John

We can also pass in multiple parameters, as shown below.

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;
}

public class Demo


{
private static final Logger LOGGER = Logger.getLogger( Demo.class.getName() );
public static void main(String args[])
{
LOGGER.log(Level.INFO , "Logging started");

Person per=new Person();


per.Name="John";
per.age=30;
LOGGER.log(Level.INFO,"Person Name {0} Person Age {1}",new Object[]
{per.Name,per.age});
}
}

With this program, the output is as follows:


Oct 27, 2017 1:56:58 PM Demo main
INFO: Logging started
Oct 27, 2017 1:56:58 PM Demo main
INFO: Person Name John Person Age 30
Conclusion

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

Nathan Clark is an expert programmer with nearly 20 years of experience


in the software industry.
With a master’s degree from MIT, he has worked for some of the leading
software companies in the United States and built up extensive knowledge
of software design and development.
Nathan and his wife, Sarah, started their own development firm in 2009 to
be able to take on more challenging and creative projects. Today they assist
high-caliber clients from all over the world.
Nathan enjoys sharing his programming knowledge through his book
series, developing innovative software solutions for their clients and
watching classic sci-fi movies in his free time.

You might also like