159
readers helped!

This helped me

How to Write Your First Program in Java

Java is an object-oriented programming language created in 1995 by James Gosling, which means that it represents concepts as "objects" with "fields" (which are attributes that describe the object) and "methods" (actions that the object can make). Java is a "write once, run anywhere" language, which means that it is designed to run on any platform that has a Java Virtual Machine (JVM). Since Java is a very verbose programming language, it is easy for beginners to learn and understand. This tutorial is an introduction to writing programs in Java.

Part 1
Part 1 of 3:

Finding an IDE

  1. How.com.vn English: Step 1 Set up your work environment.
    Many programmers use Integrated Development Environments (IDEs) such as Eclipse and Netbeans for their Java programming, but one can write a Java program and compile it without bloated IDEs.
  2. How.com.vn English: Step 2 Find a program that will allow you to program in Java.
    Any sort of Notepad-like program will suffice for programming in Java. Hardcore programmers sometimes prefer to use text editors that are within the terminal such as vim and emacs. A very good text editor that can be installed on both a Windows machine and on a linux-based machine (Mac, Ubuntu, etc.) is Sublime Text, which is what we will be using in this tutorial.
    Advertisement
  3. How.com.vn English: Step 3 Make sure that...
    Make sure that you have the Java Software Development Kit installed. You will need this for compiling your program.
    • In a Windows-based operating system, if the environment variables are not correct, you might get an error when running javac. Refer the installation article How to Install the Java Software Development Kit for more details about JDK installation to avoid this error.
    Advertisement
Part 2
Part 2 of 3:

Hello World Program

  1. Step 1 Create a program that prints "Hello World."
    In your text editor, create a new file and save it as "HelloWorld.java". HelloWorld is your class name and you will need your class name to be the same name as your file.
  2. How.com.vn English: Step 2 Declare your class and your main method.
    The main method public static void main(String[] args) is the method that will be executed when the programming is running. This main method will have the same method declaration in every Java program.
    public class HelloWorld {    public static void main(String[] args) {    }}
  3. Step 3 Write the line of code that will print out "Hello World."
    System.out.println("Hello World.");
    • Let's look at the components of this line:
      • System tells the system to do something.
      • out tells the system that we are going to output something to the command line.
      • println stands for "print line," so we are telling the system to print a line in the output.
      • The parentheses around ("Hello World.") mean that the method System.out.println() takes in a parameter, which, in this case, is the String "Hello World."
    • Note that there are some rules in Java that we have to adhere to:
      • You must always add a semicolon at the end of every line.
      • Java is case sensitive, so you must write method names, variable names, and class names in the correct case or you will get an error.
      • Blocks of code specific to a certain method or loop are encased between curly brackets.
  4. How.com.vn English: Step 4 Put it all together.
    Your final Hello World program should look like the following:
    public class HelloWorld {    public static void main(String[] args) {        System.out.println("Hello World.");    }}
  5. How.com.vn English: Step 5 Save your file and open up command prompt or terminal to compile the program.
    Navigate to the folder where you saved HelloWorld.java and type in javac HelloWorld.java. This tells the Java compiler that you want to compile HelloWorld.java. If there are errors, the compiler will tell you what you did wrong. Otherwise, you shouldn't see any messages from the compiler. If you look at the directory where you have HelloWorld.java now, you should see HelloWorld.class. This the the file that Java will use to run your program.
  6. How.com.vn English: Step 6 Run the program.
    Finally, we get to run our program! In command prompt or terminal, type in java HelloWorld. This tells Java that you want to run the class HelloWorld. You should see "Hello World." show up in your console.
  7. How.com.vn English: Step 7 Congratulations, you have made your first Java program!
    Advertisement
Part 3
Part 3 of 3:

