Writing and Running First Java Program

In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler [the name of the class files is same that of the class defined]. A .class file does not contain code that is native to the processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java.exe launcher tool then runs the application with an instance of the Java Virtual Machine.

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS.

Through the Java VM, the same application is capable of running on multiple platforms.

The Java Platform

A platform is the hardware or software environment in which a program runs. We’ve already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms.

If you wanna watch Core Java Videos free of cost, you can go for this link: http://www.bestdotnettraining.com/core-java-online-training

The Java platform has two components:

The Java Virtual Machine

The Java Application Programming Interface (API)

The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages.

The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.

Step 1. Create a Source File

/**

* The HelloWorld class implements an application that

* simply prints “Hello World!” to standard output.

*/

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello World”); // Display the string.

}

}

Save the code in a file with the name HelloWorld.java.[Not compulsory to save it with same name as that of class name]

Step 2. Compile the Source File into a .class File

Bring up a shell, or “command,” window. We can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run… and then entering cmd.

To compile the source file, change the current directory to the directory where the file is located. For example, if the source directory is java on the C drive, type the following command at the prompt and press Enter:

Goto your source code folder:

The command prompt should to D:\Core_Java_June_10>

If we enter dir at the prompt, you should see our source file.

Now we are ready to compile. At the prompt, type the following command and press Enter.

javac HelloWorld.java

The compiler has generated a bytecode file, HelloWorld.class. At the prompt, type dir to see the new file that was generated. Now that we have a .class file, you can run our program.

Step 3. Run the Program

In the same directory, enter the following command at the prompt:

java HelloWorld

A Closer Look at the “Hello World” Application

The “Hello World” application consists of three primary components: source code comments, the HelloWorld class definition, and the main method. The following explanation will provide us with a basic understanding of the code.

Source Code Comments

The following bold text defines the comments of the “Hello World!” application:

/**

* The HelloWorld class implements an application that

* simply prints “Hello World!” to standard output.

*/

class HelloWorld {

public static void main(String[] args) {

System.out.println (“Hello World”); // Display the string.

}

}

Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:

/* text */

The compiler ignores everything from /* to */.

/** documentation */

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation.

// text

The compiler ignores everything from // to the end of the line.

The HelloWorld Class Definition

The following bold text begins the class definition block for the “Hello World!” application:

class HelloWorld {

public static void main(String[] args) {

System.out.println (“Hello World”); // Display the string.

}

}

As shown above, the most basic form of a class definition is:

class Identifier {

. . .

}

The keyword class begins the class definition for a class named Identifier, and the code for each class appears between the opening and closing curly braces marked in bold above. Java being the object oriented programming language every code should and must be written in a class even main method must be defined in a class.

The main Method

The following bold text begins the definition of the main method:

class HelloWorld {

public static void main(String[] args) {

System.out.println (“Hello World”); //Display the string.

}

}

In the Java programming language, every application must contain a main method whose signature is:

public static void main(String[] args)

The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. We can name the argument anything we want, but most programmers choose “args” or “argv”.

The main method is the entry point for our application and will subsequently invoke all the other methods required by our program.

The main method accepts a single argument: an array of elements of type String.

public static void main(String[] args)

This array is the mechanism through which the runtime system passes information to our application. Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it

The “Hello World!” application ignores its command-line arguments, but we should be aware of the fact that such arguments do exist.

Finally, the line:

System.out.println (“Hello World”);

uses the System class from the core library to print the “Hello World!” message to standard output.

System is a class present in java.lang package [Java Libraries are bundled in form of bundles called packages]. This class has one member called out which has functionality of printing.

Common Problems (and Their Solutions)

1. Compiler Problems

Common Error Messages on Microsoft Windows Systems

‘javac’ is not recognized as an internal or external command, operable program or batch file

If we receive this error, Windows cannot find the compiler (javac).

Here’s one way to tell Windows where to find javac. Suppose we installed the JDK in C:\Program Files\Java\jdk1.6.0_20. At the prompt we have to type the following command and press Enter:

C:\Program Files\Java\jdk1.6.0_20\bin\javac HelloWorld.java

If we choose this option, we will have to precede our javac and java commands with C:\Program Files\Java\jdk1.6.0_20\bin\ each time we compile or run a program.

Update the PATH variable will resolve the problem permanently

Set the PATH variable if we want to be able to conveniently run the JDK executables (javac.exe, java.exe, javadoc.exe, etc.) from any directory without having to type the full path of the command. If we don’t set the PATH variable, we need to specify the full path to the executable every time we run it, such as:

