UNIT 3
Java as Object Oriented Programming Language Overview
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is −
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.
For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares −
Key takeaway
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Fig 1 - Example
There are two types of array.
Single Dimensional Array in Java
Syntax to Declare an Array in Java
Instantiation of an Array in Java
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
Let's see the simple example to print this array.
Output:
33
3
4
5
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
Output:
3
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.
Output:
10
22
44
66
Returning Array from the Method
We can also return an array from the method in Java.
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or greater than the array size while traversing the array.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
Example to instantiate Multidimensional Array in Java
Example to initialize Multidimensional Array in Java
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
Output:
1 2 3
2 4 5
4 4 5
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of arrays with different number of columns.
Output:
0 1 2
3 4 5 6
7 8
What is the class name of Java array?
In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object.
Output:
We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method
Example of Copying an Array in Java
Output:
caffein
Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java array which means it copies the references.
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
Output:
2 6 8
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix which can be understood by the image given below.
Fig 2 – Matrix example
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
Output:
6 6 6
12 12 12
18 18 18
Key takeaway
Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimensional or multidimensional arrays in Java.
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
is same as:
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Fig 3 - String
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
Fig 4 – CharSequence
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what is String in Java and how to create the String object.
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
Java String literal is created by using double quotes. For Example:
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
Fig 5 - Example
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
java
strings
example
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No. | Method | Description |
1 | char charAt(int index) | returns char value for the particular index |
2 | int length() | returns string length |
3 | static String format(String format, Object... args) | returns a formatted string. |
4 | static String format(Locale l, String format, Object... args) | returns formatted string with given locale. |
5 | String substring(int beginIndex) | returns substring for given begin index. |
6 | String substring(int beginIndex, int endIndex) | returns substring for given begin index and end index. |
7 | boolean contains(CharSequence s) | returns true or false after matching the sequence of char value. |
8 | static String join(CharSequence delimiter, CharSequence... elements) | returns a joined string. |
9 | static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | returns a joined string. |
10 | boolean equals(Object another) | checks the equality of string with the given object. |
11 | boolean isEmpty() | checks if string is empty. |
12 | String concat(String str) | concatenates the specified string. |
13 | String replace(char old, char new) | replaces all occurrences of the specified char value. |
14 | String replace(CharSequence old, CharSequence new) | replaces all occurrences of the specified CharSequence. |
15 | static String equalsIgnoreCase(String another) | compares another string. It doesn't check case. |
16 | String[] split(String regex) | returns a split string matching regex. |
17 | String[] split(String regex, int limit) | returns a split string matching regex and limit. |
18 | String intern() | returns an interned string. |
19 | int indexOf(int ch) | returns the specified char value index. |
20 | int indexOf(int ch, int fromIndex) | returns the specified char value index starting with given index. |
21 | int indexOf(String substring) | returns the specified substring index. |
22 | int indexOf(String substring, int fromIndex) | returns the specified substring index starting with given index. |
23 | String toLowerCase() | returns a string in lowercase. |
24 | String toLowerCase(Locale l) | returns a string in lowercase using specified locale. |
25 | String toUpperCase() | returns a string in uppercase. |
26 | String toUpperCase(Locale l) | returns a string in uppercase using specified locale. |
27 | String trim() | removes beginning and ending spaces of this string. |
28 | static String valueOf(int value) | converts given type into string. It is an overloaded method. |
Key takeaway
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
3. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
4. String s=new String(ch);
is same as:
2. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
Fig 6 - Objects
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
An object has three characteristics:
Fig 7 – Characteristics of object
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fig 8 – Class in java
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of MethodThe new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
Output:
0
null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java
Output:
0
null
There are 3 ways to initialize object in Java.
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
File: TestStudent2.java
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
Output:
101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
Output:
111 Karan
222 Aryan
Fig 9 - Example
As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
3) Object and Class Example: Initialization through a constructor
We will learn about constructors in Java later.
Object and Class Example: Employee
Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
Output:
55
45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
We will learn these ways to create object later.
Fig 10 – Different ways to create an object in java
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
Calling method through a reference:
Calling method through an anonymous object
Let's see the full example of an anonymous object in Java.
Output:
Factorial is 120
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
Initialization of refernce variables:
Let's see the example:
Output:
55
45
File: TestAccount.java
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. We can also easily modify code using methods. In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a method in Java.
A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method.
The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.
Fig 11 – Method declaration
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier:
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it is known as method overloading.
There are two types of methods in Java:
In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints Java on the console.
Let's see an example of the predefined method.
Demo.java
Output:
The maximum number is: 9
In the above example, we have used three predefined methods main(), print(), and max(). We have used these methods directly without declaration because they are predefined. The print() method is a method of PrintStream class that prints the result on the console. The max() method is a method of the Math class that returns the greater of two numbers.
When we go through the link and see the max() method signature, we find the following:
Fig 12 - Example
In the above method signature, we see that the method signature has access specifier public, non-access modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
We have defined the above method named findevenodd(). It has a parameter num of type int. The method does not return any value that's why we have used void. The method body contains the steps to check the number is even or odd. If the number is even, it prints the number is even, else prints the number is odd.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method.
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the sum.
Addition.java
Output:
The sum of a and b is= 24
A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the main() method.
Display.java
Output:
It is an example of a static method.
The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an instance method.
InstanceMethodExample.java
Output:
The sum is: 25
There are two types of instance method:
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value of the private field. It is used to get the value of the private field.
Example
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the private field.
Example
Example of accessor and mutator method
Student.java
The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.
Syntax
Demo.java
Output:
Abstract method...
It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();
Key takeaway
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
An object has three characteristics:
Java return keyword is used to complete the execution of a method. The return followed by the appropriate value that is returned to the caller. This value depends on the method return type like int method always return an integer value.
Examples of Java return Keyword
Let's see a simple example to return integer value.
Output:
10
Let's see an example to determine whether we can use return in void method.
Output:
Void methods cannot return a value
Let's see an example to return string.
Output:
[Java, C++, Python]
Key takeaway
Java return keyword is used to complete the execution of a method. The return followed by the appropriate value that is returned to the caller. This value depends on the method return type like int method always return an integer value.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
There are two types of constructors in Java:
Fig 13 – Types of constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. |
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.Fig 14 - Example
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
Example of default constructor that displays the default values
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.
Java Constructor | Java Method |
A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
A constructor must not have a return type. | A method must have a return type. |
The constructor is invoked implicitly. | The method is invoked explicitly. |
The Java compiler provides a default constructor if you don't have any constructor in a class. | The method is not provided by the compiler in any case. |
The constructor name must be same as the class name. | The method name may or may not be same as the class name. |
Fig 15 – Difference between constructor and method
There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
In this example, we are going to copy the values of one object into another using Java constructor.
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
Output:
111 Karan
111 Karan
Key takeaway
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Fig 16 – This keyword
Here is given the 6 usage of java this keyword.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
Fig 17 - Usage
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keywordLet's understand the problem if we don't use this keyword by the example given below: |
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keywordOutput:
111 ankit 5000
112 sumit 6000
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
Program where this keyword is not requiredOutput:
111 ankit 5000
112 sumit 6000
It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters in real time, and always use this keyword.2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
Fig 18 - Example
Output:
hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
Output:
hello a
10
Calling parameterized constructor from default constructor:
Output:
5
hello a
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.
Output:
111 ankit java null
112 sumit java 6000
Rule: Call to this() must be the first statement in constructor.Compile Time Error: Call to this must be first statement in constructor
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:
Output:
method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.
5) this: to pass as argument in the constructor call
We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:
Output:10
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
Example of this keyword that you return as a statement from the method
Output:
Hello java
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same. |
Output:
A5@22b3ea59
A5@22b3ea59
Key takeaway
Here is given the 6 usage of java this keyword.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
How can an object be unreferenced?
There are many ways:
Fig 19 – How can an object be unreferenced?
2) By assigning a reference to another:
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
Simple Example of garbage collection in java
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.
Key takeaway
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
Throwable - the Exception is raised by this method
Output:
2018699554
end of garbage collection
finalize method called
Key takeaway
Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
Output:
main with String[]
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:
Fig 20 Method Overloading and Type Promotion
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float or double and so on.
Example of Method Overloading with TypePromotion
Output:40
60
Example of Method Overloading with Type Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
Output:int arg method invoked
Example of Method Overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.
Output:Compile Time Error
One type is not de-promoted implicitly for example double cannot be depromoted to any type implicitly.
Key takeaway
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method. |
|
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example: |
Output:before change 50
after change 50
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:
Output:before change 50
after change 150
Key takeaway
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method. |
Objects as Parameters
A method can take an objects as a parameter. For example, in the following program, the method setData( ) takes three parameter. The first parameter is an Data object. If you pass an object as an argument to a method, the mechanism that applies is called pass-by-reference, because a copy of the reference contained in the variable is transferred to the method, not a copy of the object itself.
Program
Program Source
class Data {
int data1;
int data2;
}
class SetData {
void setData(Data da,int d1,int d2)
{
da.data1 = d1;
da.data2 = d2;
}
void getData(Data da)
{
System.out.println("data1 : "+da.data1);
System.out.println("data2 : "+da.data2);
}
}
public class Javaapp {
public static void main(String[] args) {
Data da = new Data();
SetData sd = new SetData();
sd.setData(da,50,100);
sd.getData(da);
}
}
Key takeaway
A method can take an objects as a parameter. For example, in the following program, the method setData( ) takes three parameter. The first parameter is an Data object. If you pass an object as an argument to a method, the mechanism that applies is called pass-by-reference, because a copy of the reference contained in the variable is transferred to the method, not a copy of the object itself.
As we know it is core concept that in Java there is always pass by value and not by pass by reference. So in this post we will focus on that how this concept get validated in case of passing primitive and passing reference to a method.
In case when a primitive type is passed to a method as argument then the value assigned to this primitive is get passed to the method and that value becomes local to that method,which means that any change to that value by the method would not change the value of primitive that you have passed to the method.
While in case of passing reference to a method again Java follow the same rule of pass by value now let understand how it happens.
As we know that a reference in Java holds the memory location of object created if it is assigned to that reference otherwise it is initiated as null.Now the point to remember here is that the value of the reference is the memory location of the assigned object,so whenever we pass the reference to any method as argument then we actually pass the memory location of that object which is assigned to that particular reference.This technically means that the target method has memory location of our created object and can access it to.So in case if target method access our object and make changes to any of property of it than we would encounter with the changed value in our original object.
public class PassByValue {
static int k =10;
static void passPrimitive(int j) {
System.out.println("the value of passed primitive is " + j);
j = j + 1;
}
static void passReference(EmployeeTest emp) {
EmployeeTest reference = emp;
System.out.println("the value of name property of our object is "+ emp.getName());
reference.setName("Bond");
}
public static void main(String[] args) {
EmployeeTest ref = new EmployeeTest();
ref.setName("James");
passPrimitive(k);
System.out.println("Value of primitive after get passed to method is "+ k);
passReference(ref);
System.out.println("Value of property of object after reference get passed to method is "+ ref.getName());
}
}
class EmployeeTest {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
the value of passed primitive is 10
Value of primitive after get passed to method is 10
the value of name property of our object is James
Value of property of object after reference get passed to method is Bond
Key takeaway
As we know it is core concept that in Java there is always pass by value and not by pass by reference. So in this post we will focus on that how this concept get validated in case of passing primitive and passing reference to a method.
In case when a primitive type is passed to a method as argument then the value assigned to this primitive is get passed to the method and that value becomes local to that method,which means that any change to that value by the method would not change the value of primitive that you have passed to the method.
While in case of passing reference to a method again Java follow the same rule of pass by value now let understand how it happens.
What are final classes in Java?
The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
You cannot extend a final class. If you try it gives you a compile time error.
final class Super {
private int data = 30;
}
public class Sub extends Super{
public static void main(String args[]){
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at newJavaExamples.Sub.main(Sub.java:9)
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
Java static nested class example with instance method
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
Internal class generated by the compiler
Java static nested class example with static method
If you have the static member inside static nested class, you don't need to create instance of static nested class.
Output:
data is 30
Java Inner Classes
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
Syntax of Inner classAdvantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Do You Know
Difference between nested class and inner class in Java
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
- Member inner class
- Anonymous inner class
- Local inner class
Type | Description |
Member Inner Class | A class created within class and outside method. |
Anonymous Inner Class | A class created for implementing interface or extending class. Its name is decided by the java compiler. |
Local Inner Class | A class created within method. |
Static Nested Class | A static class created within class. |
Nested Interface | An interface created within class or interface. |
Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are −
Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
Variables and methods can be declared without any modifiers, as in the following examples −
String version = "1.5.1";
boolean processOrder() {
return true;
}
Private Access Modifier - Private
Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
The following class uses private access control −
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.
Public Access Modifier - Public
A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
The following function uses public access control −
public static void main(String[] arguments) {
// ...
}
The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.
Protected Access Modifier - Protected
Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
The following parent class uses protected access control, to allow its child class override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer extends AudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier.
Access Control and Inheritance
The following rules for inherited methods are enforced −
Key takeaway
The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
You cannot extend a final class. If you try it gives you a compile time error.
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt. |
Output: Your first argument is: sonoo
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop. |
Output: sonoo
jaiswal
1
3
Abc
Key takeaway
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Since JSE1.5 you can pass a variable number of values as argument to a method. These arguments are known as var args and they are represented by three dots (…)
public myMethod(int ... a) {
// method body
}
In the following example, the method named sample() accepts varargs (of type String) and from the main method, we are invoking this method multiple times by passing a different number of arguments each time we invoke it.
public class VarargsExample{
void sample(String... args) {
for (String arg: args) {
System.out.println(arg);
}
}
public static void main(String args[] ){
VarargsExample obj = new VarargsExample();
obj.sample("Ram", "Rahim", "Robert");
obj.sample("Krishna", "Kasyap");
obj.demoMethod("Vanaja");
}
}
Ram
Rahim
Robert
Krishna
Kasyap
Vanaja
When to use − Whenever, you want to pass different number of arguments each time you call a method you should use vararg methods.
In the following example the sample() method accepts varargs of type integer and from the main method we are invoking this method multiple times and, we are passing different number of integer arguments each time we invoke it.
public class VarargsExample{
void demoMethod(int... args) {
for (int arg: args) {
System.out.println(arg);
}
}
public static void main(String args[] ){
VarargsExample obj = new VarargsExample();
obj.demoMethod(1101, 10225, 26);
obj.demoMethod(22365, 12);
obj.demoMethod(1);
}
}
1101
10225
26
22365
12
1
Key takeaway
Since JSE1.5 you can pass a variable number of values as argument to a method. These arguments are known as var args and they are represented by three dots (…)
public myMethod(int ... a) {
// method body
}
References:
1. T. W. Pratt, M. V. Zelkowitz, "Programming Languages Design and Implementation‖, 4th Ed, PHI, ISBN 81-203-2035-2.
2. Sebesta R., "Concepts of Programming Languages", 4th Edition, Pearson Education, ISBN81-7808-161-X.
3. Herbert Schildt, "The Complete Reference Java", 9th Ed, TMH,ISBN: 978-0-07-180856-9.
4. Dr.R. Nageshwar Rao, "Core Java: An Integrated Approach", Dreamtech Press
5. Deugo, ―Java Gems‖, Cambridge University Press, ISBN 10: 0521648246 ISBN 13: 9780521648240
6. Carl Townsend,” Programming in turbo PROLOG”, Tata-McGraw Hill
7. Ivan Bratko, “Prolog Programming for Artificial Intelligence”, Wesley Publishers Limited
8. Winston P., Klaus B., Horn P., "LISP", 3rd Edition, Pearson Education, 81 - 7808 -155-5
9. Carlo Ghezzi, Mehdi Jazayeri, ―Programming Language Concepts‖,3rd Ed, Wiley Publication ISBN : 978-81-265-1861-6.