Generate random Id using java inbuilt UUID object

Using java inbuilt UUID object here we are going to print 5 unique ids.  Using this approach it is guaranteed that every time java compiler will print the new and unique id.

import java.util.UUID;

public class GenerateId {
    public static void main(String[] args) {
       
        for (int i = 0; i < 5; i++){
            String generatedID = UUID.randomUUID().toString();
            System.out.println(generatedID);
        }
    }
}


Output:

d53abfbd-e92a-4651-91f6-fb134b959c0f
bf2da306-74ef-4657-a27d-47d8b9a8e2b9
2a69cb7b-8df1-47a3-90f2-c0fcf0f4d553
70861ec7-40de-493d-8a71-81856445d2a1
a87d98d4-f1af-472b-94fe-af3af6124902

How to print number triangle using the for loop

Here we are going to print the number triangle. As we change number of rows we see the different result.

public class NumberTriangle {
    public static void main(String arg[]) {
        int rows = 10; // change rows accordingly
        int count = 1;
        for (int i = 1; i <= rows; i++) {
            for (int j = 0; j < i; j++) {
                if (count < 10)
                    System.out.print(count + "  ");
                else
                    System.out.print(count + " ");
                count++;
            }
            System.out.println();
        }
    }
}
Output: 1 
2  3 
4  5  6 
7  8  9  10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

How to print the class, package and method name using java code

Below java code will be able to print the current java class name, package name as well as method name.

package com.java.amzi;

public class FindClassPackageName {

    public void className() {
        System.out.println("Class name is: " + this.getClass().getSimpleName());
    }

    public void packageName() {
        System.out.println("Package name is: "
                + this.getClass().getCanonicalName());
        // System.out.println(this.getClass().getName());
    }

    public void methodName() {
        System.out.println("Current method name is: "
                + new Exception().getStackTrace()[0].getMethodName());
    }

    public static void main(String[] args) {

        FindClassPackageName find = new FindClassPackageName();
        find.className();
        find.packageName();
        find.methodName();
    }
}


Output:

Class name is: FindClassPackageName
Package name is: com.java.amzi.FindClassPackageName
Current method name is: methodName

Hibernate tutorial


Hibernate section will be coming soon...

Junit example


Junit section will be coming soon...

JAXB example for Marshalling the java object to xml

First of all we need to create a JAXB object. With 4 fields along with getters and setters we are going to create an Employee object.

package com.java.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

    private String firstName;
    private String lastName;
    private long ssn;
    private int eId;

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlElement
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @XmlElement
    public long getSsn() {
        return ssn;
    }

    public void setSsn(long ssn) {
        this.ssn = ssn;
    }

    @XmlAttribute
    public int geteId() {
        return eId;
    }

    public void seteId(int eId) {
        this.eId = eId;
    }
}


Now, we are going to create an EmpObj class and in which we are going to set the value for Employee object. Once after we run this java class, we will be getting the employee.xml file generated into the specified temp folder and also the same content will be printed into the console.