C:\Program Files\Java\jdk1.6.0_20\bin\javac MyClass.java

It’s useful to set the PATH permanently so it will persist after rebooting.

How do I set the PATH permanently? To set the PATH permanently, add the full path of the C:\Program Files\Java\jdk1.6.0_20\bin directory to the PATH variable. Typically this full path looks something like C:\Program Files\Java\jdk1.6.0_20\bin. Set the PATH as follows on Microsoft Windows:

a. Click Start > Control Panel > System on Windows XP or Start > Settings > Control Panel > System on Windows 2000.

b. Click Advanced > Environment Variables.

c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:

C:\Program Files\Java\jdk1.6.0_20\bin

PATH environment variable is a series of directories separated by semi-colons (;) and is not case sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.

We should only have one bin directory for a JDK in the path at a time. Those following the first instance are ignored. If one is already present, update it to C:\Program Files\Java\jdk1.6.0_20\bin.

The new path takes effect in each new command window we open after setting the PATH variable.

2. Runtime Problems

1. Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld

If we receive this error, java cannot find our bytecode file, HelloWorld.class.

In such case we might have to change our CLASSPATH variable. To see if this is necessary, try clobbering the classpath with the following command.

set CLASSPATH=.

Now enter java HelloWorld again. If the program works now, we will have to change your CLASSPATH variable. The CLASSPATH variable is set in the same manner as that done for the PATH.

2. Exception in thread “main” java.lang.NoClassDefFoundError: HelloWorld/class

A common mistake made by beginner programmers is to try and run the java launcher on the .class file that was created by the compiler. For example, we will get this error if you try to run your program with java HelloWorld.class instead of java HelloWorld. Remember, the argument is the name of the class that you want to use, not the filename.

3. Exception in thread “main” java.lang.NoSuchMethodError: main

The Java VM requires that the class you execute with it have a main method at which to begin execution of your application. Check the signature of the main method.

HTML5 Forms Introduction and New Attributes

 Form Input types:

 HTML5 has several new input types for forms, using these means less development time and an improved user experience. These new features allow better input control and validation.

color

date

datetime

datetime-local

email

month

number

range

search

tel

time

url

week

HTML5 has several new attributes for <form> and <input>.

New attributes for <form>:

autocomplete

novalidate

New attributes for <input>:

autocomplete

autofocus

form

formaction

formenctype

formmethod

formnovalidate

formtarget

height and width

list

min and max

multiple

pattern (regexp)

placeholder

required

step

<!DOCTYPE html>

<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<meta charset=”utf-8″ />

<title>HTML Form</title>

<style>

input:required:invalid, input:focus:invalid {

border-color:red;

}

input:focus:valid

{

color:blue

}

</style>

</head>

<body>

<form action=”/” method=”post”>

Name: <input type=”text” placeholder=”LastName, FirstName” required/> <br />

Employee ID: <input type=”text” pattern=”[a-z][0-9]{4}” placeholder=”1 letter + 4 nums” /> <br />

Color: <input type=”color” id=”colorpicker” name=”color” value=”#ff0000″><div id=”hexcolor”></div> <br />

Experience (0-20): <input type=”rangemin=”0″ max=”20″ step=”1″ value=”3″ /> <br />

Date of Birth: <input type=”date” name=”dob” value=”2011-01-13″ /> <br/>

Time of Birth: <input type=”time” name=”bdaymonth”> <br />

Join Month and Year: <input type=”month” name=”bdaymonth”> <br />

Choose Even Number: <input type=”numbermin=”0″ max=”200″ step=”2″ value=”0″ /> <br />

Telephone Number: <input type=”tel” name=”telphone” value=”98490 01840″ /> <br />

Email Id: <input type=”email” list=”emailchoices” name=”lstCourses” />

<datalist id=”emailchoices“>

<option label=”Sandeep Soni” value=”sandeepsoni@deccansoft.com”>

<option label=”Rahul” value=”rahul@deccansoft.com”>

<option label=”E.M. Sai” value=”sai@deccansoft.com”>

</datalist> <br />

URL: <input type=”url” name=”siteurl” value=”http://www.deccansoft.com” /> <br />

Preferred Holiday Week: <input type=”week” name=”week_year”> <br />

<input type=”submit” name=”submit” value=”Submit” />

</form>

</body>

</html>

 Form Elements:

