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 in any folder.

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

Command to Compile: javac
Command to execute: java MyFirstClass

C:\Documents and Settings\admin\Desktop>javac

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.

About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

Some of the video tutorials on Udemy I would recommend are;

Join our email newsletter to get promo codes for almost 90% discount on these courses, and yes you will get a lot of free eBooks too, absolutely Free.

Leave a Reply

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

Subscribe to JournalDev Newsletter
Get the FREE access to JournalDev Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.