Thursday, September 9, 2021

Why Class Name and File Name Should be Same in Java

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

  • File name and class name should be same in Java.
  • Main method signature- The main method signature must be public static void main(String[] args)

Refer Why main Method static in Java to understand the requirement why main method should be static.

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

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

File name and class name same in Java - Public class

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

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

File name and class name same in Java - Without public class

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 giving 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 in Java (provided there is no public class in the file) but at the run time it has to be same.

Why these restrictions

Now let’s try to see why this restriction to have file name same as class name for public class in Java? One scenario which I can think of where it makes sense is when you have a Java file with one public class and other classes too. You must be knowing that you can have a file in Java with at most one public class and other classes with default access (package-private).

Let’s see it with an example, suppose I have a java file as follows–

public class Test{
 public static void main(String[] args) {
  System.out.println("in test class");
  //Test1 t = new Test1();
 }
}

class Test1{
 public void display(){
  System.out.println("in Test1 class");
 }
}

class Test2{
 public void display(){
  System.out.println("in Test2 class");
 }
}

Here we have one public class Test and two other classes Test1 and Test2 having default access. Now, let’s say we don’t have the restriction to save this file as Test.java (which is the name of the public class). So, you saved it as ABC.java. Now at the time of compilation (javac ABC.java) compiler has to scan the whole file structure to find out the public class which is surely an overhead and easily avoidable by saving the Java file as Test.java.

Coming to another point that a class with default access can be saved with different name but the compiled .class file will have the same name as the class name.

Here again let’s try to understand it with an example–

Let’s say I have one class Test1 with Default access and I have saved it as XYZ.java

class Test1 {
 public void display(){
  System.out.println("in Test1 class");
 }
}

And another class where Test1 class object is created.

public class Test{
 public static void main(String[] args) {
  System.out.println("in Test class");
  Test1 t = new Test1();
  t.display();
 }
}

In this class when you are creating the object of class Test1 you are using the name of the class (Test1 t = new Test1();) not the saved filename (XYZ.java).

Test will look for a .class file Test1 when it has to load Test1 class. If .class file also won’t have the same name as the class then JVM must maintain some internal structure to have that mapping from saved file name to class name and refer that mapping every time to load the correct class. That again is an overhead so better to have the easy solution to generate at least the .class file with the same name as class name even in the case of class which is not public.

Well the gist is better to always have the same name for the java file as the class name. For academic purpose, you may fiddle with the file name Vs class name to see what is permitted and what is restricted.

Points to note-

  • If there is no public class then file name may be different from the class name in Java.
  • 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).

Recommendations for learning (Udemy Courses)

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

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!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java Pass by Value or Pass by Reference
  2. What are JVM, JRE and JDK in Java
  3. Object in Java
  4. Just In Time Compiler (JIT) in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Class in Java
  2. final Keyword in Java With Examples
  3. Automatic Numeric Type Promotion in Java
  4. How HashMap Works Internally in Java
  5. Difference between ArrayList and CopyOnWriteArrayList in Java
  6. Functional Interfaces in Java
  7. Fail-Fast Vs Fail-Safe Iterator in Java
  8. String in Java Tutorial

Wednesday, September 8, 2021

Constructor Chaining in Java

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

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

How does Constructor Chaining work in Java

If class A is superclass and there is a child class Class B. 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.

Monday, September 6, 2021

Find Largest And Smallest Number in a Given Array Java Program

This post is about writing a Java program to find the largest and the smallest number in a given array or it can also be rephrased as- Find the maximum and minimum number in a given array.

Condition here is that you should not be using any inbuilt Java classes (i.e. Arrays.sort) or any data structure.

Solution to find the largest and the smallest number in an array

Logic here is to have two variables for maximum and minimum numbers, initially assign the element at the first index of the array to both the variables.

Then iterate the array and compare each array element with the max number if max number is less than the array element then assign array element to the max number.

If max number is greater than the array element then check if minimum number is greater than the array element, if yes then assign array element to the minimum number.

Java code