Input and Output

  1. How.com.vn English: Step 1 Extend the Hello World program to take input from the user.
    In our Hello World program, we printed out a string for the user to see, but the interactive part of programs is when the user gets to enter input into the program. We will now extend our program to prompt the user for his or her name and then greet the user by his or her name.
  2. How.com.vn English: Step 2 Import the Scanner class.
    In Java, we have some built in libraries that we have access to, but we have to import them. One of these libraries is java.util, which contains the Scanner object that we need to get user input. In order to import the Scanner class, we add the following line to the beginning of our code.
    import java.util.Scanner;
    • This tells our program that we want to use the Scanner object which exists in the package java.util.
    • If we wanted to have access to every object in the java.util package, we simply write import java.util.*; at the beginning of our code.
  3. How.com.vn English: Step 3 Inside our main method, instantiate a new instance of the Scanner object.
    Java is an object-oriented programming language, so it represents concepts using objects. The Scanner object is an example of an object that has fields and methods. In order to use the Scanner class, we have to create a new Scanner object that we can populate the fields of and use the methods of. To do this, we write:
    Scanner userInputScanner = new Scanner(System.in);
    • userInputScanner is the name of the Scanner object that we just instantiated. Note that the name is written in camel case; this is the convention for naming variables in Java.
    • We use the new operator to create a new instance of an object. So, in this instance, we created a new instance of the Scanner object by writing new Scanner(System.in).
    • The Scanner object takes in a parameter that tells the object what to scan. In this case, we put in System.in as a parameter. System.in tells the program to scan the input from the system, which is the input that the user will type into the program.
  4. How.com.vn English: Step 4 Prompt the user for an input.
    We have to prompt the user for an input so that the user knows when to type something into the console. This can be accomplished with a System.out.print or a System.out.println.
    System.out.print("What's your name? ");
  5. How.com.vn English: Step 5 Ask the Scanner object to take in the next line that the user types in and store that in a variable.
    The Scanner will always be taking in data on what the user is typing in. The following line will ask the Scanner to take what the user has typed in for his or her name and store it in a variable:
    String userInputName = userInputScanner.nextLine();
    • In Java, the convention for using an object's method is objectName.methodName(parameters). In userInputScanner.nextLine(), we are calling our Scanner object by the name we just gave it and then we are calling its method nextLine() which does not take in any parameters.
    • Note that we are storing the next line in another object: the String object. We have named our String object userInputName
  6. How.com.vn English: Step 6 Print out a greeting to the user.
    Now that we have the user's name stored, we can print out a greeting to the user. Remember the System.out.println("Hello World."); that we wrote in the main class? All of the code that we just wrote should go above that line. Now we can modify that line to say:
    System.out.println("Hello " + userInputName + "!");
    • The way we chained up "Hello ", the user's name, and "!" by writing "Hello " + userInputName + "!" is called String concatenation.
    • What's happening here is that we have three strings: "Hello ", userInputName, and "!". Strings in Java are immutable, which means that they cannot be changed. So when we are concatenating these three strings, we are essentially created a new string that contains the greeting.
    • Then we take this new string and feed it as a parameter to System.out.println.
  7. How.com.vn English: Step 7 Put it all together and save.
    Our code should now look like this:
    import java.util.Scanner;public class HelloWorld {    public static void main(String[] args) {        Scanner userInputScanner = new Scanner(System.in);        System.out.print("What's your name? ");        String userInputName = userInputScanner.nextLine();        System.out.println("Hello " + userInputName + "!");    }}
  8. How.com.vn English: Step 8 Compile and run.
    Go into command prompt or terminal and run the same commands as we ran for our first iteration of HelloWorld.java. We have to first compile the program: javac HelloWorld.java. Then we can run it: java HelloWorld.
    Advertisement

Community Q&A

Search
Add New Question
  • Question
    How do I write a program to accept a number and then check if it is prime or not prime?
    How.com.vn English: Community Answer
    Community Answer
    Try: import java.io.*;class prime{public static void main(String args[]) throws IOException{int n,i,r,f=0;DataInputStream in=new DataInputStream(Sytem.in);in=Integer.parseInt(in.readLine());for(i=2;i
  • Question
    What is the difference between public and private?
    How.com.vn English: Community Answer
    Community Answer
    Public involves classes, sub-classes, and packages. Private involves only classes and sub-classes.
  • Question
    How can I compile and run a saved Java program?
    How.com.vn English: Community Answer
    Community Answer
    An easy way is to click on the right side of the mouse and a window will pop up, then click run java application.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit

      Advertisement

      Tips

      • Java is an object-oriented programming language, so it's useful to read more on the foundations of object-oriented programming languages. Some languages tend to share characteristics syntax-wise.
      • Object Oriented Programming has many features specific to its paradigm. Three of these main features are:
        • Encapsulation: the ability to restrict access to some of the object's components. Java has private, protected, and public modifiers for fields and methods.
        • Polymorphism: the ability for objects to take on different identities. In Java, an object can be cast into another object to use the other object's methods.
        • Inheritance: the ability to use fields and methods from another class in the same hierarchy as the current object.
      Advertisement

      About this article

      Tested by:
      How.com.vn Technology Team
      How.com.vn is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 84 people, some anonymous, worked to edit and improve it over time. This article has been viewed 1,067,605 times.
      How helpful is this?
      Co-authors: 84
      Updated: December 18, 2023
      Views: 1,067,605
      Thanks to all authors for creating a page that has been read 1,067,605 times.

      Is this article up to date?

      ⚠️ Disclaimer:

      Content from Wiki How English language website. Text is available under the Creative Commons Attribution-Share Alike License; additional terms may apply.
      Wiki How does not encourage the violation of any laws, and cannot be responsible for any violations of such laws, should you link to this domain, or use, reproduce, or republish the information contained herein.

      Notices:
      • - A few of these subjects are frequently censored by educational, governmental, corporate, parental and other filtering schemes.
      • - Some articles may contain names, images, artworks or descriptions of events that some cultures restrict access to
      • - Please note: Wiki How does not give you opinion about the law, or advice about medical. If you need specific advice (for example, medical, legal, financial or risk management), please seek a professional who is licensed or knowledgeable in that area.
      • - Readers should not judge the importance of topics based on their coverage on Wiki How, nor think a topic is important just because it is the subject of a Wiki article.

      Advertisement