Sunday, 23 October 2016

How to find vowels in a string in java program

What is the java coding to find out vowels in a string? How to use OR operator in java? because the symbol " || " is not taken while i executing the java program.

try the below code The program iterats over the given string and check if each character is an vowel 1. The symbol '||' can be used as OR, below program is an example

 public class Test {

    public static void main(String[] args) {    
        String str ="This is a test";
        for(int i=0;i <str.length();i++){
            if((str.charAt(i) == 'a') || 
                (str.charAt(i) == 'e')  ||
                (str.charAt(i) == 'i') || 
                (str.charAt(i) == 'o') ||
                (str.charAt(i) == 'u')) {
                System.out.println(" The String contains " + str.charAt(i));
            }
        }
    }
    }
Note: it will match only lower case vowels

Friday, 21 October 2016

Using the Java Native Interface in C#

Using the Java Native Interface in C#

Introduction

The JNI or Java Native Interface is a set of features available in the Java platform. Applications that use the JNI can incorporate Java code with code written in other languages such as C++, Delphi, and C#.
In my example, I will show you how to call a couple of Java methods from a C# client.

Advantages

You can reuse your existing libraries/classes that were previously written in Java from your new application written in C#. This means that you do not have to abandon your legacy code written in Java and reinvent the wheel again in C#.

Background

