15 Exception Handling

Exceptions in Java are objects. All exceptions are derived from the java.lang.Throwable class. Exceptions can be handled in Java using try-catch-finally construct. Exceptions thrown by the try block of code is caught (handled) by the catch block.

The following code shows an example of the try-catch-finally construct.





The output of the above example




Whenever an exception is thrown by try block of code, it looks for catch construct which handles that exception. If no catch construct is found which handles the exception, then the exception is handled by default exception handler. Catch construct is not executed if no exception is thrown or if the respective catch construct does not handle the specific exception. For example, in the code above, the catch construct only catches ArithmeticException. Any other exception, say FileNotFound will not be handled by this catch construct. Finally, the code block is executed, no matter an exception is thrown or not. An example for use of finally construct can be to write a code that closes DB connections. This will ensure that DB connection is closed, no matter an error happens or not during data retrieval from DB.



14 Interfaces

An interface is a group of related methods with empty bodies. In other words, it is a collection of abstract methods. An interface is not a class. A class implements an interface to inherit the abstract method of the interface.


The following code shows an interface Cars, that has method make() and price().


Cars Interface



The following steps show class Nissan which implements Cars interface and define its abstract method make() and price().



14.1 | Create a new class in Eclipse


1. Create a new class in Eclipse as defined in the previous post.

2. Provide reference of Cars interface as shown in below screen.
3. Click on Finish button.


Nissan Class implements Cars interface




14.2 | Created Nissan Class


Created Nissan class looks like below screen





The following code shows class Nissan which implements Cars interface and defines its abstract method make() and price().


Nissan Class



The below screen is the output of the above codes.








13 Abstract class

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods. If a class contain any abstract method then the class is declared as an abstract class. An abstract class is never instantiated. It is used to provide abstraction.

abstract class className {

 }

Before learning the abstract class, let's understand the abstraction in Java first.


13.1 | Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user. 

let's take an example, We send an email to others, where you type the mail body & receiver email id and send it, without knowing the internal processing of the email delivery.


13.2 | Abstract Method

A method, which is declared as abstract and does not have implementation is known as an abstract method. The method body will be defined by its subclass.

Example-

abstract return_type method_name ();  //no method body with abstract keyword


13.3 | Non-Abstract Method

A method, which is declared with a body and without abstract keyword is known as a non-abstract method. We also know the non-abstract method as a normal method and concrete method.


abstract return_type method_name () {
         
      ... 
       method body define here 
        ...

}


Example of the Abstract Class:

Abstract Class Example


The output of the above example







12 Inheritance

Inheritance is a mechanism which allows classes to inherit the attributes of an existing class. It is used in situations where the subclass (which inherit attributes) is a subset of the superclass, whose attributes are Inherited. For example, suppose there are three classes of employee, developer, and tester. In this case, both developers and testers are employees. Here, the employee class can define generic attributes of employees. Specific attributes of developers can be defined in developer class, while specific attributes of testers can be defined in tester class. Both developer and tester are subclasses while an employee is a superclass. A class can inherit other class attributes using the keyword 'extends'.


12.1 | Employee.java

The following code shows the inherent attributes of another class.

Employee superclass


12.2 | Developer.java

Developer subclass


Similar to class Developer.java, a separate class Tester.java can be defined for defining tester attributes.

The class below 'Company.java' shows how to use the above-defined classes for adding and viewing employee details.


12.3 | Company.java

Company main class

The below screen is the output of the above codes.

output of the Company main class






11 Constructors & Enum

11.1 | Constructors


Constructor declarations are similar to method declarations. However, constructors name must be the same as the class name and it cannot return a value. The main objective of a constructor is to set the initial state of an object. When the object is created by using the new operator. The following code shows how to declare constructors with and without input parameters.


Constructor Class



11.2 | ENUM


Enum is a Java keyword used to represent a fixed number of well-known values. For example, the number of days in a week, the number of planets in the solar system, etc.

  
Example 11.2.1 Simple enum of weekdays.

Enum Class




Example 11.2.2 Simple enum of weekdays with weekday number


Enum Class




Example 11.2.3 An enum defining weekday full name and weekday number


Enum Class









10 Class and Methods

10.1 | Class

A class is a template from which objects are created. A class declaration typically contains a set of attributes (instance variables) and functions (methods).



Class



10.2 | Methods

In Java, functions, and procedures are called methods. Methods can include zero or more input parameters and zero or one return parameter. The following code shows some method declarations. An arithmetic class has two methods printSum and getSum. method printSum has two input parameters both of integer type and no return parameter. while method getSum has two integer type input parameter and one integer type return parameter.





10.2.1 | Method Overloading

In Java, method overloading occurs when two or more methods in the same class have the same name but different parameters. Two methods can be considered overloaded if any of the below conditions are true:
  • The number of parameters is different for the methods.
  • The parameter types (input or return) are different.
Class ArithmeticClass below has two methods with same name getSum. these two methods are overloaded as the number of input parameters is different of both.

