Wednesday, 29 April 2015

Why main method is static in Java

When we start learning java and make our first "Hello World" program, there are two things which stand out.

Here we'll talk about the main method. Coming to main method signature it is easy to see that main method is -

  • Public - Access modifier is public so that main method is visible to every other class, same package or other. If it is not public JVM classes will not be able to access it.
  • Void - As it does not return any value.
  • String[] args - arguments to this method. The main method takes an array of Strings as parameter, that array is called 'args'.

But why static is a question that needs some explanation.

In the post Why file name and class name should be same in Java it has already beed discussed that at run time class name should be same, as that's how JVM knows which class to load and where is the entry point (main method).

But the question here is, how will JVM access that main method with out creating an instance of the class, answer is having main method as static.

If it is not declared as static then instance of the class has to be created which may cause ambiguity, consider the example -

public class A {
 private int i;
  A(int i){
  this.i = i;
 }
 public static void main(String args[]){
  A a = new A(5);
 }
}

Here in the class there is a constructor with one argument i. Assume that the main method is not static, which means JVM has to directly create the instance of class A to execute the main method. But in order to create an object of the class constructor has to be invoked which brings up the question what should be passed as i?

JVM wouldn't know with what values your object has to be initialized. So you have a catch22 situation here in order to get an object of the class this line A a = new A(5); has to be executed and to execute this line instance of the class is needed if there is no static method in the class.

To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static in Java.

Points to note -

  • main method must be declared public, static and void if any of these are missing; java program will compile but at run time error will be thrown.
  • At run time interpreter is given the class file which has main method, thus main method is entry point for any java program.
  • Declaring main method as static ensures that JVM can invoke the entry point (main method) with out creating any instance of the class.
  • With varargs in Java 5 onward it is possible to write the main method as public static void main(String ... args).

That's all for this topic Why main method is static in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. static in Java
  2. static method overloading or overriding in Java
  3. static import in Java
  4. static reference to the non-static method or field error
  5. static block in Java
  6. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Why class name and file name should be same in Java

When we start learning java and make our first "Hello World" program, there are two things that stand out.

  • File name and class name should be same.
  • Main method signature - Public static void main(String[] args)

Here we'll talk about having this requirement that File name and class name should be same. Let be clear on one point; this requirement is not mandatory unless until there is a public class in the file.

If there is public class in the file then it has to be saved with the same file name.

Let's see the case when we have a public class.

public class Test {
    public static void main(String[] args) {
        System.out.println("This is a test class");
    }

}

If we save it as Thetest.java then we'll get an error while trying to compile it.

class name and file name should be same

It can be seen how compiler complains about having the public class Test and how it should be declared as Test.java.

Now if we save the class as Test.java then it compiles and runs just fine.

class name and file name should be same

Now let's take an example when there is no public class -

class FinalClass{
 String a;
 final void finalMethod(){

 }

}
class FinalClassDemo {
 public static void main(String[] args) {

 }

}

I have this file with 2 classes and none of them is public, now I can save it as any name, let's say I saved it as ABC.java. Yes, it is possible if there is no class with access modifier as public. But that is only half of the truth! When this java file is compiled it will create 2 classes

FinalClassDemo.class
FinalClass.class

It can be seen that even if the file name is different compiled classes have the same name as the class names.

Now if we have to run it then we have to use -

java FinalClassDemo

This shows that at compile time file name may be different from the class name (provided there is no public class in the file) but at the run time it has to be same.

So the next question is why even that restriction to have the same name as class name at run time.
Answer is that is how java interpreter will know which class to load and where is the entry point (main() method) otherwise interpreter may have to scan a lot of class files to determine where to start.

Points to note -

  • If there is no public class then file name may be different from the class name.
  • In case there is a public class then it is enforced that the file name is same as the public class.
  • Even, in the case, where the file name is different, after compilation .class files have the same name as the class names.
  • Having the same name as class name is how the JVM will know which class to load and where to look for entry point (main method).

That's all for this topic Why class name and file name should be same in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why main method static in Java
  2. Java pass by value or pass by reference
  3. What are JVM, JRE and JDK in Java
  4. Object in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Object in Java

In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class.

As explained in the post Class in Java when a new class is created essentially a new data type is created. This type can be used to declare objects of that type.

An object stores its state in fields and exposes its behavior through methods.

Creating Objects

Creation of an object for a class is done in three steps -
  • Declaration - Declare a variable of the class type, note that no object is defined yet. This variable can refer to an object as and when the object is created.
  • Instantiation - Create an object and assign it to the variable created in step 1. This object creation is done using new operator.
  • Initialization - Class name followed by parenthesis after the new operator (new classname()) means calling the constructor of the class to initialize the object.

As Example

If we have a class called Rectangle as this -

class Rectangle{
    double length;
    double width;
    
    //methods 
    ……
    ……
}

Then declaring object of the class Rectangle would be written as -

Rectangle rectangle;

This statement declares an object rectangle of the class Rectangle. It does not hold any thing yet.

With the following statement a new object rectangle is created, which means rectangle objects holds reference to the created object of Rectangle class.

rectangle = new Rectangle();
Decalring an object in Java
Declaring an object of type Rectangle

As it can be seen from the figure the rectangle variable holds reference to the allocated Rectangle object.

The new operator allocates memory for an object at run time and returns a reference to that memory which is then assigned to the variable of the class type.

In the statement new Rectangle(), the class name Rectangle() followed by parenthesis means that the constructor of the class Rectangle would be called to initialize the newly created object.

Generally this three step process of declaring, creating and initializing an object is written in a single statement like -

Rectangle rectangle = new Rectangle();
This encapsulation of variables and methods into a class and using them through objects provides a number of benefits including -
  • Modularity - The application can be divided into different functional categories. Then code can be written for many independent objects implementing the specific functionality. Once created an object can be easily passed around inside the system creating a series of operations to execute functionality.
  • Information-hiding- By encapsulating the variables and methods and providing interaction to the outside entities only through object's methods, an object hides its internal implementation from the outside world.
  • Code re-use - While working on an application we use several third party libraries. That is an example how we use several already existing objects (already created and tested) in our application.
  • Pluggability and debugging ease - Since a whole application comprises of several working components in form of objects, we can simply remove one object and plug in another as replacement in case a particular object is not providing the desired functionality.

That's all for this topic Object in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Object creation using new operator in Java
  2. Object class in Java
  3. this in Java
  4. finalize method in Java
  5. Java OOP interview questions

You may also like -

>>>Go to Java Basics page

abstract class in Java

An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.
The declaration of an abstract method starts with the abstract keyword and ends with a semicolon, it does not have a method body.

abstract type method_Name(parameter_list);

If a class contains an abstract method, either declared or inherited from another class, it must be declared as an abstract class.

Usage of Abstract class

There are situations when one wants to define a generalized structure using a super class without providing a complete implementation of every method. In that case sub classes have the responsibility to provide implementation for the methods. Thus, super class just provides the structure of a given abstraction that must be extended and implemented by the corresponding sub-classes.

Example of an Abstract class

Let's say we have an abstract class shape which defines the general structure for the 2D figures and declare the area method in the super class as abstract. That would mean that any sub-class extending the super class has to provide an implementation of meaningful area method.

abstract class Shape{
 double length;
 double breadth;
 //Constructor
 Shape(double length, double breadth){
  this.length = length;
  this.breadth = breadth;
 }
 // Abstract method
 abstract void area();
 
}

class Triangle extends Shape{
 //constructor to initialize length
 Triangle(double i, double j){
  super(i, j); // calling the super class constructor  
 }
 // Abstract method implementation for Triangle class
 void area(){
  System.out.println("In area method of Triangle");
  System.out.println("Area of square - " + (length * breadth)/2);
 }
}

class Rectangle extends Shape{
 //constructor to initialize length
 Rectangle(double i, double j){
  super(i, j); 
 }
 // Abstract method implementation for Rectangle class
 void area(){
  System.out.println("In area method of Rectangle");
  System.out.println("Area of Rectangle - " + length * breadth);;
 }
}

Restrictions with Abstract Classes

  • Any class that contains one or more abstract methods must also be declared abstract.
  • Abstract class can not be directly instantiated so there can't be any object of an abstract class.
  • Any class that extends an abstract class must provide implementation of all the abstract methods in the super class; otherwise the sub-class must be declared abstract itself.
  • There can't be an abstract constructor or abstract static method.

Abstract class and run time polymorphism

As we already know that there can't be an object of an abstract class, but abstract class can be used to create object references. As run time polymorphism in Java is implemented through the use of super class reference and abstract class is deigned to be used as a super class with generalized structure. Thus, it is imperative that abstract class reference could be created which can be used to refer to subclass object.

Example

If we take the same shape class as used above
abstract class Shape{
 double length;
 double breadth;
 //Constructor
 Shape(double length, double breadth){
  this.length = length;
  this.breadth = breadth;
 }
 // Abstract method
 abstract void area();
 
}

class Triangle extends Shape{
 //constructor to initialize length
 Triangle(double i, double j){
  super(i, j); // calling the super class constructor  
 }
 // Abstract method implementation for Triangle class
 void area(){
  System.out.println("In area method of Triangle");
  System.out.println("Area of square - " + (length * breadth)/2);
 }
}

class Rectangle extends Shape{
 //constructor to initialize length
 Rectangle(double i, double j){
  super(i, j); 
 }
 // Abstract method implementation for Rectangle class
 void area(){
  System.out.println("In area method of Rectangle");
  System.out.println("Area of Rectangle - " + length * breadth);;
 }
}