One of the most important things to be familiar in JNI is Field Descriptors. As you will notice in the test harness, when I call a Java method that takes a string parameter, I pass in "Ljava/lang/String;". This represents a field type in the Java programming language. For example, if you wanted to represent an int field, then you would use "I", a float field would be "F", and a boolean field would be "Z", etc.
The table below describes the primitive types in the Java programming language and the corresponding types in JNI. All field descriptors that start with L are dealt with as objects (note: a string is passed as an object) and must be terminated by a ";" character. An array type is always prefixed with the "[" character.
JNI Field DescriptorJava Language Type
Zboolean
Bbyte
Cchar
Sshort
Iint
Jlong
Ffloat
Ddouble
Ljava/lang/String;string
[Ljava/lang/Object;object[]
Method descriptors make use of the fields descriptors and describe the structure of a Java method. There are no spaces between the field descriptors in a method descriptor.
Apart from the void return type which is denoted by V, all other return types use the field descriptor. The table below describes the Java method declaration and the corresponding JNI descriptor. The JNI method descriptor is used when calling a Java method from C# via JNI.
Java Method DeclarationJNI Method Descriptor
String foo();"()Ljava/lang/String;"
Void bar(int I, bool b);(IZ)V

Using the code

An example of calling Java code from a .NET GUI application

Once a reference is set to the assembly JNI located in the download section of my code, you can start to call Java methods in only a few lines of code.
The first thing that needs to be done is to create a dictionary object that will contain all of the parameters to pass to the Java Virtual Machine. In the example below, I am doing the minimum of setting the class path that will tell the JVM where to look for the classes and packages.
private Dictionary<string, string> jvmParameters = new Dictionary<string, string>();
jvmParameters.Add("-Djava.class.path", Location of the java class);
Once the JVM parameters have been assigned to the dictionary object, an instance of JavaNativeInterfacecan be created. Once created, the method LoadJVM needs to be called with the JVM parameters, and this will then load up the Java Virtual Machine. Once loaded, the user calls the method to instantiate the Java object (note that the use of the method InstantiateJavaObject is optional as the user may just want to call a static method, in which case, this method does not need to be called; however, it will not cause any harm).
Java = new JavaNativeInterface();
Java.LoadVM(jvmParameters, false);
Java.InstantiateJavaObject(Name of the java class excluding the extension);
Once the JVM has been loaded and a class instantiated, the user may call any method they wish. First create an object list that will contain all of the parameters to pass into the Java method. As it is an object list, it can hold parameters of different types as everything inherits from an object.
List<object> olParameters = new List<object>();
olParameters.Add(Value of the parameter to be passed to the java method);
Next, simply call the generic method CallMethod passing in the return type of the Java method as the template type. In the example below, I am calling CallMethod<string> which means that the return type of my Java method that I want to call is a string.
Next, pass in the name of the Java method to call and the method descriptor (see above); finally, pass in the list of all of the parameters. (Note: If no parameters are required, then pass in an empty list.)
Java.CallMethod<string>("AddTwoNumbers", "(IILjava/lang/String;)I", olParameters);
Well, I guess that wraps it all up, but remember that there is so much more you can do with JNI. The test application was just a quick and dirty way to demonstrate the basics of the JNI component. For a full understanding of JNI, I advise you to read this book: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/.

compile and run of java program

compile and run of java program

If you are new to Java programming and wish to learn it right now by doing some hands-on practice, you have come to the right place. This tutorial will help you writing your first Java program, typically a “hello world” one - your first step of the adventure into Java programming world. Throughout this tutorial, you will learn fundamental concepts and steps which are necessary for every Java fresher.
To start, all you need is a fresh computer without any Java software installed, a text-based editor and a good internet connection.
NOTES: This beginner tutorial is targeted for Windows environment.


1. Downloading and installing JDK software

In order to write and run a Java program, you need to install a software program called Java SE Development Kit (or JDK for short, and SE means Standard Edition). Basically, a JDK contains:
    • JRE(Java Runtime Environment): is the core of the Java platform that enables running Java programs on your computer. The JRE includes JVM(Java Virtual Machine) that runs Java programs by translating from bytecode to platform-dependent code and executes them (Java programs are compiled into an intermediate form called bytecode), and other core libraries such as collections, File I/O, networking, etc.
    • Tools and libraries that support Java development.
The JDK ships with two powerful tools which every Java developer should be familiar with:
    • javac.exe: is Java compiler that translates programs written in Java code into bytecode form.
    • java.exe: is the Java Virtual Machine launcher that executes bytecode.
Click on the following link to download the latest version of JDK installer program:
Check the option “Accept License Agreement”, and choose an appropriate version for your computer from the list. Here we choose the version for Windows x64:

After downloading the program, run it to install the JDK on your computer (just following the steps, leave the defaults and click Next, Next…):
After downloading the program, run it to install the JDK on your computer (just following the steps, leave the defaults and click Next, Next…):

You would see the JDK is installed in the following directory, for example: C:\Program Files\Java\jdk1.7.0_21. The following screenshot describes the JDK’s directory structure:

Now let’s test if Java runtime is installed correctly. Open a command prompt window and type:
java -version
You would see the following result:

That shows version of the JRE, e.g. “1.7.0_21” - Congratulations! Your computer is now capable of running Java programs.
Now try to type the following command:
javac -version
You would see the following error:


That’s because Windows could not find the javac.exe program, so we need to set some environment variables which tell the location of javac.exe.


2. Setting up environment variables

Now we’re going to set environment variables so that the javac.exe program can be accessed anywhere from command line. On Windows 7, go to My Computer and click System Properties:
Then click Advanced system settings:
The System Properties dialog appears, select Advanced tab and click Environment Variables...:
The Environment Variable dialog appears, click on the New… button under the System variables section.
That opens up the New System Variable dialog. Type the following information:
The field Variable name must be JAVA_HOME, and the field Variable value must point to JDK’s installation directory on your computer. Here it is set to c:\Program Files\Java\jdk1.7.0_21. Click OK to close this dialog.
Now back to the Environment Variables dialog, look for a variable called Path under the System Variables list, and clickEdit…:
In the Edit System Variable dialog, append the following to the end of the field Variable value:
;%JAVA_HOME%\bin
Note that there is a semicolon at the beginning to separate this value from other ones. Click OK three times to close all the dialogs.
Now we have to quit the current command prompt and open a new one to see the changes takes effect. Type the following command again in the re-opened command prompt window:
javac -version

You would see the following output:
Congratulations! You have completed the setup for essential Java development environment on your computer. It’s now ready to write your first Java program.









This tutorial shows how to implement a Java web application that uploads files to server and save the files into database.
The application applies the following technologies:
    • Servlet 3.0: Using Servlet 3.0 we can write code to handle file upload easily. For detailed explanation of how to upload file with Servlet 3.0, read the tutorial
    • MySQL database 5.5: We will store uploaded files in MySQL database. For more details about how to store files in MySQL database, read the article       
    • The application will consist of the following source files:
        • Upload.jsp: presents a form which allows users entering some information (first name and last name), and picking up a file (a portrait image).
        • FileUploadDBServlet: captures input from the upload form, saves the upload file into database, and forwards the users to a message page.
        • Message.jsp: shows either successful or error message.
      Now, let’s go through each part of the application in details.

      1. Creating MySQL database table

      First, let’s create a database and a table in MySQL. Execute the following script using either MySQL Command Line Clientor MySQL Workbench:
    • create database AppDB;
       
      use AppDB;
       
      CREATE TABLE `contacts` (
        `contact_id` int(11) NOT NULL AUTO_INCREMENT,
        `first_name` varchar(45) DEFAULT NULL,
        `last_name` varchar(45) DEFAULT NULL,
        `photo` mediumblob,
        PRIMARY KEY (`contact_id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=latin1

The script will create a database named AppDB and a table named contacts. File will be stored in the column photo which is of type mediumblob which can store up to 16 MB of binary data. For larger files, use longblob (up to 4 GB).

2. Coding upload form page

Write code for the upload form as follows (Upload.jsp):

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
    <center>
        <h1>File Upload to Database Demo</h1>
        <form method="post" action="uploadServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>First Name: </td>
                    <td><input type="text" name="firstName" size="50"/></td>
                </tr>
                <tr>
                    <td>Last Name: </td>
                    <td><input type="text" name="lastName" size="50"/></td>
                </tr>
                <tr>
                    <td>Portrait Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>



This page shows two text fields (first name and last name) and a file field which allows the users choosing a file to upload. The action attribute of this form is set to uploadServlet which is URL mapping of the servlet we will create in the next section.

3. Coding file upload servlet

Create a servlet class named FileUploadDBServlet.java with the following code: