Menu

Showing posts with label Java Learning. Show all posts
Showing posts with label Java Learning. Show all posts

How to check installed Java version in your machine?

If you see this error while executing any program or running and debugging maven build then follow the following easy steps, to resolve this issue from eclipse.


How to check installed Java version in your machine?

There are two ways to check installed java version in your machine.
1. Using command prompt
  • Go to start and search for cmd, open command prompt.
  • No need to change the default directory from command prompt, just  copy and paste command "java -version".
  • Hit enter key to run the command.

Below is the screen shot for more clarification.


how to check java version
Java version check

2. Another simple way to check installed java version in your machine by using java version link.


Verify version of java installed in your machine
Verify Java and find out-dated version



  • Click on the Agree and continue button.
  • A popup window will appear, which needs your approval to run java version check application. Simply click on the "Run" button on that popup.
  • Now you will see the Java detail page on your browser. as showing in the below screen shot.

Java version in your machine
Java version in your computer

Cannot make a static reference to the non-static method

Cannot make a static reference to the non-static method display(String) from the type RunAndTest.
We cannot access or call a non static method or variable from a static method or main method(which is also a static method) of a class. Since non-static method and variables belongs to the instance of the class and we call them instance variable and method, but static method and variable are directly belongs to class which we called member variable and method.
We can access a non-static variable and method in static method only using the instance of the class. But if you want to access any non-static variable and method in non-static method of the same class then we can access them without instance of the class.


Why we can not access? 

As soon as our program loaded into memory at the same time all static variable, method and block get loaded in the memory as well, and JVM will maintain only single copy of those static thing through all over the class. And all non-static components will get loaded into the memory when we create instance of that class that why we called them instance variable/method, and when you create another instance of that class then a new and separate memory will be get allocated for all those variables and methods for that instance.

In case if you will write a code to access a non-static member in static method without instance of that class then compiler will through the error "Cannot make a static reference to the non-static method".

Below is a code sample which you could just copy and paste in your IDE and understand the concept of this static and non-static.

Compilation fail while accessing a non-static method in static method.


package coreJava;
public class RunAndTest {
public static void main(String[] args) {
display("string"); //This line of code will through compile time error "cannot make a static reference to the non-static method display(String) from the type RunAndTest"
}
void display(RunAndTest rt){
System.out.println("Test");
display("sdj");
}
void display(String string){
System.out.println("String method");
}
}

Access a non-static method in static method, with the help of object of the class.


package coreJava;public class RunAndTest { public static void main(String[] args) { RunAndTest rt=new RunAndTest(); rt.display("string"); 
} void display(RunAndTest rt){ System.out.println("Test"); display("sdj"); } void display(String string){ System.out.println("String method"); }} 

How to set property of a bean from external source file using Spring framework

Today in this tutorial we are going to discuss how to set property of a bean from external source file using Spring framework.

As we already know Spring is a very powerful framework to inject the dependency at get the value at run time in the form of beans. But what happen if we don't have value for those beans in our ApplicationContext.xml file and we need to fetch value from some external file or data source and assign those values to beans. We will see these all in a sample example program.

Files used in this example:


  1. Apple.java
  2. myApp.properties
  3. AppContextRashid.xml
  4. ClassHer.java


First we will create a java POJO calss "Apple.java" in this class we will create two String variables and their getters and setters. Also we will create a method whoareyou() with return type String.
Below is the code:
package rashidtest;
public class Apple  {
String name1, desc1="not yet set";
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
public String whoareyou() {
String result= name1 + desc1;
if(desc1 == null) return name1;
else if(name1 == null) return desc1;
else return result;
}
}

Second we will create a property file which contains the value for name1 and desc1 variables. to do so we will create a file "myApp.properties" in a xmlBeans package in our source directory which have some values. below is the example file.

def-desc=I am a fruit and my color is Red.
def-name=Apple.

Third we will create a xml bean file "AppContextRashid.xml" in which we will to include namespace "xmlns:context="http://www.springframework.org/schema/context" to read the data from external source.

To read the external property or value from file we will provide the location in property placeholder. e.g. <context:property-placeholder location="xmlBeans/myApp.properties"/> 

Then in Bean property tag we will assign values from file to POJO class variables. To get the value from properties file we will write "${name of the property}". 
e.g. <property name="desc1" value="${def-desc}"></property> 
In the above statement we are fetching value for property "def-desc" from .property file and assigning its value to "desc1" variable in Apple class.

<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:property-placeholder location="xmlBeans/myApp.properties"/> 
<bean id="apple" class="rashidtest.Apple">
<property name="desc1" value="${def-desc}"></property>
<property name="name1" value="${def-name}"></property>
</bean>
</beans>

Fourth and final we will create a implementer class which have main method, instance of ApplicationContext and inject the value from bean to class using setter injection. to achieve this we will create a java file "ClassHer.java". Below is the complete class.

package rashidtest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClassHer {
public static void main(String[] args) {
ApplicationContext appContext=new ClassPathXmlApplicationContext("rashidtest/AppContextRashid.xml");
Apple apple=appContext.getBean("apple", Apple.class);
System.out.println("Apple class have property: " +apple.whoareyou());
}
}

Date and Time classes in Java

Today in this tutorial we will look how to work with date and times in Java programming.

Date and time is very important for every application and managing that date and time in your specified format, specified time zone and readable format as you want to get fetch from java program.

We are going to use some methods of LocalDate, LocalTime and LocalDateTime classes.

now() : This method return the current system date and time. If you call this now() using the LocalDate then it will give you date only not time stamp. But the same now if you call using the object of LocalTime then that will return time stamp only not date.

minusMonths() :  This method will reduce number of months from your given date. e.g. if your date is 2017-06-06 and when you will use minusMonths(2) then your date will become 2017-04-06.

plusMonths() : This method will add number of more months in your given date. e.g. if your date is 2017-04-06 and when you will use plusMonths(2) then your date will become 2017-06-06.

getDayOfWeek(): This method will return name of the day on a given time.

isBefore(): this getBefore method will return true or false by comparing the two given dates. e.g birthDate.isBefore(date.now()); here this will compare your birthdate is before current date or not. in the same way you can use the isAfter() as well.

Below is the complete example (ready to use) which you can just copy and paste  in your eclipse and execute to see how different Date methods are working in Java.


package abctest;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static java.time.temporal.TemporalAdjusters.*; // this import we have used to use next()import static java.time.DayOfWeek.*;
public class DateEx {
//here we have created three objects of LocalDate class. LocalDate now, bDate, today;
public static void main(String[] args) {
DateEx dateex=new DateEx();
// here we have created object local date(ld) from LocalDateTime.
LocalDateTime ld=LocalDateTime.now();
System.out.println(ld);
String locaDate=ld.format(DateTimeFormatter.ISO_DATE);
System.out.println(locaDate);
dateex.setNow(LocalDate.now());
dateex.dateMethods();
}
public void dateMethods(){
System.out.println("Date Methods:");
System.out.println("Date: " +getNow());
 //below line is to fetch the local time from your system.
System.out.println("Time: " +LocalTime.now());
//minusMonths() is to minus the number of months from a given date.
bDate=getNow().minusMonths(12);
//isBefore() method is used to compare the earlier date from two given dates.
System.out.println("Birthaday: "+bDate +" Is dbirthday before current date? "+bDate.isBefore(now));
//To get the name of the for a date.
System.out.println("He born on day: " +bDate.getDayOfWeek());
//On what date next Monday will be from a given date.
System.out.println("Next Monday will be on " +getNow().with(next(MONDAY)));
//From which era your date belongs from either BCE or AD.
System.out.println("Era: "+bDate.getEra());
}
public LocalDate getNow() {
return now;
}
public void setNow(LocalDate now) {
this.now = now;
}
}

New features in java language in Java-9 or JDK-9 release

The major change in Java SE 9 is its module system. Other than this there are several small language changes as well in Java SE 9.

As we already know on 21st Sept 2017 JDK 9 or Java 9 has been release in market. Today we will see what all new programming features introduced in Java SE-9.


  • You can now declare a private method in a Interface class. This allows non-abstract methods of an interface to share code between them. 
For Example: 
public interface AccountOp{
public static final String NAME="wellDo";

//default method of interface
public default void foot(){}
//private method within interface
private void displayAge();
}


  • Underscore character no more legal for identifier name. Your source code will not compile if you use underscore character ["_"] in an identifier name[variables, methods, classes, packages and interfaces]. e.g. String ras_name; interface Local_Home; public void gender_Test(); are the illegal in Java 9/JDK 9.


  • Allow effectively final variables to be used as resources in the try-with-resources statement. If you already have a resource as a final or effectively final variable, you can use that variable in a try-with-resources statement without declaring a new variable. An "effectively final" variable is one whose value is never changed after it is initialized.
    For example, you declared these two resources:
              // A final resource

              final Resource resource1 = new Resource("resource1");
              // An effectively final resource
              Resource resource2 = new Resource("resource2");
              In Java SE 7 or 8, you would declare new variables, like this:
                        try (Resource r1 = resource1;

                             Resource r2 = resource2) {
                            ...
                        }
                        In Java SE 9, you don’t need to declare r1 and r2:
                          // New and improved try-with-resources statement in Java SE 9

                                  try (resource1;
                                       resource2) {
                                      ...
                                  }


                          • @SafeVarargs annotation is allowed on private instance methods.

                          The @SafeVarargs annotation can be applied only to methods that cannot be overridden. These include static methods, final instance methods, and, new in Java SE 9, private instance methods.


                          • You can use diamond syntax in conjunction with anonymous inner classes.
                          Types that can be written in a Java program, such as int or String, are called denotable types. The compiler-internal types that cannot be written in a Java program are called non-denotable types.
                          Non-denotable types can occur as the result of the inference used by the diamond operator. Because the inferred type using diamond with an anonymous class constructor could be outside of the set of types supported by the signature attribute in class files, using the diamond with anonymous classes was not allowed in Java SE 7.
                          In Java SE 9, as long as the inferred type is denotable, you can use the diamond operator when you create an anonymous inner class.

                          For more detail information please refer the Java official doc.


                          Reference:

                          1. https://docs.oracle.com/javase/9/language/toc.htm
                          2. http://www.oracle.com/technetwork/java/javase/9all-relnotes-3704433.html
                          3. https://docs.oracle.com/javase/9/whatsnew/toc.htm

                          Key Changes in Java 9

                          On 21st September 2017 Oracle released new version of Java/JDK version 9.

                          in this tutorial we will see what all are the key changes in Java 9 and how it will improve the performance of an application and who this things are going to help a programmer to write good programs.

                          Java Platform Module System

                          Introduces a new kind of Java programming component, the module, which is a named, self-describing collection of code and data. This module system have following features:

                          1. Introduces the modular JAR file, which is a JAR file with a module-info.class file in its root directory.
                          2. Introduces a new optional phase, link time, which is in-between compile time and run time, during which a set of modules can be assembled and optimized into a custom runtime image.
                          3. Adds options to the tools javac, and java where you can specify module paths, which locate definitions of modules.
                          4. Introduces the JMOD format, which is a packaging format similar to JAR except it can include native code and configuration files.
                          5. The JDK itself has been divided into a set of modules. 

                          For more detail information you can download Java 9 release notes from here.

                          New Version-String Scheme

                          Provides a simplified version-string format that helps to clearly distinguish major, minor, security, and patch update releases.


                          The new version-string format is as follows: 

                          $MAJOR.$MINOR.$SECURITY.$PATCH

                          For more detail see version-string format or browse the link from reference.

                          References:


                          How to pass command line argument in Java using Eclipse IDE


                          1. Right-click on your project or Java class file which you wants to execute.
                          2. Go to Debug As > Debug Configurations or Run As > Run Configurations option. this will open a new pop-up window as shown is below screen shot.
                          3. Click the tab Arguments.
                          4. Enter in your Program Arguments. e.g. agr1, agr2
                          5. Click Apply or Run

                          command line argument in Java using Eclipse IDE
                          Add command line argument in Java using Eclipse IDE

                          How to throw NullPointerException in a Java program

                          Exception Handling in Java program.

                          Throwable interface has three class.
                          1. Error
                          2. Runtime Exception
                          3. Exception

                          There are two types of exception in Java.

                          Checked: Which can be handle using try and catch block

                          • Exception class comes under the checked exception which we can handle.
                            • NullPointerException
                            • DivideByZeroException
                            • IndexOutOfBoundException
                            • ClassCastException

                          Unchecked : Which cannot be handle.

                          • Error and Runtime Exception come under the unchecked exception which we can't handle.


                          Below is a example program:

                          package rashid;

                          public class testException {

                          public static void main(String[] args) {
                          String var1=null;

                          System.out.println(var1.length());
                          }

                          }

                          Output:
                          Exception in thread "main" java.lang.NullPointerException
                          at rashid.testException.main(testException.java:8)


                          Static block and method in Java?

                          Can a class be static in Java?

                          We can not make top level class static. Only nested or inner classes can be static.

                          Can we call main method explicitly in Java?

                          Yes, we can call main method explicitly.

                          Can we execute a program without main method?

                          No, we can not execute a program without main method. Up to Java 6 we were able to run a program using static block.

                          How to create a static method in Java? How to create a static block in Java? Inner Class in Java?
                          Below is the example code:


                          package abctest;

                          public class testExa {
                          public static void main(String[] args) {
                          System.out.println("Main method is working!!");

                          //Explicitly call main method of other class
                             rashid.main(args);
                                 }
                          /* static block start*/
                          static {
                                 System.out.println("static block called ");
                                 
                                 //Call static method inside static block
                                 nameUser();     
                                 String[] val={"ABCD","CDE"};
                                 
                                 //Explicitly call main method from static block
                                 main(val);
                                 System.out.println("exiting static block called ");
                          }
                          /* static block end*/

                          //Static method
                          public static String nameUser()
                          {
                          String UserName="Name";
                          System.out.println("Static method executing");
                          return UserName;
                          }

                          //Static class declaration; Only inner class could be declare as a static
                          public static class rashid{
                          public static void main(String args[])
                          {
                          System.out.println("Main from class Rashid");
                          }
                          }
                          }

                          Output:


                          static block called 
                          Static method executing
                          Main method is working!!
                          Main from class Rashid
                          exiting static block called 
                          Main method is working!!

                          Main from class Rashid


                          why Java does not support multiple inheritance

                          Java does not support multiple inheritance because Java does not want any ambiguity and confusion in the code.

                          Look here how:
                          Suppose we have a class A which has two methods method1() and method2(). Now another class B inherit the class A and given the definition for both method1 and method2. the another class C inherit class A and B at this point Java will get confused when we give definition for any method in class C. Here the confusion will be that Java don't know exactly from which class we are going to inherit this method either super class class A or class B, since in both the classes we have the method1 and method2.

                          This is the reason because of that  Java does not support multiple inheritance.


                          Java Tutorial for beginner 

                          Simple Spring project example

                          Create a implementation class ImplCode.java

                           1
                           2
                           3
                           4
                           5
                           6
                           7
                           8
                           9
                          10
                          11
                          12
                          13
                          14
                          15
                          16
                          17
                          18
                          19
                          20
                          21
                          import org.springframework.context.ApplicationContext;
                          
                          import org.springframework.context.support.FileSystemXmlApplicationContext;
                          
                          public class ImplCode {
                          
                           public static void main(String[] args) {
                          
                            ApplicationContext appContext=new FileSystemXmlApplicationContext("AppContextBeanFile.xml");
                          
                            Fruit fruit=appContext.getBean("fruit", Fruit.class);
                          
                            Vegetable veg=(Vegetable) appContext.getBean("veg");
                          
                            System.out.println(fruit.whoareyou());
                          
                            System.out.println(veg.whoareyou());
                          
                           }
                          
                          }
                          

                          Create a bean class Vegetable.java

                           1
                           2
                           3
                           4
                           5
                           6
                           7
                           8
                           9
                          10
                          11
                          12
                          13
                          package rashiddemo;
                          
                          public class Vegetable {
                          
                           public String whoareyou() {
                          
                            String intro="I am vegetable!!";
                          
                            return intro;
                          
                           }
                          
                          }
                          

                          Create another bean class Fruit.java

                           1
                           2
                           3
                           4
                           5
                           6
                           7
                           8
                           9
                          10
                          11
                          12
                          13
                          package rashiddemo;
                          
                          public class Fruit {
                          
                           public String whoareyou() {
                          
                            String intro="I am fruit!";
                          
                            return intro;
                          
                           }
                          
                          }
                          

                          Create a AppContextBeanFile.xml and add your bean classes using bean tag.

                           1
                           2
                           3
                           4
                           5
                           6
                           7
                           8
                           9
                          10
                          11
                          12
                          13
                          <?xml version="1.0" encoding="UTF-8"?>
                          
                          <beans xmlns="http://www.springframework.org/schema/beans"
                          
                           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                          
                           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
                          
                            <bean id="fruit" class="rashiddemo.Fruit"></bean>
                          
                           <bean id="veg" class="rashiddemo.Vegitable"></bean>
                          
                          </beans>
                          

                          Pyramid in Java Programming

                          Java Programs

                          In this tutorial we are going to write a program which will print Pyramid with given number.

                          import java.util.*;
                          public class Main {
                          public static void main(String[] args) {
                          for(int i=1;i<=5;i++){
                          System.out.println();
                          for(int j=1;j<=i;j++)
                          System.out.print("\t" + j);
                          }
                          }
                          }


                          Output:


                           1
                          1 2
                          1 2 3
                          1 2 3 4
                          1 2 3 4 5

                          Java Virtual Machine

                          JDK is a software development program provided by sun Microsystems. Java Development Kit or JDK comes in various version and can be downloaded free from the sun Microsystems. JVM compiler, debugger and other tools are used with JDK for developing java based application & java applets. So make sure that your JVM compiler & JDK versions are same. 

                          What is the Java Virtual Machine? What  is its role?

                          Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.