public class PolymorphicTest {
 public static void main(String[] args){
  // Abstract class reference
  Shape shape;
  Triangle triangle = new Triangle(5, 6); 
  Rectangle rectangle = new Rectangle(7, 5); 
  // shape dynamically bound to the Triangle object
  shape = triangle;
  // area method of the triangle called
  shape.area(); 
   // shape dynamically bound to the Rectangle object
  shape = rectangle;
  // area method of the rectangle called 
  shape.area(); 
 }
}

Output

In area method of Triangle
Area of square - 15.0
In area method of Rectangle
Area of Rectangle - 35.0

It can be seen that a reference of an abstract class is created

Shape shape;

That shape reference refers to the object of Triangle class at run time first and then object of Rectangle class and appropriate area method is called.

Abstract class with interfaces

If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.

public interface MyInterface {
 void method1();
 String method2(String Id);
}
abstract class in Java
Error if all methods of interface are not implemented

But we can declare the class as abstract in that case

public abstract class AbstractClassDemo implements MyInterface {
 public static void main(String[] args) {
  System.out.println();

 }

}

Points to note -

  • There can be a class declared as abstract that provides implementation of all the methods in a class i.e. no abstract method in the class but vice versa is not true, if there is any abstract method in a class then the class must be declared abstract.
  • Abstract class may have some methods with implementation and some methods as abstract.
  • Abstract classes can not be instantiated to create an object.
  • An object reference of an abstract class can be created.
  • If a class implements an interface and does not provide implementation for all the interface methods, it must be declared abstract.

That's all for this topic Abstract class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Polymorphism in Java
  2. Inheritance in Java
  3. Class in Java
  4. final in Java
  5. interface in Java
  6. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Tuesday, 28 April 2015

final in Java

final keyword in java has its usage in preventing the user from modifying a field, method or class.

final variable in Java

A variable can be declared as final which prevents its contents from being modified. A final variable can be initialized only once but it can be done in two ways.

  • Value is assigned when the variable is declared.
  • Value is assigned with in a constructor.

Please note that the final variable that has not been assigned a value while declaring a variable is called blank final variable, in that case it forces the constructor to initialize it.

Final variable examples

final variable value can't be changed

Compilation error if value of a final variable is changed in the setter method.

final variable value can't be changed

Compilation error if value of a final variable is changed using an object.

Final blank variable example

final blank variable

Compilation error that the blank final variable is not initialized. In that case this variable should be initialized in a constructor of the class.

Final object

Making an object reference variable final is a little different from a normal variable as in that case object fields can still be changed but the reference can't be changed. That is applicable to collections too, a collection declared as final means only its reference can't be changed values can still be added, deleted or modified in that collection.

Example of final object

final method parameter

Parameters of a method can also be declared as final to make sure that parameter value is not changed in the method. Since java is pass by value so changing the parameter value won't affect the original value anyway. But making the parameter final ensures that the passed parameter value is not changed in the method and it is just used in the business logic the way it needs to be used.

Final variables and thread safety

Variables declared as final are essentially read-only thus thread safe.

Also if any field is final it is ensured by the JVM that other threads can't access the partially constructed object, thus making sure that final fields always have correct values when the object is available to other threads.

final with inheritance

The use of final with the method or class apply to the concept of inheritance. You can have a final method or a final class ensuring that a method declared as final can't be overridden and the class declared as final can't be extended.

final method

A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

If creator of the class is sure that the functionality provided in a method is complete and should be used as is by the sub classes then the method should be declared as final.

Benefit of final method

Method's declared as final may provide performance enhancement too. Generally in Java, calls to method are resolved at run time which is known as late binding.

Where as in case of final methods since compiler knows these methods can not be overridden, call to these methods can be resolved at compile time. This is known as early binding. Because of this early binding compiler can inline the methods declared as final thus avoiding the overhead of method call.

Final method example

Final Class

A class declared as final can't be extended thus avoiding inheritance altogether.

If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.

Declaring a class as final implicitly means that all the methods of the class are final too as the class can't be extended.

It is illegal to declare a class as both final and abstract. Since abstract class by design relies on subclass to provide complete implementation.

Example of final class

Benefits of final class

  • Since all the methods in a final class are implicitly final thus final class may provide the same performance optimization benefit as final methods.
  • Restricting extensibility may also be required in some cases essentially when using third party tools.
  • A class may be declared final to enforce immutability.

Points to note -

  • final keyword can be used with fields, methods and classes.
  • final variables are essentially read only and it is a common convention to write the final variables in all caps. As example
    Private final int MAXIMUM_VALUE = 10
  • final variables that are not initialized during declaration are called blank final variable in that case it forces the constructor to initialize it. Failure to do so will result in compile time error.
  • final variables can be initialized only once, assigning any value there after will result in compile time error.
  • final variables are read-only thus thread safe.
  • In case of Final object reference can't be changed.
  • final methods can't be overridden
  • final classes can't be extended.
  • final methods are bound during compile time (early binding), which means compiler may inline those methods resulting in performance optimization.

That's all for this topic final in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. finalize method in Java
  2. finally block
  3. final Vs finally Vs finalize
  4. Method Overloading in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Monday, 27 April 2015

static in Java

When we want to define a class member that can be used independently of any object of that class we use static keyword. When a class member is defined as static it is associated with the class, rather than with any object.

The static can be used with -

Static Variable in Java

A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable. A static variable can be accessed directly by the class name and doesn't need any object.

Since static variables are associated with the class, not with instances of the class, they are part of the class data in the method area.

Usage of Static variable

One common use of static is to create a constant value that's at a class level and applicable to all created objects, it is a common practice to declare constants as public final static, static so that it is at class level, shared by all the objects. final so that the value is not changed anytime.

Example

public class Employee {
 int empId;
 String name;
 String dept;
 // static constant
 static final String COMPANY_NAME = "XYZ";
 Employee(int empId, String name, String dept){
  this.empId = empId;
  this.name = name;
  this.dept = dept;
 }
 
 public void displayData(){
  System.out.println("EmpId = " + empId + " name= " + name + " dept = " + 
  dept + " company = " + COMPANY_NAME);
 }
 public static void main(String args[]){  
  Employee emp1 = new Employee(1, "Ram", "IT");
  Employee emp2 = new Employee(2, "Krishna", "IT");
  emp1.displayData();
  emp2.displayData();
 }
}
Output
EmpId = 1 name= Ram dept = IT company = XYZ
EmpId = 2 name= Krishna dept = IT company = XYZ

Another usage is when there is a requirement to have a counter at the class level. Since static variable is associated to the class and will have the same value for every instance of the class, where as value of non static variable will vary from object to object. So any counter which should be at the class level has to be declared as static.

Example

class Counter{
 // at class level and gets memory only once
 static int count = 0;
 
 Counter(){
  count++;
 }
 
}

Static Method in Java

Same as static variable, static method also is associated with the class rather than objects of the class. Static method can be called directly with the class name like ClassName.static_method() rather than with the object of the class.

main() method is the most common example of static method, main() method is declared static because main() must be called before any object of the class exists.

Usage of Static method

The most common usage of static method is to declare all the utility methods (like date formatting, conversion of data types) as static. Reason being these utility methods are not part of actual business functionality so should not be associated with individual objects.

Example of Static method

public class StaticDemo {
 static void staticMethod(int i){
  System.out.println("in static method " + i);
 }
 
 public static void main(String[] args) {  
  StaticDemo.staticMethod(5);
 }

}

It can be seen here that the staticMethod is accessed with the class itself.

StaticDemo.staticMethod(5);

Please note that it won't be an error if class object is used to access a static method, though compiler will warn to use class instead.

Restrictions with static method

  1. static method can directly call other static methods only.
    public class StaticDemo {
     // Non Static method
     void staticMethod(int i){
      System.out.println("in static method " + i);
     }
     
     public static void main(String[] args) {  
      staticMethod(5); // Compiler error
     }
    
    }
    
    It will throw compiler error "Can not make static reference to the non-static method".
  2. static method can directly access static data only
    public class StaticDemo {
     // non static field
     int i;
     
     public static void main(String[] args) {  
      i = 10; // Compiler error
     }
    
    }
    
    It will throw compiler error "Cannot make a static reference to the non-static field".
  3. Static methods cannot refer to this or super in any way.

Static Block in Java

A static block in a class is executed only once, when the class is first loaded, even before the main method.

Usage of Static Block

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
If some computation is needed, in order to initialize a static variable, that can be done in static block.

public class StaticDemo {
 // static blank final variable
 static final int i;
 static int b;
 static {
  System.out.println("in static block");
  i = 5;
  b = i * 5;
  System.out.println("Values " + i + " " +  b);
 }
 
 public static void main(String args[]){  
  System.out.println(" in main method ");
 }
}
Output of the program
in static block
Values 5 25
in main method

It can be seen that main method is called only after executing the static block. In static block the static blank final variable is initialized. Also Another static variable too is initialized with in the block after some computation.

Points to note -

  • static keyword can be used with variables, methods and nested class in Java. There can also be a static block.
  • static variables and methods are associated with class itself rather than with any object.
  • static variables will have a single copy that will be used by all the objects.
  • static fields are not thread safe so proper synchronization should be done in case of several threads accessing the static variable.
  • static methods can directly call other static methods only and directly access static fields only.
  • static methods can be overloaded but can not be overridden.
  • static block is executed in a class at the time of class loading even before the main method.
  • With static import it is possible to access any static member (static field or method) of the class with out qualifying it with class name.

That's all for this topic static in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. static import in Java
  2. static method overloading or overriding in Java
  3. Why main method static in Java
  4. interface static methods in Java 8
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Friday, 24 April 2015

Constructor Overloading in Java

Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

Why Constructor overloading is needed

To know why constructor overloading is needed first let's be aware of one fact - if any constructor is defined for a class then Java won't define a default constructor. Default constructor for the class will only be inserted in case no constructor is defined.

In that case if there is a constructor defined like -

class ConstrOverLoading{
 private int i;
 private int j;
 //Constructor with 2 params
 ConstrOverLoading(int i, int j){
  this.i = i;
  this.j = j;
 }
}  

As it can be seen the ConstrOverLoading() constructor takes 2 parameters. In this case all the objects of this class must have two parameters, For example the statement
ConstrOverLoading obj = new ConstrOverLoading();
Will be invalid because, as already told, if any constructor is defined for a class then Java won't define a default constructor.

In these type of situations overloaded constructors are required.

A practical example would be ArrayList class where there are 2 constructors related to initial capacity,

public ArrayList(int initialCapacity)
public ArrayList() {
    this(10);
}

In one of the case user can pass the initial capacity for the ArrayList, in another case user can use the no-arg constructor and ArrayList would have the default initial capacity of 10.

Using this with overloaded constructors

It is a common practice to use this with overloaded constructors and let only one of the constructor do the initialization, all the other constructors merely make a call to that constructor. Let's see it with an example.

Overloaded Constructor Example

class ConstrOverLoading {
 int a;
 double b;
 ConstrOverLoading(int a, double b){
  this.a = a;
  this.b = b;
 }
 ConstrOverLoading(int a){
  this(a, 0.0);
 }
 ConstrOverLoading(){
  this(0);
 }
 
}

It can be noticed here that only one of the contructor ConstrOverLoading(int a, double b) is doing any assignment other constructors are merely invoking that constructor through this(). This use of this helps in reducing the duplication of code.

Two points to note here -

  1. this() should be the first statement within the constructor in this case.
  2. this() and super() can't be used with in the same constructor as it is required for both to be the first statement in the class.

That's all for this topic Constructor Overloading in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Constructor in Java
  2. Constructor chaining in Java
  3. Method overloading in Java
  4. super in Java
  5. this in Java
  6. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Wednesday, 22 April 2015

Java pass by value or pass by reference

Java's parameter passing is pass by value or pass by reference is one question which causes a bit of confusion so let's try to clarify it.
Before going into whether java is pass by value or pass by reference let's first see what these 2 terms actually means.

  • Pass by value - In this case actual parameter is evaluated and its value is copied into memory(stack) used by the parameters of the method.
  • Pass by reference - In this case the memory address of the actual parameter is copied in the parameter of the method. Thus anytime method is using its parameter it is actually using the actual parameter.

In Java at least there is no confusion with primitive values as it is easy to see that primitives are passed by value.
Let's see it with an example -

public class A {
 
 void displayData(int i){  
  //value of the passed primitive variable changed
  i++;
  System.out.println("Value of i inside method "  + i);
 }  
 public static void main(String args[]){ 
  A a = new A();
  int i = 5;
  // Sending variable i as param
  a.displayData(i);  
  System.out.println("Value of i inside main "  + i);
 }  
}

Output of the program

Value of i inside method 6
Value of i inside main 5

Thus it can be seen that the changing of the passed int value in the method doesn't affect the original value.

With object passed as a parameter, people have some confusion whether it's pass by value or pass by reference. Before going it to it let's be very clear that in java every thing is pass by value whether primitives or objects. It does make sense as java has no pointers thus no way to send memory addresses of the variables.

But still if an object is passed as parameter in java and some variable in that object is changed in the method that change is global i.e. same value is reflected every where.
Let's see an example

public class A {
 private int i;
 //constructor
 A(int i){
  this.i = i;
 }

 void displayData(A obj){ 
  // object manipulated 
  obj.setI(7);
  System.out.println("Value of i inside method "  + obj.getI());
 }  
 public static void main(String args[]){ 
  A a = new A(5);
  System.out.println("Value of i inside main before method call "  + a.getI());
  a.displayData(a);  
  System.out.println("Value of i inside main after method call "  + a.getI());
 }
 //getter
 public int getI() {
  return i;
 }
//setter
 public void setI(int i) {
  this.i = i;
 }  
}

Output of the program

Value of i inside main before method call 5
Value of i inside method 7
Value of i inside main after method call 7

It can be seen from the output that changes done in the method displayData() are reflected globally. When value of i is printed after the method call it is changed. If java is pass by value then why that?

It is because when we say
A a = new A();

The new operator allocates memory for the created object and returns a reference to that memory which is then assigned to the variable of the class type.
So, it can be said “a” is a variable which is holding a value and that value happens to be the reference to the memory address.

When the method is called with
a.displayData(a);

copy of the reference value is created and passed into the other object which means in method void displayData(A obj) obj parameter holds the copy of the reference value thus a and obj both are references to the same memory given to the object. Refer to the image to have clarity.

pass by value or pass by reference

So to make it clear, in the case of object Java copies and passes the reference by value, not the object. That is why any manipulation of the object in the method will alter the object, since the references point to the original objects.

Let's write a program to see this statement "In the case of object Java copies and passes the reference by value" in detail.

public class A {
 private int i;
 A(int i){
  this.i = i;
 }
 void displayData(A obj){
  // change the reference
  obj = new A(8);
  System.out.println("Value of i inside method "  + obj.getI());
 }  
 public static void main(String args[]){ 
  A a = new A(5);
  System.out.println("Value of i inside main before method call "  + a.getI());
  a.displayData(a);  
  System.out.println("Value of i inside main after method call "  + a.getI());
 }
 
 // getter
 public int getI() {
  return i;
 }
 // setter
 public void setI(int i) {
  this.i = i;
 }  
}

In this program the reference of the object which was copied and passed as value to the parameter in method displayData() has been changed
obj = new A(8);
but it can be seen from the output that it doesn't change the original reference as it retains the original value of the variable i.

Value of i inside main before method call 5
Value of i inside method 8
Value of i inside main after method call 5

I hope I am able to make it clear that in Java, whether primitives or objects, everything is pass by value. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why main method static in Java
  2. Why file name and class name should be same in Java
  3. Constructor in Java
  4. static in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Tuesday, 21 April 2015

Java automatic numeric type promotion

In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.

As exp.

  byte a = 100;
  byte b = 50;
  int i = a * b;
  

in the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these type of situations Java will automatically promote the byte, short or char to int when evaluating an expression. Also, note that the result is assigned to an int variable i without any explicit casting as the result was already an int.

Rules for Type promotion

There are several type promotion rules that are followed while evaluating expressions-
  • All byte, short and char values are promoted to int.
  • If any operand is long then the expression result is long. i.e. whole expression is promoted to long.
  • If any operand is a float then the expression result is float. i.e. whole expression is promoted to float.
  • If any operand is a double then the expression result is double. i.e. whole expression is promoted to double.

Let's see an example depicting the rules -

automatic numeric type promotion

As shown in the code, since one of the value is float so the result should also be float and that's what the compiler is complaining about here.

Problems because of automatic type promotion

Sometimes automatic numeric promotion may cause confusing compilation problems.
Let's see it with an example -

automatic numeric type promotion

Here byte b has the value 2. Again I am trying to assign (b * 2) to b which is with in the range of byte (-128 to 127) but compiler complains "Can't convert from int to byte". This error is there because the byte is automatically converted to int at the time of evaluating the expression. If it has to be assigned to a byte then explicit casting is required.

b=(byte)b*2;

That's all for this topic Java automatic numeric type promotion. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. interface in Java
  2. Inheritance in Java
  3. Constructor in Java
  4. static in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

super in Java

The super keyword in java is essentially a reference variable that can be used to refer to class' immediate parent class.

Usage of super

  • Invoke the constructor of the super class.
  • Accessing the variables and methods of parent class.

First let's see how code will look like if super() is not used.

Let's say there is a super class Shape with instance variables length and breadth. Another class Cuboids extends it and add another variable height to it. With these 2 classes and not using super(), constructors of the class will look like -

public class Shape {
 int length;
 int breadth;
 Shape(){
  
 }
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 int height;
 Cuboids(int length, int breadth, int height){
  this.length = length;
  this.breadth = breadth;
  this.height = height;
 }
}

It can be noticed there are 2 problems with this approach -

  • Duplication of code as the same initialization code in the constructor is used twice.
  • Second and most important problem is super class instance variables should be given such an access modifier that they can be used in child class, thus violating the OOP principle of Encapsulation.

So super() comes to the rescue and it can be used by a child class to refer to its immediate super class.
Let's see how super() can be used.

Invoke the constructor of the super class

From the constructor of the subclass if constructor of the immediate super class has to be called to initialize the variables that are residing in super class super() can be used.
Note that in that case super() should be the first statement inside the subclass' constructor. This will ensure that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.

Example code using super

public class Shape {
 private int length;
 private int breadth;
 Shape(){
  
 }
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 private int height;
 Cuboids(int length, int breadth, int height){
  // Calling super class constructor
  super(length, breadth);
  this.height = height;
 }
}

Here it can be noticed that the instance variables are private now and super() is used to initialize the variables residing in the super class thus avoiding duplication of code and ensuring proper encapsulation.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

That will happen because; If a constructor is explicitly defined for a class, then the Java compiler will not insert the default no-argument constructor into the class. You can see it by making a slight change in the above example.

In the above example, if I comment the default constructor and also comment the super statement then the code will look like -

public class Shape {
  private int length;
  private int breadth;
  /*Shape(){
   
  }*/
  Shape(int length, int breadth){
   this.length = length;
   this.breadth = breadth;
  }
}

class Cuboids extends Shape{
  private int height;
  Cuboids(int length, int breadth, int height){
   // Calling super class constructor
   /*super(length, breadth);*/
   this.height = height;
  }
}

This code will give compile-time error. "Implicit super constructor Shape() is undefined".

Accessing Superclass Members

If method in a child class overrides one of its superclass' methods, method of the super class can be invoked through the use of the keyword super. super can also be used to refer to a hidden field that is if there is a variable of the same name in the super class and the child class then super can be used to refer to the super class variable.

public class Car {
 int speed = 100;
 
}

class FastCar extends Car{
 int speed = 200;
 FastCar(int a , int b){
  super.speed = 100;
  speed = b;
 }
}

Here, in the constructor of the FastCar class super.speed isused to access the instance variable of the same name speed in the super class.

Points to note -

  • super keyword in java is a reference variable to refer to class' immediate parent class.
  • super can be used to invoke the constructor of the immediate parent class, that's help in avoiding duplication of code, also helps in preserving the encapsulation.
  • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
  • super can also be used to access super class members.
  • If a variable in child class is shadowing a super class variable, super can be used to access super class variable.

That's all for this topic super in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. final in Java
  2. this in Java
  3. static in Java
  4. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Constructor Chaining in Java

In case when we have a hierarchy of classes (in case of inheritance) it is important to know the order in which constructors for the classes are executed. That order is known as constructor chaining.

There is also concept of constructor overloading where, with in the same class, there are multiple constructors with different signatures.

How does Constructor Chaining work

If class A is superclass and there is Class B which is subclass of A. In that case if a new instance of class B is created what is the order in which constructors of Class A and Class B are executed?

Answer is; the order followed is from superclass to subclass.

Subclass can call a constructor in the superclass inside one of the subclass constructors explicitly using super(). In that case super() must be the first statement in a subclass constructor. If super() is not used then the default no-arg constructor of each superclass will be executed implicitly. Note that the order remains same (from superclass to subclass ) whether or not super() is used.

Let's see it with an example -

class A{
 A(){
  System.out.println("In class A's constructor");
 }
}

class B extends A{
 B(){
  System.out.println("In class B's constructor");
 }
}
class C extends B{
 C(){
  super();
  System.out.println("In class C's constructor");
 }
}
public class ConstrChaining {

 /**
  * @param args
  */
 public static void main(String[] args) {
  C c = new C();

 }

}

It can be noticed here that we have a multilevel inheritance where super class is A which is extended by B and B is extended by C. When the instance of C is created it will trigger the chain of constructor invocations starting from the constructor of class A, then class B and at the last constructor of class C.
It can be seen from the output of the program

In class A's constructor
In class B's constructor
In class C's constructor

It can be seen from the program that I have explicitly called the constructor of B from the constructor of class C using super() where as in the constructor of class B there is no super still the constructor of class A is called because default no-arg constructor of super class will be executed implicitly in that case.

Points to note

  1. Constructor chaining refers to the order in which constructors will be called in case there is hierarchy of classes.
  2. Constructor of the superclass can be called from Subclass' constructor explicitly using super().
  3. If super() is used in a constructor then it has to be the first statement in the constructor.
  4. If super() is not used then the default no-arg constructor of each superclass will be executed implicitly.

That's all for this topic Constructor Chaining in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Constructor in Java
  2. Constructor overloading in Java
  3. Inheritance in Java
  4. super in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Method Overloading in Java

When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number, the methods are said to be overloaded. This process of overloaded methods is known as method overloading.

Method overloading is one of the ways through which java supports polymorphism.

When an overloaded method is called, which method is to be called is determined through -

  • Types of the parameters.
  • Number of the parameters.

Please note that return type of the methods may be different but that alone is not sufficient to determine the method that has to be called.

Let's see an example of method overloading -

public class OverloadingExample {
 // Method with 1 int param
 void overloadedMethod(int i){
  System.out.println("In overloadedMethod with one int parameter " + i);
 }
 
 // Method with 2 int params
 void overloadedMethod(int i, int j){
  System.out.println("In overloadedMethod with 2 int parameters " + i + " " + j);
 }
 
 // Method with 1 double param
 void overloadedMethod(double i){
  System.out.println("In overloadedMethod with 1 double parameter " + i);
 }
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5);
  obj.overloadedMethod(5.7);
  obj.overloadedMethod(5, 10);
 }
}

Here we have 3 methods with the same name but parameters are different either in number or type. One method has 1 int param, another method has 2 int params and yet another has 1 double param.

Output of the program

In overloadedMethod with one int parameter 5
In overloadedMethod with 1 double parameter 5.7
In overloadedMethod with 2 int parameters 5 10

Method overloading and automatic type conversion

In java automatic type promotion may happen and it does have a role in how overloaded methods are called, let's see it with an example to have clarity.

public class OverloadingExample {
 // overloaded Method with 1 int param
 void overloadedMethod(int i){
  System.out.println("In overloadedMethod with one int parameter " + i);
 }
 
 // overloaded Method with 2 double params
 void overloadedMethod(double i, double j){
  System.out.println("In overloadedMethod with 2 double parameters " + i + " " + j);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5);
  obj.overloadedMethod(5.7, 103.78);
  obj.overloadedMethod(5, 10);
 }
}

Here notice the third call to the method
obj.overloadedMethod(5, 10);

It has 2 int params, but there is no overloaded method with 2 int params, in this case automatic type conversion happens and java promotes these 2 int parameters to double and calls overloadedMethod(double i, double j) instead.

Overloaded method in case of Inheritance

In the case of parent-child relationship i.e. inheritance if two classes have the method with same name and signature then it is considered as method overriding, otherwise it is method overloading.

class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overloaded Method with String param
 public void dispayData(String showMsg){
  System.out.println(showMsg + "Value of j " + j);
 } 
}

class OverloadDemo{
 public static void main(String args[]){ 
  Child childObj = new Child(5, 10);
  // This call will invoke the child class method
  childObj.dispayData("in Child class displayData ");
  // This call will invoke the parent class method
  childObj.dispayData();
 }
}

Output of the program would be

in Child class displayData Value of j 10
Value of i 5

Benefit of Method Overloading

If we don't have method overloading then the methods which have same functionality but parameters type or number differs have to have different names, thus reducing readability of the program.

As example - If we have a method to add two numbers but types may differ then there will be different methods for different types like addInt(int a, int b), addLong(long a, long b) and so on with out overloaded methods.

With method overloading we can have the same name for the overloaded methods thus increasing the readability of the program.

That's all for this topic Method Overloading in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Method Overriding in Java
  2. Polymorphism in Java
  3. Inheritance in Java
  4. Difference between Encapsulation and Abstraction in Java
  5. Java OOP interview questions

You may also like -

>>>Go to Java Basics page

Method Overriding in Java

In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.

Example of Method overriding

class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  child.dispayData();  
 }

}

Output of the program

Value of j 7

It can be noticed here that when displayData() is invoked on an object of class Child, the overridden displayData() method of the child class is used.

Please note that In the case of parent-child relationship if both classes have the method with same name and signature then only it is considered as method overriding, otherwise it is method overloading only.

Benefit of method overriding

Method overriding allows java to support run-time polymorphism which in turn helps in writing more robust code and code reuse.

Method overriding helps in hierarchical ordering where we can move from general to specific.

If we use the same example to demonstrate run time polymorphism here.
class Parent {
 private int i;
 // Constructor
 Parent(int i){
  this.i = i;
 }
 // Method with no param
 public void dispayData(){
  System.out.println("Value of i " + i);
 } 
}

class Child extends Parent{
 private int j;
 // Constructor
 Child(int i, int j){
  // Calling parent class constructor
  super(i);
  this.j = j;
 }
 // Overridden Method
 public void dispayData(){
  System.out.println("Value of j " + j);
 } 
}

public class OverrideDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child child = new Child(5, 7);
  Parent parent = new Parent(8);
  // calling parent displayData method
  parent.dispayData();
  // parent holding the reference of child
  parent = child;
  // child class displayData method will be called
  parent.dispayData();  
 }

}

Output of the program

Value of i 8
Value of j 7

It can be noticed here that initially parent object calls displayData() method of parent class, later at run time the reference is changed and the parent is assigned the reference of child class. Now, when the displayData() method is called on the parent object, it calls the method of the class Child.

Points to note -

  • If method in the sub-class has the same name and signature as the parent class method then only it is called method overriding otherwise it is method overloading.
  • Method overriding allows java to support run-time polymorphism.
  • Method overriding helps in hierarchical ordering where we can move from general to specific. In super class a method can have a general implementation where as the sub classes provide the more specific implementation by overriding the parent class method.
  • If a method is declared as final in parent class then it can not be overridden by sub classes.
  • If a method is declared as abstract in the parent class then the sub class has to provide implementation for those inherited abstract methods

That's all for this topic Method Overriding in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Method Overloading in Java
  2. Inheritance in Java
  3. Abstraction in Java
  4. Exception handling and method overriding
  5. Java OOP interview questions

You may also like -

>>>Go to Java Basics page