Category: Java

Final keyword in Java

Java Tutorial – Final keyword in Java can be applied to a Variable, Method or Class. Java keeps restrictions on those, that are declared final.

Final keyword in Java

Final keyword in Java can be applied in the following scenarios :

  • Final Variable – Once a variable is declared as final, it can be initialized during declaration or in the constructor. And can never be changed during the course of the program. Hence static final variables are also called constants.
  • Final Method – Once a method is declared as final, it can never be overridden by any sub class that is inheriting the method’s class.
  • Final Class – Once a class is declared as final, it can never be inherited.

Final Keyword in Java - Java Tutorial - www.tutorialkart.com

Final Variable

Final variable once initialized can never be modified.

Following Example Java program, Audi.java, demonstrates following two scenarios :

  • BRAND is a final variable and initialized to “AUDI” during declaration itself and can never be changed. They remain constant for all the objects of class type Audi.
  • EngineNumber is only declared as final but not initialized. These kind of variables could be initialized in Constructor. They remain constant only for the object of Audi, i.e., each Audi object can have different EngineNumber.
Now we shall try to modify the final variable and understand what happens.
Java Compiler throws an Error.
 

Final Method

Final method cannot be overridden. This property could also be used to keep restrictions in PolymorphismMethod Overriding. Let us see an Example Java Program that has Car.java and Audi.java. Audi inherits Car, and accelerate() method of car is declared final.

Now we shall try overriding accelerate method in Audi.java

Java Compilation Error occurs

 

Final Class

Final Class can never be inherited by other classes.

We shall now try to extend this AudiR8.java from another class and understand what happens

Java Compiler throws Error : The type AnotherCar cannot subclass the final class AudiR8

 

Conclusion :

In this Java Tutorial, we have learnt about final keyword in Java that can be applied to a Variable, Method or Class and also the restrictions Java keeps on those, that are declared final. In our next tutorial, we shall learn about another Object Oriented Concept – Abstraction in Java.

Method Overriding in Java

In this tutorial, we shall learn Overriding in Java with Example Programs, where methods of Super Class are overridden by methods of Sub Class.

Method Overriding in Java

Method Overriding is a way to realize Polymorphism in Java.

In context of Sub Class extending a Super Class, the Sub Class can access super class’s methods. If in case the Sub Class wants functionality of an existing method in Super Class to be replaced by some specific implementation, then Java provides the ability to override the existing functionality through Method Overriding. It can also be thought of as Runtime Polymorphism.

Following are the rules for implementing Method Overriding in Java:

  1. The method declaration should be same as that of the method that is to be overridden.
  2. The class (sub class) should extend another class (super class), prior to even try overriding.
  3. Sub Class can never override final methods of Super Class.

We shall take an example scenario where Car is a Super Class and Audi is a Sub Class.

 

Sub Class Overriding Method of Super Class

Now we shall override accelerate method in Audi.java by overriding accelerate() in Car.java

 

What happens when you try to override final method of Super Class

Any method that is declared final in the Super Class cannot be overridden by Sub Class. If you try doing so, you may get an Error as shown in the following :

 

Conclusion :

In this Java Tutorial, we have learnt Method Overriding in Java with Example Programs, the prerequisites to Override a method. In our next tutorial, we shall learn about Final Keyword in Java.

Method Overloading in Java

Java Tutorial – We shall learn about Overloading in Java, ability to use same name for different methods with different set of arguments, with Java Example Programs.

Overloading in Java

Overloading is a way to realize Polymorphism in Java.

If a method can expect different types of inputs for the same functionality it implements, implementing different methods (with different method names) for each scenario may complicate the readability of code.

For example, we need a functionality to add two numbers. Now these two numbers could be integer values, float values, long values or double values. If we implement methods like addTwoInts(int a, int b), addTwoFloats(float a, float b), addIntFloat(int a, float b), etc., it becomes very difficult to use these methods in other classes because of lack of readability. Java provides the ability to overload a method based on the nature of parameters passed in the function call, provided the methods have a same name.

 

How to implement Overloading in Java

Following are the rules to implement Overloading of methods :

  1. All the methods that take park in Overloading should have the same name.
  2. No two methods should have the same set of arguments. They should differ either in
    • the number of arguments they have in their definition or
    • the type of arguments they have in their definition

If a method is not found for a set of arguments, the compiler does Type Promotion and checks for a suitable method definition. We shall learn in detail about Type Promotion with an example in due course of this tutorial.

Note : Different Return types do not make two methods different with respect to Overloading in Java.

 

Example of Overloading in Java

We shall use the same example of addition to demonstrate Overloading in Java

Now we shall cross verify the rules that we already stated with the above program.

  1. All the five methods that take part in overloading have same method name “add”.
  2. No two definitions of add function have same set of arguments. One add method have (int, int), another has (int, float), etc.

 

Type promotion during method Overloading

If a method is not found for a set of arguments, the compiler does Type Promotion and checks for a suitable method definition. Following diagram shows different type promotions that are possible.

Overloading in Java - Java Tutorial - www.tutorialkart.com

If there is forward path between two data types, then the starting datatype in the path can be type promoted to the datatype at end of the path.

  • byte can be type promoted to short.
  • short can be type promoted to int.
  • Implication can be applied in type promotion. i.e., if byte can be promoted to short and short can be promoted to int, then byte can be promoted to int. Also byte can be promoted to long, double or float.

We shall use the same Calculation class, but remove the definition add(int, int). As we have add(int, float), even we make a call add(int, int), as int can be promoted to float, double or long, we have add(int, float) and add(int, double) which are potential overloadable methods.

Int has been promoted to Float.

Now, we shall remove add(int, float) and see the result.

For both add(int, int) and add(int, float), add(int, double) has been called i.e., int and float are promoted to double.
You may experiment with other type promotions and verify the results with the type promotions presented in the picture.

 

Conclusion :

In this Java Tutorial, we have learnt about Overloading in Java with an Example program of adding two numbers for different set of input arguments and also type promotions that are possible with different data types in Java  for overloading methods. In our next tutorial, we shall learn about Overriding in Java.

 

How to reverse a String in Java ?

Java Tutorial – We shall learn how to reverse a String in Java Programming Language.

Reverse a String in Java

We shall get the bytes of given String and order them in reverse fashion.

Following is the Java Example to reverse a String :

When the above program is run, output to the console is as shown in the following :

Conclusion :

In this Java Tutorial, we have learnt how to reverse a given String in Java.

Following are some of the other Java String Examples :

Replace all occurrences of a substring with another in a string using Java

In this Java Tutorial, we shall see how to use String.replaceAll(String subString, String otherString) method to replace all occurrences of a substring with another in a string using Java.

Replace all occurrences of a substring with another in a string using Java

Following is the Java Example program to replace all occurrences of a substring with another in a string using Java.

When the above program is run, the output to the console is as shown in the following :

Conclusion :

In this Java Tutorial, we have learnt how to replace all occurrences of a substring with another in a string.

Following are some of the other Java String Examples :

How to get the index of first occurrence of a substring in a String using Java ?

In this Java Tutorial, we shall learn to get the index of first occurrence of a substring in a String using Java Programming Language.

Get the index of first occurrence of a substring in a String using Java ?

We shall make use of String.indexOf(String otherString) method, to find the index of first occurrence of a substring. If the substring is present in the string, it returns the index of its first occurrence, else it returns -1 indicating that the substring specified is not present in the string.

Following the Java Example to get the index of first occurrence of a substring

When the above program is run, the output to the console is as shown below :

Following is the Java Example to get the index of first occurrence of a substring in string, reading both the strings from console input

When the above program is run, the output to the console is as shown below :

Conclusion :

In this Java Tutorial, we have learnt how to get index of first occurrence of a substring in a String using Java Programming Language.

Following are some of the other Java String Examples :

How to check if two Strings are Equal in Java ?

In this Java Tutorial, we shall see how to check if two Strings are Equal in Java using the method String.equals(String anotherString). Also, we shall see a program to ignore the case, and check if two Strings are Equal.

Java Example program to check if two Strings are Equal

When the program is run, the output to the console is as shown in the following :

Java Example program to check if two Strings are Equal, with input strings read from console

When the program is run, the output to the console is as shown in the following :
 

Java Example program to ignore the case of characters in the Strings and check if two Strings are Equal

When the program is run, the output to the console is as shown in the following :

Java Example program to ignore the case of characters in the Strings and check if two Strings are Equal, with input strings read from console

When the program is run, the output to the console is as shown in the following :

Conclusion :

In this Java Tutorial, we have learned to check if two strings are equal in Java, with inputs given directly in the program or read from the console, and ignoring the case of characters in the string if necessary.

Following are some of the other Java String Examples :

How to read a String from console input in Java ?

Read a String from console input in Java

In this Java Tutorial, we shall use Scanner scanner = new Scanner(System. in); to read a String from console input in Java.

When the program is run, the execution waits after printing “Enter a string : “, where you would enter a string like “hello world”. The program prints the string read from the console input in the next step. The whole output in the console would be as shown in the following :

System.in

In the context of reading something from console, System class provides a means to access standard input through one of its fields, in. ‘in’ field is a Stream (to be specific, its a InputStream), which is declared public static and final. Hence, one can use ‘in’ directly without any initialization.Typically this InputStream corresponds to keyboard input or another input source specified by the host environment or user.

Conclusion :

In this Java Tutorial, we have learnt to use Scanner scanner = new Scanner(System. in); to read a String from console input in Java.

 Following are some of the other Java String Examples :