package com.java.example;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class EmpObj {

    public static void main(String[] args) {

        Employee employee = new Employee();
        employee.seteId(007);
        employee.setFirstName("James");
        employee.setLastName("Bond");
        employee.setSsn(123456789);

        try {

            File file = new File("C:\\Temp\\employee.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // optional line to format the xml, without this line the whole xml
            // will be printed into one single line
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            // This line will write the generated xml into the specified temp
            // location
            jaxbMarshaller.marshal(employee, file);
            // This line will print the generated xml into the console.
            jaxbMarshaller.marshal(employee, System.out);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee eId="7">
    <firstName>James</firstName>
    <lastName>Bond</lastName>
    <ssn>123456789</ssn>
</employee>

How to print numbers as per the phone keypad for any given string

Here we are going to write a java program to convert any String into the phone keypad digits.
eg. ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9)

import java.util.Scanner;

public class PhoneKeypad {
    public static int getNumber(char uppercaseLetter) {
        int number = 0;
        switch (uppercaseLetter) {
        case 'A':
        case 'B':
        case 'C':
            number = 2;
            break;
        case 'D':
        case 'E':
        case 'F':
            number = 3;
            break;
        case 'G':
        case 'H':
        case 'I':
            number = 4;
            break;
        case 'J':
        case 'K':
        case 'L':
            number = 5;
            break;
        case 'M':
        case 'N':
        case 'O':
            number = 6;
            break;
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
            number = 7;
            break;
        case 'T':
        case 'U':
        case 'V':
            number = 8;
            break;
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
            number = 9;
        }
        return number;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a string to convert in phone keypad: ");
        String stringVal = in.nextLine();

        for (int i = 0; i < stringVal.length(); i++) {
            if (Character.isLetter(stringVal.charAt(i)))
                System.out.print(getNumber(Character.toUpperCase(stringVal
                        .charAt(i))));
            else
                System.out.print(stringVal.charAt(i));
        }
    }
}


Output:

Enter a string to convert in phone keypad: AbCdE
22233

Simple employee salary calculator

 In this example consider that every employee is getting $37.50 per hour and the standard hours per week is 40 hours/week. If any employee works more than 40 hours per week then he/she should be earning $2.50 additional per extra hour worked.

import java.util.Scanner;

public class SalaryCalculator {

    public static void main(String[] args) {

        System.out.print("Enter number of hours worked: ");
        Scanner in = new Scanner(System.in);
        double totalHoursWorked = in.nextInt();
        double standardWage = 37.50;
        int standardHours = 40;
        double totalWage;
        double overtimeBonus = 2.50;

        if (totalHoursWorked > 40)
            totalWage = (standardWage * totalHoursWorked)
                        + (totalHoursWorked - standardHours) * overtimeBonus;
        else if (totalHoursWorked < 40)
            totalWage = standardWage * totalHoursWorked;
        else
            totalWage = standardWage * standardHours;

        System.out.println("Your total salary of the week is: " + totalWage);
    }
}


Output:

Enter number of hours worked: 30
Your total salary of the week is: 1125.0

Find user's operating system (OS) using java code and understand the static block.

Static block can be used to check conditions before execution of main begin, Suppose we have developed an application which runs only on Windows operating system then we need to check what operating system is installed on user machine. In our java code we check what operating system user is using if user is using operating system other than "Windows" then the program terminates.

We are using getenv method of System class which returns value of environment variable name of which is passed an as argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, 7, 8 and others.

public class FindOS {

    public static void main(String[] args) {
        System.out.println("You are using Windows operating system.");
    }
    static {
        String os = System.getenv("OS");
        if (os.equals("Windows_NT") != true) {
            System.exit(1);
        }
    }
}


Output from Windows OS:

You are using Windows operating system.

Java code to convert Fahrenheit to Celsius

Below is the java code to print and convert  Fahrenheit to Celsius.

import java.util.*;

class FahrenheitToCelsius {
    public static void main(String[] args) {
        float temperature;
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the temperature in Fahrenheit: ");
        temperature = in.nextInt();

        temperature = (temperature - 32) * 5 / 9;
        System.out.println("Temperature in Celsius = " + temperature);
    }
}


Output:

Enter the temperature in Fahrenheit: 70
Temperature in Celsius = 21.11111

Print alphabets using java code

Below code will print the English alphabets in upper case using simple "for loop". If you want to print in lower case then simply switch the case of A and Z in the for loop.

public class PrintAlphabets {
    public static void main(String args[]) {
        char ch;

        for (ch = 'A'; ch <= 'Z'; ch++)
            System.out.print(ch + " ");
    }
}


Output:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Java code to check the given string is palindrome or not

Here we are going to check whether the given string value is palindrome or not. We will declare two String as "original" and "reverse". Then import the Scanner object which will enable us to enter any String value into the console. In my example I'm going to enter "mom" as an original String and which is obviously a palindrome.

Palindrome definition:

The string value should be the same whether we read from left hand side or from right hand side.
Palindrome exp: mom, dad
Non palindrome exp: java, string etc.

import java.util.*;
public class PalindromeTest {
    public static void main(String args[]) {         String original, reverse = "";         Scanner in = new Scanner(System.in);         System.out.print("Enter a string to check if it is a palindrome: ");         original = in.nextLine();         int length = original.length();         for (int i = length - 1; i >= 0; i--)             reverse = reverse + original.charAt(i);         if (original.equals(reverse))             System.out.println("Entered string is a palindrome.");         else             System.out.println("Entered string is not a palindrome.");     } }

Output:

Enter a string to check if it is a palindrome: mom
Entered string is a palindrome.

Accessing java bean from JSP using jsp useBean tag

First of all write a java bean called "Address" and for the simplicity add only two fields "city" and "state" generate getters and setters and the java class should look something like this.

public class Address {

 private String city;
 private String state;

 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;
 }

}

Now, create a jsp page and add the below code snippet inside the body tag.


    <jsp:useBean id="add" class="Address">
        <jsp:setProperty name="add" property="city" value="Newyork" />
        <jsp:setProperty name="add" property="state" value="NY" />
    </jsp:useBean>
    City:
    <jsp:getProperty property="city" name="add" /><br> 
    State:
    <jsp:getProperty property="state" name="add" /><br> 
    <%-- instead of getProperty tag we can use below 
    expression and can get the same results
    City: ${add.city} <br> 
    State: ${add.state } --%>
Output:
Once after you run the jsp on your installed application server, the output should look something like this.
City: Newyork
State: NY

How to load/read properties file from java code

Below java class will enable us to load and read the properties file. In one of the previous tutorial we have written to the properties file so keeping that in mind once after we run this program we will get the desired output. For earlier tutorial please click here

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class LoadProperties {
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
            // load a properties file
            prop.load(new FileInputStream("config.properties"));

            // get the property value and print it out
            System.out.println(prop.getProperty("url"));
            System.out.println(prop.getProperty("username"));
            System.out.println(prop.getProperty("password"));
            // below line will print null as it doesn't exist
            System.out.println(prop.getProperty("will print null"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


Output:

host IP Address
Amzi
passw0rd
null

Find the given number as even or odd in Java

This example will prompt to enter any integer number and as per the formula it will print weather the number is even or odd.

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter any integer number: ");
        int number = scanner.nextInt();

        if (number % 2 == 0)
            System.out.println(number + " is an even number");
        else
            System.out.println(number + " is an odd number");
    }
}


Output:

Please enter any integer number: 7
7 is an odd number

Create and write to the properties file using java code.

Below java code snippet will create a new property file and write the properties into it.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WriteProperty {
   
    public static void main(String[] args) {
        Properties property = new Properties();
        try {
            // set the properties values
            property.setProperty("url", "host IP Address");
            property.setProperty("username", "Amzi");
            property.setProperty("password", "passw0rd");

            // save properties to project root folder
            property.store(new FileOutputStream("config.properties"), null);
            System.out
            .print("properties are saved into the destination folder");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

properties are saved into the destination folder

config.properties file should look something like this:

#Fri Aug 23 11:49:29 EDT 2013
password=passw0rd
url=host IP Address
username=Amzi

How to create a text file and write into it using java code

This java program will create a new text file in the specified location and also will write the String content to the file.

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

public class CreateAndWriteToTextFile {
    public static void main(String[] args) {
        try {
            String content = "This is the test line which will be eventually written to the text file."
                    + "\n This is other Test line.";
            File file = new File("/Users/Amzi/Amzi.txt");
            // Checks if the file already exists or not
            if (!file.exists())
                file.createNewFile();

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            System.out.println("Content is written to the file!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

Content is written to the file!

How to swap/interchange two numbers in Java

In this example I'll show you two ways to swap the integer numbers.

import java.util.Scanner;

class SwapNumbers {
    public static void main(String args[]) {
        int x, y;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter x");

        x = in.nextInt();
        System.out.println("Enter y");
        y = in.nextInt();

        System.out.println("Before Swapping\nx = " + x + "\ny = " + y);

        x = x + y;
        y = x - y;
        x = x - y;

        // This is the second way to swap between two numbers
        /*
         * int temp = x; x = y; y = temp;
         */

        System.out.println("After Swapping\nx = " + x + "\ny = " + y);
    }
}


Output:

Enter x
10
Enter y
20
Before Swapping
x = 10
y = 20
After Swapping
x = 20
y = 10

Using conditional if else statement print number in words

Below java code will print the integer value between 1 to 9 into words, any number other than 1 to 9 will be displayed as "OTHER".

import java.util.Scanner;

public class PrintNumberInWord {
    public static void main(String[] args) {
        System.out.println("Enter any integer number ");
        Scanner in = new Scanner(System.in);
        int number = in.nextInt();

        if (number == 1)
            System.out.println("ONE");
        else if (number == 2)
            System.out.println("TWO");
        else if (number == 3)
            System.out.println("THREE");
        else if (number == 4)
            System.out.println("FOUR");
        else if (number == 5)
            System.out.println("FIVE");
        else if (number == 6)
            System.out.println("SIX");
        else if (number == 7)
            System.out.println("SEVEN");
        else if (number == 8)
            System.out.println("EIGHT");
        else if (number == 9)
            System.out.println("NINE");
        else
            System.out.println("OTHER");
    }
}


Output:

Enter any integer number
9
NINE

Simple calculator using Scanner object

 Below java class will explain you how to use the Scanner object which is a part of java.util package. This class is basically for integer values only however you can use the same way for double, float etc.


import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your first integer value: ");
        int first = in.nextInt();
        System.out.println("Enter your second integer value: ");
        int second = in.nextInt();

        int plus = first + second;
        int minus = first - second;
        int multiply = first * second;
        int divide = first / second;

        System.out.println("Summation for " + first + " and " + second
                + " is: \t\t" + plus);
        System.out.println("Subtraction for " + first + " and " + second
                + " is: \t\t" + minus);
        System.out.println("Multiplication for " + first + " and " + second
                + " is: \t" + multiply);
        System.out.println("Division for " + first + " and " + second
                + " is: \t\t" + divide);
    }
}


Output:

Enter your first integer value: 
50
Enter your second integer value: 
50
Summation for 50 and 50 is:       100
Subtraction for 50 and 50 is:     0
Multiplication for 50 and 50 is:  2500
Division for 50 and 50 is:        1

Calling super class constructor from sub class constructor

This example will help you to understand the constructor chaining along with the inheritance concept in java. The following java code snippet is the super class which has 3 set of constructors with different parameters along with getVolume() method.

public class ParentCube {

    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    ParentCube() {
        this(10, 10);
        System.out.println("Finished with Default Constructor of ParentCube");
    }

    ParentCube(int l, int b) {
        this(l, b, 10);
        System.out
        .println("Finished with Parameterized Constructor having 2 params of ParentCube");
    }

    ParentCube(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out
        .println("Finished with Parameterized Constructor having 3 params of ParentCube");
    }
}


Now, we will create the sub class which will extend the super class and will call the super class constructor from its own constructor. Once after we see the output of the following program, it will be clear how the execution flow is moving.

public class ChildCube extends ParentCube {

    int weight;

    ChildCube() {
        super();
        weight = 10;
        System.out
        .println("Finished with Parameterized Constructor having 0 param of ChildCube");
    }

    ChildCube(int l, int b) {
        this(l, b, 10);
        System.out
        .println("Finished with Parameterized Constructor having 2 params of ChildCube");
    }

    ChildCube(int l, int b, int h) {
        super(l, b, h);
        weight = 20;
        System.out
        .println("Finished with Parameterized Constructor having 3 params of ChildCube");
    }

    public static void main(String[] args) {
        ChildCube childObj1 = new ChildCube();
        ChildCube childObj2 = new ChildCube(10, 20);
        System.out.println("Volume of childObj1 is : " + childObj1.getVolume());
        System.out.println("Weight of childObj1 is : " + childObj1.weight);
        System.out.println("Volume of childObj2 is : " + childObj2.getVolume());
        System.out.println("Weight of childObj2 is : " + childObj2.weight);
    }
}


Output
Finished with Parameterized Constructor having 3 params of ParentCube
Finished with Parameterized Constructor having 2 params of ParentCube
Finished with Default Constructor of ParentCube
Finished with Parameterized Constructor having 0 param of ChildCube
Finished with Parameterized Constructor having 3 params of ParentCube
Finished with Parameterized Constructor having 3 params of ChildCube
Finished with Parameterized Constructor having 2 params of ChildCube
Volume of childObj1 is : 1000
Weight of childObj1 is : 10
Volume of childObj2 is : 2000
Weight of childObj2 is : 20

Java code to greet the user based on the current time.

Here I am going to explain, how to get the current date and time using java code. Also, based on the current time how to greet the user good morning, good evening etc.

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DisplayDateTime {
 public static void main(String[] args) {
  GregorianCalendar time = new GregorianCalendar();
  int hour = time.get(Calendar.HOUR_OF_DAY);
  int min = time.get(Calendar.MINUTE);
  int day = time.get(Calendar.DAY_OF_MONTH);
  int month = time.get(Calendar.MONTH) + 1;
  int year = time.get(Calendar.YEAR);

  System.out.println("The current time is \t" + hour + ":" + min);
  System.out.println("Today's date is \t" + month + "/" + day + "/"
    + year);

  if (hour < 12)
   System.out.println("Good Morning!");
  else if (hour < 17 && !(hour == 12))
   System.out.println("Good Afternoon");
  else if (hour == 12)
   System.out.println("Good Noon");
  else
   System.out.println("Good Evening");
 }
}

Output:

The current time is  12:2
Today's date is  8/20/2013
Good Noon

Java constructor chaining example

This example will illustrate, how the constructor chaining is achieved in Java.

public class ConstructorChaining {

    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    ConstructorChaining() {
        this(10, 10);
        System.out.println("In zero parameter Constructor");
    }

    ConstructorChaining(int length, int breadth) {
        this(length, breadth, 10);
        System.out.println("In two Parameterized Constructor");
    }

    ConstructorChaining(int length, int breadth, int height) {
        this.length = length;
        this.breadth = breadth;
        this.height = height;
        System.out.println("In threee Parameterized Constructor");
    }

    public static void main(String[] args) {
        ConstructorChaining cube1 = new ConstructorChaining();
        ConstructorChaining cube2 = new ConstructorChaining(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cube1.getVolume());
        System.out.println("Volume of Cube2 is : " + cube2.getVolume());
    }
}


Output:

In threee Parameterized Constructor
In two Parameterized Constructor
In zero parameter Constructor
In threee Parameterized Constructor
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

How to print the client IP address using java code.

Below is the java source code in order to capture the client ip address. After running this code, you should be able to see the ip address of the machine on which you are running your code.

import java.net.InetAddress;

class IPAddress {
    public static void main(String args[]) throws Exception {
        System.out.println(InetAddress.getLocalHost());
    }
}



How to open notepad using java code

Below is the java source code in order to open the notepad application. Once after running this program your notepad application will be opened.

import java.io.IOException;

class Notepad {
    public static void main(String[] args) {
        Runtime rs = Runtime.getRuntime();

        try {
            rs.exec("notepad");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Print multiplication tables for given range

Below is the java source code to print the range of multiplication table.
For an example if you pass the range between 3 to 7 then it will print all the tables starting from 3 until it reaches to 7.
In my case I'm passing two integers 7 and 8 so it will print the multiplication table for 7 and 8.

import java.util.Scanner;

class PrintTables {
    public static void main(String args[]) {
        int firstNumber, secondNumber, range, index;

        System.out
        .println("Enter range of numbers to print their multiplication table");
        Scanner in = new Scanner(System.in);

        firstNumber = in.nextInt();
        secondNumber = in.nextInt();

        for (range = firstNumber; range <= secondNumber; range++) {
            System.out.println("--------------------------");
            System.out.println("Multiplication table of " + range);
            System.out.println("--------------------------");

            for (index = 1; index <= 10; index++) {
                System.out.println(range + "*" + index + " = "
                        + (range * index));
            }
        }
    }
}
Output:
 

How to create the tomcat server instance on Eclipse IDE

Take the following steps in order to create the Tomcat or any other app/web server instance on Eclipse IDE.

Step:1
Start the Eclipse and go to Window > Show View > Other > Server > Servers and click OK.
Fig 1
Step:2
Now you should have the "servers" tab open in your Eclipse. Right click anywhere in the servers tab and click on New > Server(as shown in Fig 2) and a new pop up window will be open(Fig 3).
Fig 2
Now expand the Apache node and choose the latest version of Tomcat which will auto populate the host and the server name. Now click on Next and point to the directory location where you have downloaded the Tomcat library and click on Finish.
Fig 3
Step:3
By now you should be able to see the new node under the Servers tab. So, all you have to do is to start the server and test it. In order to start the server, you may click on the start button as per the Fig 4 or you may also right click on the Tomcat Server instance and click on start.
Fig 4
Once after you start the server, it will display some log messages on the console and should say server started as per the Fig 5.
Fig 5
Now, to verify you can open the browser and hit the URL - localhost:8080
Entering this url should redirect you to the admin page of Tomcat server. Now you Eclipse IDE is all set to deploy any war file.

Hope this short tutorial will help you configure the tomcat server. Feel free to ask any question if at all you have any issues.

How to reverse a String in Java

Below java code snippet will be responsible to reverse any string.

public class ReverseStringTest {
    public static void main(String[] args) {
        String inOrder = "JAVA";
        String reverse = new StringBuffer(inOrder).reverse().toString();
        System.out.println("Before reversing the string: " + inOrder);
        System.out.println("After reversing the string: " + reverse);
    }
}

Output:
Before reversing the string: JAVA
After reversing the string: AVAJ

How to create a new file using java code

New test file can be created using the below java code.
import java.io.File;
import java.io.IOException;

public class CreateFile {
   public static void main(String[] args) {
      try{
         File file = new File("C:/newfile.txt");
         if(file.createNewFile())
         System.out.println("File created Successfully!");
         else
         System.out.println
         ("Error, file may already exists.");
     }
     catch(IOException ioe) {
        ioe.printStackTrace();
     }
   }
}
Output: File created Successfully!