Tuesday, May 18, 2021

Java OOP Interview Questions And Answers

In this post some of the Java OOP interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is encapsulation?

    Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). In Java a class contains the member variables (instance variables) and the code in methods. In a properly encapsulated Java class method defines how member variables can be used.
    Read more about encapsulation here.


  2. What is abstraction?

    Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, Abstraction means abstracting/hiding the real working and we, as a user, knowing only how to use it.

    Real world example would be a vehicle which we drive with out caring or knowing what all is going underneath.

    Read more about abstraction here.


  3. Difference between abstraction and encapsulation?

    Abstraction is more about hiding the implementation details. In Java abstraction is achieved through abstract classes and interfaces.

    Encapsulation is about wrapping the implementation (code) and the data it manipulates (variables) with in a same class. A Java class, where all instance variables are private and only the methods with in the class can manipulate those variables, is an example of encapsulated class.
    Read more about difference between Encapsulation and Abstraction in Java here.


  4. What is Polymorphism?

    Polymorphism, a Greek word, where poly means many and morph means change, thus it refers to the ability of an object taking many forms. The concept of polymorphism is often expressed as "One interface, multiple methods".
    Where one general class may have the generic method and the derived classes (classes which extend the general class) may add their own specific method with implementation. At the time of execution "One interface" i.e. the general class will take "many forms" i.e. references of the derived classes.
    Read more about polymorphism here.


  5. What is inheritance?

    Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class. The class whose members are inherited is called the Super class (or base class), and the class that inherits those members is called the Sub class (or derived class).
    The relationship between the Super and inherited subclasses is known as IS-A relationship.
    Read more about inheritance here.


  6. What Is a Class?

    In object-oriented terms class provides a blue print for the individual objects created from that class. Once a class is defined it can be used to create objects of that type.
    Read more about class here.


  7. What Is an Object?

    In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class. 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.
    Read more about object here.


  8. What is method overloading?

    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.
    Read more about method overloading here.


  9. What is method overriding?

    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.
    Read more about method overriding here.


  10. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways -

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  11. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  12. What is an abstract class?

    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.

    Read more about abstract class here.

  13. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  14. What is an Assocation?

    An association is a structural relationship, in object oriented modelling, that specifies how objects are related to one another. This structural relationship can be shown in-

    • Class diagram associations
    • Use case diagram associations
    An association may exist between objects of different types or between the objects of the same class. An association which connects two classes is called a binary association. If it connects more than two classes (not a very common scenario) it is called n-ary association. There are two types of associations
    • Aggregation
    • Composition

    Read more about Association here.


  15. What is an Aggregation?

    Sometimes you do need to define a “whole/part” relationship between classes where one class (whole) consists of smaller classes (part). This kind of relationship is called aggregation. It is also known as a “has-a” relationship as object of the whole has objects of the part. For example Company has a Person.

    Aggregation doesn't represent a strong "whole/part" relationship and both the "whole" and "part" entities can survive without each other too.

    Read more about Aggregation here.


  16. What is a Composition?

    There is a variation of aggregation called composition which has strong ownership, thus the scope of the whole and part are related. In composition if there are two classes, class A (whole) and class B (part) then destruction of class A object will mean class B object will also cease to exist. Which also means class B object may be a part of class A object only.
    Read more about Composition here.


Related Topics

  1. Core Java Basics Interview Questions And Answers
  2. Java String Interview Questions And Answers
  3. Java Exception Handling Interview Questions And Answers
  4. Java Multithreading Interview Questions And Answers
  5. Java Collections Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Monday, May 17, 2021

How to Append to a File in Java

In the post writing file in Java we have already seen how to write to a file in Java but the code given there creates a new file every time and writes the lines in the file. But there are many cases when you actually want to append to an already existing file in Java.

In this post we’ll see how to append to a file in Java. Both FileOutputStream and FileWriter classes have a constructor with a boolean argument, which when passed as true, means appending to a file. FileOutputStream and FileWriter are classes provided by Java to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably.

It is always advisable to use BufferedOutputStream or BufferedWriter rather than directly using FileOutputStream and FileWriterbecause that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.


Java program to append to a file using BufferedOutputStream

In the Java code if the file is not existing already it will be created and lines will be written to it. If it already exists then lines will be appended to that file.

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileAppend {
 public static void main(String[] args) {
  // Change path for windows
  writeFile("/home/netjs/Documents/text.txt");
 }

 public static void writeFile(String fileName){
  FileOutputStream fos;
  BufferedOutputStream bos = null;
  try {
   fos = new FileOutputStream(fileName, true);
   bos = new BufferedOutputStream(fos);
   // For windows you may need /r/n for new line
   bos.write("Writing first line\n".getBytes());
   bos.write("Writing second line\n".getBytes());
  }
  catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   try {
    if(bos != null){
     bos.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

Java program to append to a file using BufferedWriter

BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing.

When appending, if the file does not exist already it will be created and lines will be written to it. If it already exists then lines will be appended to that file.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileAppendWrite {

 public static void main(String[] args) {
  //Change path for windows
  writeFile("/home/netjs/Documents/test.txt");
 }
 /**
  * 
  * @param fileName
  */
 public static void writeFile(String fileName){
  // Using Java 7 try-with-resources
  try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true))){
   bw.write("Writing first line");
   bw.newLine();
   bw.write("Writing second line");
   bw.newLine();
  }
  catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Java program to append to a file using Files class methods

In Java 7 Files class is added which provides write() method to write to a file. There is also a newBufferedWriter method with 2 arguments, added in Java 8 that can be used to write to a file. In both of these methods you can pass StandardOpenOption.APPEND as option argument when you want to append to a file in Java.

There are 2 overloaded versions of write method.

  • public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException– Write bytes to a file specified by the path. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
  • public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException- Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.

Appending to a file using Files.write() method

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileWrite8 {
 public static void main(String[] args) {
  String content = "This is the line to be added.\nThis is another line.";
  try {
   Files.write(Paths.get("G://test.txt"), content.getBytes(), StandardOpenOption.APPEND);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that String is converted to Byte array and also StandardOpenOption.APPEND is passed as options varargs parameter which means appending to a file.

There are 2 overloaded versions of newBufferedWriter method.

  • public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException- Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
  • public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException- Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.

Appending to a file using Files.newBufferedWriter method

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileWrite8 {
 public static void main(String[] args) {
  Path path = Paths.get("G://test.txt");
  try (BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) {
      writer.write("Hello World");
      writer.newLine();
      writer.write("Hello again");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that StandardOpenOption.APPEND is provided as options varargs which means appending to a file.

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


Related Topics

  1. Write to a File in Java
  2. Read or List All Files in a Folder in Java
  3. How to Read Properties File in Java
  4. Unzip File in Java
  5. How to Create PDF From XML Using Apache FOP

You may also like-

  1. Setting And Getting Thread Name And Thread ID in Java
  2. Comparing Enum to String in Java
  3. Connection Pooling Using Apache DBCP in Java
  4. Java Program to Find First Non-Repeated Character in a Given String
  5. Abstraction in Java
  6. super Keyword in Java With Examples
  7. Lock Striping in Java Concurrency
  8. Race Condition in Java Multi-Threading

Sunday, May 16, 2021

How to Sort HashSet in Java

There may be a situation when you want to sort a HashSet in Java. Since the very idea of HashSet is to store elements according to the calculated Hash so by design HashSet is unordered. Thus, in order to sort a HashSet you can either-

  • Convert HashSet to a list and then sort that List by using Collections.sort() method. One drawback of using this option to sort a HashSet is that you get the result as list.
  • Create a TreeSet by passing the HashSet, it will automatically be sorted. TreeSet is an implementation of SortedSet and stores its element in sorted order. This option gives the result as Set.

Let's see a Java program where a HashSet storing strings is sorted.

Java Program to sort a HashSet

public class SetSorting {

  public static void main(String[] args){
    Set<String> citySet = new HashSet<String>();
    citySet.add("Delhi");
    citySet.add("Mumbai");
    citySet.add("Bangalore");
    citySet.add("Chennai");
    citySet.add("Hyderabad");
    
    //Convert it to a list and sort
    List<String> cityList = new ArrayList<>(citySet);
    Collections.sort(cityList);
    System.out.println("Sorted List " + cityList);
    
    // Sorting HashSet by using treeset
    Set<String> sortedSet = new TreeSet<String>(citySet);
    System.out.println("Sorting set by converting it to TreeSet " + sortedSet);
    
    // By using Java 8 stream and sorting
    Set<String> ab = citySet.stream().collect(Collectors.toCollection(TreeSet::new));
    System.out.println("SOrted Set using Java 8 Stream " + ab);
  }
}

Output

Sorted List [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
Sorting set by converting it to TreeSet [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
SOrted Set using Java 8 Stream [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]

Here first way to sort HashSet is to convert HashSet into a List and then sort that list. If you are ok with having a sorted elements in a list then this way is just fine. But don't do the mistake of converting it back to HashSet as shown below because converting back to HashSet will again make it unordered.

citySet = new HashSet<String>(cityList);
System.out.println("" + citySet);

While sorting a HashSet using a TreeSet, if you want another ordering than the natural ordering then you'll have to provide a comparator with the treeset.

From Java 8 onwards sorting the HashSet using a TreeSet can be done using collect() operation in stream API. It is still creating a TreeSet using the given HashSet but method reference is used here to create a new TreeSet.

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


Related Topics

  1. How HashSet Works Internally in Java
  2. LinkedHashSet in Java With Examples
  3. How to Sort ArrayList of Custom Objects in Java
  4. Difference Between Comparable and Comparator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. CopyOnWriteArraySet in Java With Examples
  3. finalize method in Java
  4. Varargs (Variable-length Arguments) in Java
  5. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  6. Java ThreadLocal Class With Examples
  7. Deadlock in Java Multi-Threading
  8. Java Multithreading Interview Questions And Answers

Saturday, May 15, 2021

static Keyword in Java With Examples

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

The static keyword in Java can be used with-

Static Variable in Java

A variable declared as static in Java 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 using the class 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 keyword in Java 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.

static field 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.

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 is also associated with the class rather than objects of the class. Static method can be called directly using 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 in Java

  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 in Java

A static final variable that is not initialized at the time of declaration is known as static blank final variable in Java. 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.

static nested class

Top level class can't be declared as static but a nested class can be declared as static, such a nested class is known as static nested class in Java.

Points to note about static keyword in Java-

  • static keyword in Java 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 members of a class can be accessed even before object of a class is created.
  • 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 Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Import in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. Why main Method static in Java
  4. Interface Static Methods in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. super Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. Constructor Overloading in Java
  4. Exception Handling in Java Lambda Expression
  5. Difference Between throw And throws in Java
  6. final Vs finally Vs finalize in Java
  7. Java ReentrantReadWriteLock With Examples
  8. How HashMap Works Internally in Java

Friday, May 14, 2021

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 in Java.

Method overloading is one of the ways through which java supports polymorphism. In fact method overloading is an example of static polymorphism or compile time polymorphism.

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

  • Types of the parameters- For example test(int a, int b) and test(float a, int b). In these overloaded methods name is same but the types of the method parameters differ.
  • Number of the parameters- For example test(int a, int b) and test(int a, int b, int c). In these overloaded methods name is same but the number of parameters is different.

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.


Examples of method overloading in Java

1- Method overloading example with methods having different types of parameters. In the Java example there are two overloaded methods, one having two parameters and both are int where as other method has one int and one double parameter.

public class OverloadingExample {
 // overloaded Method
 void overloadedMethod(int i, int j){
  System.out.println("In overloadedMethod with both int parameters- " + i);
 }
 
 // overloaded Method
 void overloadedMethod(int i, double j){
  System.out.println("In overloadedMethod with int and double parameters " + i + " " + j);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5, 7);
  obj.overloadedMethod(5, 103.78);
 }
}

Output

In overloadedMethod with both int parameters- 5
In overloadedMethod with int and double parameters 5 103.78

2- Method overloading example with methods having different number of parameters. In the Java example there are two overloaded methods, one having a single int parameter where as other method has one int and one String parameter.

public class OverloadingExample {
 // overloaded Method
 void overloadedMethod(int i){
  System.out.println("In overloadedMethod with int parameter- " + i);
 }
 
 // overloaded Method
 void overloadedMethod(int i, String s){
  System.out.println("In overloadedMethod with int and string parameters- " + i + " " + s);
 }
 
 
 public static void main(String args[]){ 
  OverloadingExample obj = new OverloadingExample();
  obj.overloadedMethod(5);
  obj.overloadedMethod(5, "Test");
 }
}

Output

In overloadedMethod with int parameter- 5
In overloadedMethod with int and string parameters- 5 Test

Method overloading in Java 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 both classes have the method with same name and same number and type of parameters 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!

>>>Return to Java Basics Tutorial Page


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 And Answers

You may also like-

  1. Object Creation Using new Operator in Java
  2. final Keyword in Java With Examples
  3. Java Abstract Class and Abstract Method
  4. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  5. How HashMap Works Internally in Java
  6. final Vs finally Vs finalize in Java
  7. Lambda Expressions in Java 8
  8. Dependency Injection in Spring Framework

Thursday, May 13, 2021

Why main Method is static in Java

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

Here we'll talk about the main method and the necessity to mark main method as static in Java. 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 main method is static in Java 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). When you start execution of a Java program, JVM looks for the main method in the provided Java class as that is the entry point for the execution.

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.

Here note that any static method in Java is associated with the class not with any object of the class. Static method can be called without creating any object of the class.

What if main method is not declared as static

If Java main method 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 (Which is with in the main method) 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 in Java 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 in Java 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!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Keyword in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. static Reference to The Non-static Method or Field Error
  4. static Block in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Automatic Numeric Type Promotion in Java
  2. Java Pass by Value or Pass by Reference
  3. Method Overloading in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. this Keyword in Java With Examples
  6. How to Sort ArrayList in Java
  7. How HashMap Works Internally in Java
  8. Race Condition in Java Multi-Threading

Wednesday, May 12, 2021

If Given String Sub-Sequence of Another String in Java

I recently remembered one interview 6-7 years back where I was asked to write a Java program to find if given string is the subsequence of another string. I started writing the program but my approach was wrong as I was getting confused between subsequence and substring.

What I wrote was to ensure that given string is the substring of another string as my assumption was that the characters should come continuously. As example if I have to find "net" exists in "netjs", then it is true as all the characters n, e, t are coming continuously in netjs.

But that’s not what subsequence means so before writing the program to ensure that given string is the subsequence of another string first let’s have a proper definition of what subsequence means.

What is a subsequence

A subsequence is a sequence where all the characters of the subsequence are present in another sequence, are in order but may not be continuous. As example – If our subsequence is “net” and we have to find if that subsequence exists in the string “npeght” then it should return true as all the characters of the subsequence (n, e, t) are present in the given string and characters are in the same order. If we delete the extra elements in the second string (p, g, h) then we get the same string.

Approach for the Java program

We can have both iterative and recursive logic for the program to find if given string is the subsequence of another string. Approach remains same for both if we have to find that String-1 is subsequence of String-2 then we start from one end of the string, it can be leftmost or rightmost (In the program here I started from the leftmost character of the strings). If character of String-1 is found in String-2 then we increment the index by 1 for both strings, if character of String-1 is not found in String-2 then we increment the index by 1 only for String-2.

Java program to find if given string is the subsequence of another string

This code has both iterative and recursive solutions.

  • Method isStringSequenceFound(String str1, String str2, int i, int j)is for recursive solution.
  • Method isStringSequenceFound(String str1, String str2) is for iterative solution.
public class SubSequenceFinder {

  public static void main(String[] args) {
    // Iterative method call
    String str1 = "abc";
    String str2 = "asc";
    boolean flag = isStringSequenceFound(str1, str2);
    System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
    
    // Recursive method call
    str1 = "java";
    str2 = "javelina";
    flag = isStringSequenceFound(str1, str2, 0, 0);
    System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
    
    // Iterative method call
    str1 = "abc";
    str2 = "asbbdfc";
    flag = isStringSequenceFound(str1, str2);
    System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
  }
 
  // Recursive method to find sub-sequence
  static boolean isStringSequenceFound(String str1, String str2, int i, int j){
    // Exit condition - if i becomes equal to length 
    // of string-1 that means all the characters are found in the second string
    if(str1.length() == i){
      return true;
    }
    //if length of String-2 becomes equal to j that means string 2 is completely
    // traversed and all the characters of string-1 are not found
    if(str2.length() == j){
      System.out.println();
      return false;
    }
    //
    if(str1.charAt(i) == str2.charAt(j)){
      // increase both i and j by 1, if char is found
      return isStringSequenceFound(str1, str2, ++i, ++j);
    }else{
      return isStringSequenceFound(str1, str2, i, ++j);
    }
  }
 
  // iterative method to find sub-sequence
  static boolean isStringSequenceFound(String str1, String str2){
    int j = 0;
    for(int i = 0; i < str2.length(); i++){
      if(str1.charAt(j) == str2.charAt(i)){
        ++j;
      }
      // All the characters of String-1 are found in String-2
      if(j == str1.length()){
        return true;
      }
    }
    // If it comes here that means all the characters of String-1
    // are not found in string-2
    return false;
  }
}

Output

abc is subsequence of asc - false
java is subsequence of javelina - true
abc is subsequence of asbbdfc - true

That's all for this topic If Given String Sub-Sequence of Another String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Removing Spaces Between Words in a String Java Program
  2. Find Duplicate Characters in a String With Repetition Count Java Program
  3. Find All Permutations of a Given String Java Program
  4. How to Reverse a String in Java
  5. Java Lambda Expression Callable Example

You may also like-

  1. How to Convert String to Date in Java
  2. Read or List All Files in a Folder in Java
  3. Ternary Operator in Java With Examples
  4. Is String Thread Safe in Java
  5. Java Stream API Tutorial
  6. How ArrayList Works Internally in Java
  7. Java Object Cloning - clone() Method
  8. Dependency Injection in Spring Framework

Tuesday, May 11, 2021

this Keyword in Java With Examples

this keyword in java is a reference to the current object, meaning the object whose method or constructor is being called. It can be used inside any method or constructor to refer to the current object.

If the definition of this keyword in Java is sounding confusing, let's clear it with an example-

class ThisDemo{
 int age;
 String name;
 ThisDemo(int a, String b){
  age = a;
  name = b;
 }
 void displayData(){
  System.out.println("Age - " + age + " Name- " +name);
  System.out.println("reference of this " + this);
 }
 
}
public class ThisExample {
 public static void main(String[] args) {
  ThisDemo thisDemo = new ThisDemo(10, "Ram");
  thisDemo.displayData();
  System.out.println("reference of ThisDemo " + thisDemo);
 }
}
 

In the given example, it can be seen that in method displayData() this is printed and in the main method thisDemo object is printed. Reference of object thisDemo and reference of this in method dispalyData() would be same as this is reference to the object on which the method is invoked.

Output

 Age - 10 Name- Ram
reference of this org.netjs.examples.ThisDemo@19e0bfd
reference of ThisDemo org.netjs.examples.ThisDemo@19e0bfd

It can be seen in the output that the same reference is printed for object thisDemo and this.

Note that this can't be explicitly assigned a reference to an object of a class it will result in compilation error.

MyClass myObj = new MyClass();
// This line will give error, as assigning reference of an
// object to this is not permitted
this = myObj;

Usage of this keyword in Java

this in Java used in case of instance variable hiding

Before going into how this keyword can be used in case of instance variable hiding first let's see what actually instance variable hiding is. In Java we can't have two local variables with the same name with in the same scope. So it will be compiler error if we try some thing like-

class A {
 int a;
 double b;
 double b;// Compiler error

 public void displayData(){
  System.out.println("Values - a = " + a + " b= " + b);
 }
}

Here we are trying to have two variables with the same name b with in the same scope (scope of the class) which results in compilation error.

But in different scope it is perfectly legal to have variables with the same name, so we can have the variables with the same name in the method as well as in the class as instance variable. Thus it is perfectly legal to have some thing like

class InstanceHiding {
 int a = 50;
 double b = 60;

 public void displayData(){
  int a = 10;
  double b = 20;
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding();
  instanceHiding.displayData();
 }
} 
 

No error here because the variables are with in the different scope. But the point to note here is that local variable hides the instance variable with in the scope of the local variable. As can be seen from the output of the program.

Values a = 10 b = 20.0

With in the method, method variables get priority over the instance variables and hide them. If we comment the variables with in the method then the output would have been -

Values a = 50 b = 60.0

this can be useful in such cases to avoid name collisions, since we know that this in Java refers to the object on which the method is called so this can be used to access the instance variables.
Conventionally people prefer to have same names for variables in the case of constructors to have clarity, use of this helps there to initialize fields.

An Example
class InstanceHiding {
 int a;
 double b;
 InstanceHiding(int a, double b){
  this.a = a;
  this.b = b;
 }
 public void displayData(){  
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding(10, 20);
  instanceHiding.displayData();
 }
}

Here we are referring the instance variables using the this keyword like this.a and initializing them in the constructor.

this keyword used in case of overloaded constructors

In Java this keyword can be used to invoke overloaded constructors in a class. There are 2 restrictions that should be kept in mind while doing that.

  • this() must be the first statement with in the constructor.
  • instance variable of the constructor's class can not be used in a call to this().
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 constructor 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.

Note that while using with in a constructor either this() or super() can be used not both as both have the restriction to be the first statement with in the constructor.

Passing 'this' as an argument in the constructor call/method call

Since this in Java refers to the current object so this can be used as an argument where ever current object is needed.

public class A {
 void anotherMethod(A obj){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  anotherMethod(this);  
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

this keyword used to call methods of a class

Since this in Java refers to the current object so this can also be used to call methods of the class.

public class A {
 void anotherMethod(){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  this.anotherMethod();
  this.toString();
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. super Keyword in Java With Examples
  3. Constructor in Java
  4. static Keyword in Java With Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. strictfp in Java
  2. Constructor Chaining in Java
  3. Varargs (Variable-length Arguments) in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. How ArrayList Works Internally in Java
  6. Interface Default Methods in Java
  7. Method Reference in Java
  8. Check if Given String or Number is a Palindrome Java Program

Monday, May 10, 2021

Object in Java

In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class. An object stores its state in fields and exposes its behavior through methods.

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.

Creating object in Java

Creation of an object for a class in Java 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.

Java object creation 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 done 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 (instantiated), which means rectangle objects holds reference to the created object of Rectangle class.

rectangle = new Rectangle();
Declaring an object in Java
Declaring and Instantiating 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. This step is the initialization step.

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

Rectangle rectangle = new Rectangle();

Benefits of using class and object in Java object oriented programming

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!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Object Creation Using new Operator in Java
  2. Object class in Java
  3. this Keyword in Java With Examples
  4. finalize() Method in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Java Abstract Class and Abstract Method
  2. Java Pass by Value or Pass by Reference
  3. Automatic numeric type promotion in Java
  4. final Keyword in Java With Examples
  5. super Keyword in Java With Examples
  6. Deadlock in Java multi-threading
  7. ThreadLocal class in Java
  8. Method Reference in Java

Saturday, May 8, 2021

Class in Java

In object-oriented terms class provides a blue print for the individual objects created from that class. Once a class is defined it can be used to create objects of that type, thus it can be said that class defines new data type.

In this tutorial we'll see how to create a class in Java, how to add a constructor and methods to a class and what all access modifiers can be used with a Java class.

Form of a class in Java

A class has certain properties like data (variables) and the code that uses that data in the code logic. Since class provides a template for an object, thus many individual objects of this class type can be created which will have the basic class properties.

Java class structure

class classname {
  type instance_variable1;
  type instance_variable2;
  …..
  ......

  type methodname1(arguments){
    method code here.....
  }

  type methodname2(arguments){
    method code here.....
  }
}

The variables defined with in a class are called instance variables. The code that operates on these variables is defined with in methods. Together these variables and methods provide the structure of the class.

Java class example

Here is a simple example of defining a class in Java. This step by step example shows how to write a method in a class, how to define a constructor in the class and how to use it to initialize fields, how to create an object of the class.

class Rectangle{
  double length;
  double width;
}

class RectangleDemo {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle();
    rectangle.length = 10;
    rectangle.width = 5;
    double area = rectangle.length * rectangle.width;
    System.out.println("Area of the rectangle is " + area);    
  }
}

In this example I have created a class Rectangle which has two instance variables length and width. Then using this template Rectangle (class) new object has been created.

Rectangle rectangle = new Rectangle();

Then values are assigned to the object's instance variables and the area is computed.

We can provide a method in the Rectangle class itself to compute the area, and make the instance variables private to have better encapsulation, the new class will look like this-

class Rectangle{
  private double length;
  private double width;
  // area method to compute area 
  public void area(double ln, double wd){
    length = ln;
    width = wd;
    double area = length * width;
    System.out.println("Area of the rectangle is " + area);
  }
}

class RectangleDemo {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle();
    //rectangle.length = 10;
    //rectangle.width = 5;
    //double area = rectangle.length * rectangle.width;
    //System.out.println("Area of the rectangle is " + area); 
    rectangle.area(5, 10);
  }
}

But you must be wondering why this double work of passing the variables and then in the method assigning the values to the instance variables. Yes you can use constructor to do this.

So, we can make the Java class even better by introducing constructor for the class, the initialization of the instance variables will be done through the constructor in that case. With these changes the class will look like this -

class Rectangle{
 double length;
 double width;
 //Constructor
 public Rectangle(double length, double width) {
  this.length = length;
  this.width = width;
 }
 // Method to compute area
 public void area(){
  double area = length * width;
  System.out.println("Area of the rectangle is " + area);
 }
}

 class RectangleDemo { 
 public static void main(String[] args) {
  Rectangle rectangle = new Rectangle(10, 5);  
  rectangle.area();
 }
}

Modifiers for a class in Java

Modifiers for a class may be classified into two categories-

  • Access modifiers
  • Non-Access modifiers

Access modifiers for a Java class

Classes in Java can only have the default (package) and public access modifiers assigned to them.

  • Public- class may be declared with the modifier public, in which case that class is visible to all classes everywhere.
  • Default- If a class in Java has no modifier (the default, also known as package-private), it is visible only within its own package.

Note that an inner class can be declared as private but top level class can take only the above mentioned 2 modifiers.

Non Access modifiers for a Java class

Non access modifiers for the class in Java are-

Points to note-

  • class provides a blue print for the individual objects created from that class.
  • The variables defined with in a class in Java are called instance variables.
  • The code that operates on these variables is enclosed with in methods.
  • Together these variables and methods provide the structure of the class.
  • Access modifiers used with the class are default (package)and public
  • An inner class can be declared as private.
  • Non access modifiers for the class are final, abstract and strictfp

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

>>>Return to Java Basics Tutorial Page


Related topics

  1. Object in Java
  2. Package in Java
  3. Java Abstract Class and Abstract Method
  4. TypeWrapper Classes in Java
  5. Java OOP Interview Questions And Answers

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. this Keyword in Java With Examples
  3. How to Read Input From Console in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. equals() And hashCode() Methods in Java
  6. Creating a Thread in Java
  7. Java Exception Handling Tutorial
  8. Java Object Cloning - clone() Method

Friday, May 7, 2021

Using c-namespace in Spring

While using Spring XML configuration for wiring beans you would have used <constructor-arg> element several times for providing, property values and/or providing reference for beans, as a constructor injection. If you are looking for any shorter alternative, just as p-namesapce is used in place of nested <property> element, you can use c-namespace in Spring.

The c-namespace in Spring enables you to use the bean element’s attributes for configuring the constructor arguments rather than nested constructor-arg elements.

As example–

If you have an XML configuration for bean employee which has a constructor that refers to the bean of type address with constructor-arg you will write it like this -

<bean id="employee" class="org.netjs.model.Employee">
    <constructor-arg ref="address"/>
</bean>

You can use c-namespace to shorten it like this -

<bean id="employee" class="org.netjs.model.Employee" c:officeAddress-ref="address">
    <!-- <constructor-arg ref="address"/> -->
</bean>

You can see here that instead of using nested <constructor-arg> element you can use bean element’s attribute itself.

In this way of using c-namespace for injection of bean reference c:officeAddress-ref="address", c: denotes the use of c-namespace, officeAddress is the constructor argument name with in the employee class where value is injected, -ref indicates injection of bean reference.

Using c-namespace with literals

Same way c-namespace can be used for injecting literal values.

As example

If you have an XML configuration for bean employee which has a constructor argument empName then you can provide a literal value to empName property like this –

<bean id="employee" class="org.netjs.model.Employee">
    <constructor-arg value="Ram"/>
</bean>

Using c-namespace you can shorten it like this –

<bean id="employee" class="org.netjs.model.Employee" c:empName="Ram">
    <!-- <constructor-arg value="Ram"/> -->
</bean>

Spring c-namespace example

As we have already seen there are two classes Address and Employee and Address class bean is referred in Employee.

Employee class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 private Address officeAddress;
 
 public Employee(int empId, String empName, int age, Address officeAddress){
  this.empId = empId;
  this.empName = empName;
  this.age = age;
  this.officeAddress = officeAddress;
 }
 
 public Address getOfficeAddress() {
  return officeAddress;
 }
 
 public int getEmpId() {
  return empId;
 }
 
 public String getEmpName() {
  return empName;
 }
 
 public int getAge() {
  return age;
 }
}

Here it can be seen that Employee class has constructor that has some literal values as argument and one argument of type Address.

Address Class

public class Address {
 private String number; 
 private String street; 
 private String city; 
 private String state; 
 private String pinCode; 
 public String getNumber() {
  return number;
 }
 public void setNumber(String number) {
  this.number = number;
 }
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getPinCode() {
  return pinCode;
 }
 
 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }
 
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:c="http://www.springframework.org/schema/c"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">
 
  
  <bean id="address" class="org.netjs.model.Address" p:number="101" p:street="M I Road" 
          p:city="Jaipur" p:state="Rajasthan" p:pinCode="302001"> 
  </bean>
  
  <bean id="employee" class="org.netjs.model.Employee" c:empId="1001" c:age="25" 
   c:empName="Ram" c:officeAddress-ref="address" />
    
</beans>
Here notice the inclusion of xmlns:c="http://www.springframework.org/schema/c” and xmlns:p="http://www.springframework.org/schema/p” in XML configuration for c-namespace and p-namespace respectively.

In bean definition for address p-namespace is used for providing values. In bean definition for Employee c-namespace is used to provide values for constructor arguments.

Test Class

You can run this code using the following code -

import org.netjs.model.Address;
import org.netjs.model.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

  public static void main(String[] args) {        
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    Employee emp = (Employee)context.getBean("employee");  
    Address addr = emp.getOfficeAddress();
    System.out.println("name " + emp.getEmpName());
    System.out.println("City " + addr.getCity());
    System.out.println("PinCode " + addr.getPinCode());
    context.close();    
  }
}

Output

name Ram
City Jaipur
PinCode 302001 

That's all for this topic Using c-namespace in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Using p-namespace For Shorter XML in Spring
  2. Bean Definition Inheritance in Spring
  3. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  4. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  5. @Conditional Annotation in Spring

You may also like-

  1. Spring Profiles With Examples
  2. Spring JdbcTemplate Select Query Example
  3. How to Read Properties File in Spring Framework
  4. Functional interface annotation in Java 8
  5. Java Stream API Examples
  6. Convert String to Byte Array Java Program
  7. Interface Default Methods in Java
  8. super Keyword in Java With Examples