public class FindMaxMin {
 public static void main(String[] args) {
  int numArr[] = {56, 36, 48, 49, 29, 458, 56, 4, 7};
  
  // start by assigning the first array element
  // to both the variables
  int maxNum = numArr[0];
  int minNum = numArr[0];
  // start with next index (i.e. i = 1)
  for(int i = 1; i < numArr.length; i++){
   if(maxNum < numArr[i]){
    maxNum = numArr[i];
   }else if(minNum > numArr[i]){
    minNum = numArr[i];
   }  
  }
  System.out.println("Largest number -  " 
     + maxNum + " Smallest number - " + minNum);
 }
}

Output

Largest number -  458 Smallest number - 4

That's all for this topic Find Largest And Smallest Number in a Given Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find Largest and Second Largest Number in Given Array Java Program
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Find Duplicate Elements in an Array Java Program
  4. How to Remove Elements From an Array Java Program
  5. Matrix Multiplication Java Program

You may also like-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find All Permutations of a Given String Java Program
  3. How to Convert Date to String in Java
  4. How to Read File From The Last Line in Java
  5. Creating Tar File And GZipping Multiple Files in Java
  6. How to Remove Elements From an ArrayList in Java
  7. Executor And ExecutorService in Java With Examples
  8. Java Reflection API Tutorial

Sunday, September 5, 2021

throw Statement in Java Exception Handling

It is possible for a Java program to throw an exception explicitly, that is done using the throw statement in Java.

The flow of execution, with in a method where throw is used, stops immediately after the throw statement; statements after the throw statement are not executed.

General form of throw in Java

General form of throw statement is-

throw throwableObject;
Here, throwableObject should be an object of type Throwable or any subclass of it.

We can get this throwableObject in 2 ways-

  • By using the Exception parameter of catch block.
  • Create a new one using the new operator.

Java example program using throw keyword

public class ThrowDemo {

 public static void main(String[] args) {
  ThrowDemo throwDemo = new ThrowDemo();
  try{
    throwDemo.displayValue();
  }catch(NullPointerException nExp){
     System.out.println("Exception caught in catch block of main");
     nExp.printStackTrace();;
  }
 }
 
 public void displayValue(){
  try{
    throw new NullPointerException();   
  }catch(NullPointerException nExp){
     System.out.println("Exception caught in catch block of displayValue");
     throw nExp;
  }
 }
}

Note that in this program throw keyword is used at two places. First time, in the try block of displayValue() method, it uses the new operator to create an instance of type throwable. Second time it uses the parameter of the catch block.

throw statement helps in preserving loose coupling

One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer.

As Example SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

catch(SQLException ex){
    throw new RuntimeException("DB error", ex);
}

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


Related Topics

  1. Difference Between throw And throws in Java
  2. Exception Propagation in Java Exception Handling
  3. Try-With-Resources in Java With Examples
  4. Creating Custom Exception Class in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How HashMap Works Internally in Java
  3. finalize() Method in Java
  4. Java Pass by Value or Pass by Reference
  5. Why Class Name And File Name Should be Same in Java
  6. Java CyclicBarrier With Examples
  7. Lambda Expressions in Java 8
  8. Count Number of Times Each Character Appears in a String Java Program

Saturday, September 4, 2021

BeanFactoryAware Interface in Spring Framework

If a class implements org.springframework.beans.factory.BeanFactoryAware interface, then the class bean is provided with a reference to their owning BeanFactory. BeanFactoryAware interface has a single method setBeanFactory(BeanFactory beanFactory).

BeanFactoryAware interface in Spring

public interface BeanFactoryAware extends Aware {
  void setBeanFactory(BeanFactory beanFactory) throws BeansException
}

As you see there is one callback method setBeanFactory that supplies the owning factory to a bean instance.

Bean implementing BeanFactoryAware interface can look up collaborating beans via the factory (Dependency Lookup). However, in general you should not use it, because it couples the code to Spring and does not follow the Inversion of Control style, where most beans will choose to receive references to collaborating beans via corresponding bean properties or constructor arguments i.e. Dependency Injection.

Spring BeanFactoryAware interface example

As already stated this interface should not be used but one scenario where it can help is having many beans of the same type and deciding at the run time which specific bean to use.

For example– Suppose you have IPayment interface and two implementing classes CardPayment and CashPayment. Based on the user’s choice appropriate bean should be called to execute payments. In this scenario you can use BeanFactoryAware interface to do a dependency lookup and load the required bean.