<output> element :- The <output> element represents the result of a calculation

<form oninput= “x.value=parseInt(a.value) + parseInt(b.value)”>0

<input type=”range” id=”a” value=”50″>100 +

<input type=”number” id=”b” value=”50″>=

<output name=”x” for=”a b”></output>

</form>

Attributes in Form tag:

 <form> /<input> autocomplete Attribute

The autocomplete attribute is used to provide help for user during form entry by showing previous entered data in drop-down list for re-entering data. The autocomplete attribute has two states, on and off. By default its state is on for form.

<form action=”demo1.php” target=”my-iframe1″ id=”form1″ autocomplete=”on”>

Enter your Name: <input type=”text” name=”name”/>

Contact Num: <input type=”text” name=”num”/>

Email ID: <input type=”email” name=”mail” autocomplete=”off”/>

<input type=”submit”/>

</form>

  <form> novalidate Attribute

 novalidate if a form-level attribute used to turn off validation for a form, despite the attributes of the inputs it contains (i.e. will override inputs with the required attribute

<form action=”saveperson.aspx”>

<label for=”name”>Name: </label>

<input type=”text” name=”name” required/><br/>

<label for=”age”>Age: </label>

<input type=”number” name=”age”/><br/>

<input type=”submit” value=”Save”/>

<input type=”submit” value=”Cancel” formaction=’cancel.aspx’ formnovalidate/>

</form>

 Attributes for <input>

 <input> autofocus Attribute

It specifies that an <input> element should automatically get focus when the page loads.

<form action=”demo_form.asp”>

Name:<input type=”text” name=”name” autofocus><br>

Telephone: <input type=”tel” name=”tel”><br>

<input type=”submit”>

<input> form Attribute

It specifies one or more forms an <input> element belongs to Deccansoft Software Services HTML 5 – Form Elements

<form action=”form.asp” id=”form1″>

Student Name<input type=”text” name=”fname”><br>

<input type=”submit” value=”Submit”>

</form>

PhoneNumber <input type=”tel” name=”Phonenum” form=”form1″>

</body>

</html>

<input> form related Attribute

 <form action=”demo_form.asp”>

<input type=”submit” formaction=”form2.asp” formenctype=”multipart/form-data” formmethod=”post” formtarget=”_blank” value=”Submit to form2″>

<input type=”submit” value=”Save 2″ formtarget=”_self”/>

</form>

formenctype :-

 The formenctype attribute can force a form to submit the data in the specified encoding rather than the encoding specified in the form element when submitted as “post”.

Valid as an attribute of elements that can submit a form, including <input type=submit> and <input type=image> and <button>.

Possible values include

the default of “application/x-www-form-urlencoded” which encodes special chars in the URL to ASCII HEX values and spaces to ‘+’,

no encoding with multipart/form-data, and

text/plain which only converts spaces to +, and leaves other characters as is.

height and width:

Similar to the <img> element, the height, width, src, and alt attributes define the height, width, source and alterative text of the image button.

<input type=”image” src=”img_submit.gif” alt=”Submit” width=”48″ height=”48″>

multiple Attribute:We can take our lists and datalists one step further by applying the Boolean attribute multiple to allow more than one value to be entered from the datalist

<form action=”form1.asp”>

Select multiple files to upload: <input type=”file” name=”file” multiple>

<input type=”submit”>

</form>

Step by step procedure Implementing about JavaScript Timer

Timer Demo:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<title>Validation On Submit</title>

<script language=”JavaScript”>

function showClientTime() {

var dt = new Date()

spnTime.innerHTML = dt.toLocaleTimeString();

setTimeout(“showClientTime ()”, 1000);

}

</script>

</head>

<body onload=”showClientTime()”>

<span id=”spnTime”></span>

</body>

</html>

To show and close window:

<script type=”text/JavaScript”>

var win;

function ShowWindow() {

win = window.open(“JS1.htm”, “win1”, “menubar=no,scrollbars=no,width=400,height=500,location=no,resizable=yes”)

}

function CloseWindow() {

win.close();

}

</script>

ShowTime.js:

Code for displaying time

document.write(“<span id=’spnTime’></span>”)

function setClientTime() {

document.getElementById(“spnTime”).innerHTML = new Date().toTimeString();

setTimeout(“setClientTime()”, 1000)

}

setClientTime()

In any HTML Page, add the following to show System time:

<script type=”text/JavaScript” src=”ShowTime.js”></script>