Java Tutorial 2 – Writing and Running First Java Program

In the last article, we saw how to setup Java environment on Windows, now we are ready to write and run our first java program.

To keep things simple and working for newbie, here is the sample program that you can use.

public class MyFirstClass {

	public static void main(String args[]){
		System.out.println("Welcome to JournalDev.");
	}
}

Save above program as MyFirstClass.java in any folder.

Open Command Prompt and go to the directory where this file is saved.

Command to Compile: javac MyFirstClass.java
Command to execute: java MyFirstClass


C:\Documents and Settings\admin\Desktop>javac MyFirstClass.java

C:\Documents and Settings\admin\Desktop>java MyFirstClass
Welcome to JournalDev.

Few Pointers:
1. Any java code can have multiple classes but can have only one public class.
2. The java code file name should be same as public class name.
3. When we compile the code, it generates byte code and save it as .class extension
4. When we execute the class file, we don’t need to provide full file name. We need to use only the public class name.
5. When we run the program using java command, it loads the class into JVM and looks for main function in the class and runs it. The main function syntax should be same as specified else it won’t run and throw exception as “Exception in thread “main” java.lang.NoSuchMethodError: main”.

That’s all for this post and you can start playing with your first class. In next post, I will get into further details of classes, JDK, JVM and other features provided by java language.

Update: Read this post to know about JDK vs JRE vs JVM in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Limited Time Offer: Hadoop PDF eBook Free Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now