Arithmetic Class



10.2.2 | Method Overriding

Overriding a method involves defining a method in a subclass that has the same signature (input and return parameter) as a method in a superclass. Then, when that method is called, the method in the subclass is found and executed instead of the one in the superclass. The following code overriding method print. The code below shows the classes SuperClass and SubClass. SubClass overrides the print method of its superclass. MainClass shows different ways of calling the overridden method of a subclass as well as the original method of the superclass.

Super Class


10.2.3 | Variable and Method Scope

Java has reserved keywords to define the scope of variables methods and classes. 

private keyword is used to declare variables and methods that are to be accessible only within the class. 

protected keyword is used to declare variables and methods that are to be accessible only within the class or any class that extends to this class.

public keyword is used to declare variables and methods that are to be accessible within the class and as well as outside of class.


09.3 Control Flow

9.3 | Transfer Statement

Java provides six language constructs to tranfer control or exit loops in a program.



  1. break
  2. continue
  3. return
  4. try ...catch ...finally
  5. throw
  6. assert

break ...statement

break ...statement terminates a loop.

For example, the following code showed how to terminate a while and for a loop.

Break Statement by testinganswers.com



continue ...statement


continue ...statement exits the current iteration and starts executing the next iteration.


For example, the following code prints all numbers except number 3.






return ...statement


return ...statement stops code execution of a method and transfer control back to the calling code.





try ...catch ...finally ...statement

try ...catch ...finally ...statement is used for handling exceptions. (Further, discuss in section 'Exception Handling'.)


throws ...statement

throws ...statement is used for handling exceptions. (Further, discuss in section 'Exception Handling'.)


assert ...statement

assert ...statements are used to validate the assumptions made about the program. Assertions are expected to be true when assert statement are executed. In case it is false, the Java Virtual Machine (JVM)  throws a special error of AssertionError class. Assertion error are not handle but allowed to propagate to the top level.

Note: Assertion facility can be enabled or disabled at run-time. If disabled, assert statements are not executed during run-time.





09.2 Control Flow

9.2 | Looping Statements

Java supports four looping statements.

  • for...statement
  • for each...statement
  • while...statement
  • do while...statement

for ...statement

It executes a block of code specified number of times.

   For example - the code below prints numbers from 1 to 9.

for ...statement


for...each statement

It executes a block of code for each item in a collection or each element in an array.

For example - the code below prints all numbers in an array.

for each ...statement


while...statement

It executes a block of code while or until the condition is true.

For example - The code below executes the loop until array value <4.

while...statement


do...while statement

It executes a block of code until the condition becomes false.

do...while statement


Note: while loop is executed only if the condition is true. So while loop can execute zero or more times. Whereas do...while loop is executed first time without validating the condition, i.e. it will always execute for the first time. At the end of the first loop, the execution condition is checked. So, do...while loop always executes 1 or more times.




09.1 Control Flow

Java, like any other programming language, supports both conditional and loop statements to control code flow.


9.1 | Conditional Statements

In Java, we have four conditional statement:

1. if(condition=true){}: Execute a set of code when the specified condition is true. 
2. if(condition=true){}else{}: Execute first block of code when the specified condition is true else executes the second block of code. 
3. if(condition1=true){}elseif{condition2=true}{}else{}: Execute the first block of code for which the condition is true. If no condition is found true and else block exists, then this block of code is executed. If no condition is found true and else block does not exist, then none of the if block code is executed. 
4. Switch(choice)...case: Executes a set of code for which the choice condition is true. switch...case is used when the number of available alternatives and options are many and at a time only one holds true. Though the same can be implemented using if condition too but that makes the code cumbersome and less readable.

9.1.1 | if...Statement

Consider a scenario where code logic to be implemented is as follows:

  • If the specified number is less than 5, then print "number<5".
  • Elseif the specified number is >=5 and <10, then print "number is between 5 and 10".
  • Else, print "number is >=10".

if...statement




9.1.2 | switch...Statement

Consider a scenario where the code logic to be implemented is as follows:

  • If grade = 5, then print "Excellent".
  • If grade = 4, then print "Very Good".
  • If grade = 3, then print "Good".
  • Else, print "Poor".

switch..statement



08 Arrays

8.1 | Arrays

An array is a data structure that stores a collection of values of the same data type. Values stored in the array are accessible through the array index

//Declaring an array of integers

int arr1[];


//Creating an integer array with values

int[] arr0 = {2,3,4,5,6,7};


//Creating an integer array which can hold 100 integers

int arr2[] = new int[100];

//Or,

int arraySize = 100;

int arr3[] = new int[arraySize];


//Assigning values to the array

arr3[0] = 1;
arr3[1] = 2;


//Creating a string array which can hold 100 values

String arr4[] = new String[100];


//Assigning values to the array

arr4[0] = "This";
arr4[1] = "is a string array by";
arr4[2] = "testinganswers.com";


//Accessing array values by using for loop

for(int i=0;i<arr3.length; i++){
     System.out.println("arr3["+i+"] = "+arr3[i]);
}

//Or by using for each loop,

for(int element:arr3){

    System.out.println(element +",");

}

//Copying array

int[] arr5 = arr3;
String[] arr6 = arr4;





8.1.1 | Multi-dimensional Arrays

Multi-dimensional arrays are arrays of an array. They use more than one index to store and access values.

//Declaring a multi-dimensional array

int[][] arr0;


//Creating a multi-dimensional array

int[][] arr1 = {
                       {1,2,3}
                       {4,5,6}
                       {7,8,9}
                    };



//Creating a multi-dimensional array of size 2*3
int[][] arr2 = new int[2][3];


//Creating a multi-dimensional array using variables

int arrayXsize = 3;
int arrayYsize = 3;
int[][] arr3 = new int[arrayXsize][arrayYsize];



//Assigning values to multi-dimensional arrays

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


//Accessing values from multi-dimensional arrays

for(int i=0;i<arr2.length;i++){
    for(int j=0;j<arr2[i].length;j++){
         System.out.println("arr2["+i+"]["+j+"] = "+arr2[i][j]);
    }
}


//Copying multi-dimensional arrays

int[][] arr4 = arr3;


07 Data Types, Literals, Variables, Expressions and Operators

7.1 | Data Types

Each variable declaration in Java must define the data type of the variable. The data type defines what values a variable can store. The variable type can be as follows:
  • One of the eight basic primitive data types
  • An Array
  • The name of a class
The eight primitive data types hold values for integers, floating-point numbers, characters and boolean values. They are called primitive because they are built into the system and are not actual objects. This makes them more efficient to use.


Data Type Width (bits) Minimum value/ Maximum value
boolean
NA
True, false
byte
8
-27 , -27-1
short
16
-215 , -215-1
char
16
0x0, 0xffff
int
32
-231 , -231-1
long
64
-263 , -263-1

Float
32
±1.40129846432481707e - 45f,
±3.402823476638528860e + 38f

double
64
±4.94065645841246544e - 324,
±1.7976931348623157e + 308



7.2 | Literals

A literal denotes a constant value, i.e., the value that a literal holds. A literal can represent boolean, numerical, character, string or null value


Literal
Literal Type
Example
Integer
Decimal
Octal
Hexadecimal
8, 10L, -90
010, 012L, -0132
0 x 8, 0 x aL, -05 x a

Floating
Double
Float
0.41, 4100e-2 , 0.41e2
0.41F, 4100e-2F, 0.41e2F

Boolean

True, false

Character

'', '1', 'A', 'a'

Escape Sequences
\b, \t, \n, \f, \', \”, \\

String

“This is a String”



7.3 | Variable Declaration

A variable stores a value of specific type. Variable declaration is used to specify the type and name of the variable, The following code shows how to declare and initiate variables.

int i;                                          // Declaring interger variable
i=1;                                          // Initializing integer variable
int j=2;                                   // Declaring and initializing integer variable
long k=2L;                             // Declaring and initializing integer variable
boolean status=false;           // Declaring and initializing boolean variable
float f1 = i/3;                      // Declaring and initializing float variable
float f2 = (float) (i/3.0);    // Declaring and initializing float variable

String str = "This is a string." // Declaring and initializing a String variable


7.4 | Expression & Operators

Expressions are statements in Java that return a value. Operators are special symbols that perform an operation, for example, add and subtract.

7.4.1 | Arithmetic Operators

List Java arithmetic operators


Operator
Description
Example
+
Addition
5 + 2 = 7
-
Subtraction
5 – 2 = 3
*
Multiplication
5 * 2 = 10
/
Division
5/2 = 2
%
Modulus
5%2 = 1



7.4.2 | Comparison Operators

All Java comparators return a boolean value. 


OperatorDescriptionExample
==
Equal
5 == 2 = false
!=
Not Equal
5 != 2 = true
<
Less Than
5 < 2 = false
>
Greater Than
5 > 2 = true
<=
Less Than Equal To
5 <= 2 = false
>=
Greater Than Equal To
5 >= 2 = true


7.4.3 | Logical Operators

Logical operators are used to implementing logical AND, OR, XOR and NOT condition.


Operator
Description
Example
&&
AND
(5<2) && (2>10)
||
OR
(5<2) || (2>10)
^
XOR
(5<2) ^ (2>10)
!
NOT
!(5 < 2)


7.4.4 | Bitwise Operators

Bitwise operators perform operations on individual bits in integers.


Operator
Description
Example
&
Bitwise AND

|
Bitwise OR

^
Bitwise XOR

<<
Left shift

>>
Right shift


>>>
Zero fill right shift

-
Bitwise complement

<<=
Left shift assignment

>>=
Right shift assignment

x&=y
AND assignment
Equivalent to x=x&y
x|=y
OR assignment
Equivalent to x=x|y
x^=y
NOT assignment
Equivalent to x=x^y