Let’s see Java code for all the classes.

IPayment interface

public interface IPayment{
 void executePayment();
}

CardPayment.java

public class CardPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Card Payment "); 
 }
}

CashPayment.java

public class CashPayment implements IPayment{
 
 public void executePayment() {
  System.out.println("Perform Cash Payment "); 
 }
}

IPayService interface

public interface IPayService{
 void performPayment(String paymentType);
}

Class implementing BeanFactoryAware interface

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class PayServiceImpl implements IPayService, BeanFactoryAware{
 
 private BeanFactory beanFactory;
 private IPayment payment;
 //private int amount;
 
 public void performPayment(String paymentType) {
  System.out.println("performPayment Method called");
  payment = (IPayment)beanFactory.getBean(paymentType);
  payment.executePayment();
 }
 
 @Override
 public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  this.beanFactory = beanFactory;
 }
}

In the class you can see setBeanFactory() method is implemented, also notice the performPayment() method where the beanFactory is used to load the required bean based on the paymentType parameter.

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:context="http://www.springframework.org/schema/context"
    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="cash" class="org.netjs.exp.Spring_Example.CashPayment" />
    <bean id="card" class="org.netjs.exp.Spring_Example.CardPayment" />
   
    <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl">
    </bean>
  
</beans>

Here you can see that there is no bean injected as dependency in the bean definition of payServiceBean. As you are going to get the bean by dependency lookup in performPayment() method.

You can use the following class to run and test the code.

public class App {
  public static void main( String[] args ){
    AbstractApplicationContext context = new ClassPathXmlApplicationContext
       ("appcontext.xml");

    IPayService payBean = (IPayService)context.getBean("payServiceBean");
   
    payBean.performPayment("cash");
   
    payBean.performPayment("card");

    context.registerShutdownHook(); 
  }  
}

Output

performPayment Method called
Perform Cash Payment 
performPayment Method called
Perform Card Payment 

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

>>>Return to Spring Tutorial Page


Related Topics

  1. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  2. Spring Bean Life Cycle
  3. @Required Annotation in Spring Framework
  4. registerShutdownHook() Method in Spring Framework
  5. Autowiring in Spring Using @Autowired and @Inject Annotations

You may also like-

  1. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  2. How to Read Properties File in Spring Framework
  3. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  4. Java Reflection API Tutorial
  5. Java Stream API Examples
  6. How LinkedList Class Works Internally in Java
  7. Java Lambda Expressions Interview Questions And Answers
  8. Constructor Chaining in Java

Friday, September 3, 2021

BeanFactoryPostProcessor in Spring Framework

BeanFactoryPostProcessor interface in Spring resides in org.springframework.beans.factory.config package. BeanFactoryPostProcessor implementation is used to read the configuration metadata and potentially change it before beans are instantiated by IOC container.

You can configure multiple BeanFactoryPostProcessors, you can also control the order in which these BeanFactoryPostProcessors execute by setting the order property. You can set the order property only if the BeanFactoryPostProcessor implements the Ordered interface.

BeanFactoryPostProcessor interface in Spring

BeanFactoryPostProcessor interface is a functional interface meaning it has a single abstract method, that method is postProcessBeanFactory() which you need to implement in order to custom modify the bean definitions. Note that when this method is called at that time all bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for overriding or adding properties even to eager-initializing beans.

@FunctionalInterface
public interface BeanFactoryPostProcessor {
  void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 
    throws BeansException;
}

Usage of BeanFactoryPostProcessor in Spring

The implementations of BeanFactoryPostProcessor interface are used by Spring framework itself. When you read from property files in Spring and configure the <context:property-placeholder> element that registers PropertySourcesPlaceholderConfigurer which implements BeanFactoryPostProcessor interface and set the properties there in the bean.

Spring BeanFactoryPostProcessor example

Here let’s have a simple example of BeanFactoryPostProcessor in Spring.

The scenario is that you have set the properties in a property file for DB config but for a particular run you want to use the separate schema which is set up in such a way that all the otehr properties remain same except the url. Which means you want to override the url property of the DataSource and modify it so that you can connect to the new Schema.

Though a better option would be to create separate Spring profiles and switch among those profiles but you can access bean definition and modify the value of the property using the BeanFactoryPostProcessor.

db.properties file

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/netjs
db.username=root
db.password=admin
pool.initialSize=5

XML configuration for the datasource

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
  <property name="driverClassName" value = "${db.driverClassName}" />
  <property name="url" value = "${db.url}" />
  <property name="username" value = "${db.username}" />
  <property name="password" value = "${db.password}" />
  <property name="initialSize" value = "${pool.initialSize}" /
</bean>

BeanFactoryPostProcessor implementation class

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;

public class TestDBPostProcessor implements BeanFactoryPostProcessor, Ordered {

  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 
      throws BeansException {
    System.out.println("In postProcessBeanFactory");
    // Getting the dataSource bean
    BeanDefinition bd = beanFactory.getBeanDefinition("dataSource");
    if(bd.hasPropertyValues()){
      MutablePropertyValues pvs = bd.getPropertyValues();
      PropertyValue[] pvArray = pvs.getPropertyValues();
      for (PropertyValue pv : pvArray) {
        System.out.println("pv -- " + pv.getName());
        // changing value for url property
        if(pv.getName().equals("url")){
          pvs.add(pv.getName(), "jdbc:mysql://localhost:3306/TestSchema");
        }
      }
    } 
  }
  @Override
  public int getOrder() {
    // TODO Auto-generated method stub
    return 0;
  }
}

As you can see in the method postProcessBeanFactory() you can get the dataSource bean and modify the bean definition.

To register the BeanFactoryPostProcessor add the following line in your configuration.

<bean class="org.netjs.config.TestDBPostProcessor"  />

Here is the method where I want to use the new schema.

public List<Employee> findAllEmployees() {
  System.out.println("URL " + ((BasicDataSource)jdbcTemplate.getDataSource()).getUrl());
  return this.jdbcTemplate.query(SELECT_ALL_QUERY, (ResultSet rs) -> {
    List<Employee> list = new ArrayList<Employee>();  
    while(rs.next()){
      Employee emp = new Employee();
      emp.setEmpId(rs.getInt("id"));
      emp.setEmpName(rs.getString("name"));
      emp.setAge(rs.getInt("age"));
      list.add(emp);
    }
    return list;
  });
}
To run this example following code can be used.
public class App {
  public static void main(String[] args) {      
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAOImpl");  
    List<Employee> empList = dao.findAllEmployees();
    for(Employee emp : empList){
      System.out.println("Name - "+ emp.getEmpName() + " Age - " 
      + emp.getAge());
    }
    context.close();    
  }
}

Output

Relevant lines from the console. 

In postProcessBeanFactory
pv -- driverClassName
pv -- url
pv -- username
pv -- password
pv – initialSize

URL jdbc:mysql://localhost:3306/TestSchema

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

>>>Return to Spring Tutorial Page


Related Topics

  1. BeanPostProcessor in Spring Framework
  2. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  3. BeanFactoryAware Interface in Spring Framework
  4. Injecting Inner Bean in Spring
  5. Circular Dependency in Spring Framework

You may also like-

  1. Spring JdbcTemplate Insert, Update And Delete Example
  2. Spring JdbcTemplate With ResultSetExtractor Example
  3. Spring Expression Language (SpEL) With Examples
  4. Spring depends-on Attribute
  5. How HashMap Internally Works in Java
  6. Covariant Return Type in Java
  7. Spliterator in Java
  8. Replica Placement Policy in Hadoop Framework

Thursday, September 2, 2021

Race Condition in Java Multi-Threading

Race condition in Java occurs in a multi-threaded environment when more than one thread try to access a shared resource (modify, write) at the same time. Since multiple threads try to race each other to finish executing a method thus the name race condition.

Two points to note about race condition are-

  • It is safe if multiple threads are trying to read a shared resource as long as they are not trying to change it.
  • Multiple threads executing inside a method is not a problem in itself, problem arises when these threads try to access the same resource. Examples of shared resources are class variables, DB record in a table, writing in a file.

Example of race condition in Java

Let’s see one example of race condition in Java multi-threading, where we have a shared instance variable. Since there are three threads sharing the same object of the class so the field in the object is shared among the threads.