3 Ways to Write Your First Java Program

Table of contents:

3 Ways to Write Your First Java Program
3 Ways to Write Your First Java Program
Anonim

Java is an object-oriented programming language, this means that in Java everything is represented through the use of 'Objects' consisting of 'fields' (fields are attributes that describe the object) and 'methods' (methods represent the actions that an object can perform). Java is a 'multi-platform' programming language, which means that a program written in Java can run, without modification, on any hardware architecture that can host a Java Virtual Machine (JVM). Java is a very detailed programming language, which makes it very easy for a beginner to learn and understand. This tutorial is an introduction to writing a program in Java.

Steps

Method 1 of 3: Write the First Program in Java

91968 1
91968 1

Step 1. In order to start writing a program in Java, we first need to create and configure our work environment

Many programmers use 'Integrated Development Environments' (IDEs), such as 'Eclipse' and 'Netbeans', to create their Java programs. Nevertheless, a Java program can be written and compiled without having to resort to using these tools.

91968 2
91968 2

Step 2. Any text editor, such as 'Notepad', is sufficient for writing a program in Java

Sometimes more experienced programmers prefer to use text editors, such as 'vim' and 'emacs', included in the 'Terminal' windows. A very efficient text editor, installable in both Windows and Linux environments, is 'Sublime Text', which is also the tool we will use in this tutorial.

91968 3
91968 3

Step 3. Make sure you have the Java Software Development Kit installed on your computer

You will need this tool to compile the code of your program.

On Windows based systems, if the 'Environment Variables' are not set correctly, the 'javac' command generates an error. Please refer to the Java Software Development Kit installation guide for more details on configuring the JDK in order to avoid similar errors

Method 2 of 3: 'Hello World' program

91968 4
91968 4

Step 1. We are going to create a program that will display the phrase 'Hello World' on the screen

From your text editor, create a new file and save it with the following name: 'HelloWorld.java' (without quotes). 'Hello World' will also be the name you need to assign to your program class. Remember that the name of the file and the main class of the program (the one that contains the 'main' method) must be the same.

91968 5
91968 5

Step 2. Declare your class and your 'main' method

The 'main' method declared with the following code

public static void main (String args)

is the first method that will be invoked during program execution. The 'main' method has the same declaration system in all Java programs.

public class HelloWorld {public static void main (String args) {}}

91968 6
91968 6

Step 3. Create the line of code that will print 'Hello World' on the screen

System.out.println ("Hello World.");

  • Let's take a closer look at the components of this line of code:

    • System

    • indicates that the system will need to perform an action.
    • out

    • specifies that the action will affect something that will be displayed or printed.
    • println

    • is short for 'print line', which tells the output system to 'print' a line.
    • The parentheses that enclose

      ("Hello World.")

      indicate that the

      System.out.println ()

      has some input parameters. In our specific case it is a single parameter of type 'String'

      "Hello World."

  • Note: There are several rules in Java that we must follow:

    • You will always need to add a semicolon (;) at the end of each line of code.
    • Java is a 'case sensitive' language therefore, when you write the names of methods, variables and classes, you must respect capital and lowercase letters, otherwise an error will be generated when compiling the code.
    • Lines of code unique to a specific method or program structure (while loop, for loop, If, If then else, etc..) must be enclosed in curly brackets.
    91968 7
    91968 7

    Step 4. Incorporate the code seen so far

    Your 'Hello World' program should look like this:

    public class HelloWorld {public static void main (String args) {System.out.println ("Hello World."); }}

    91968 8
    91968 8

    Step 5. Save your file and access a command prompt window, or a 'Terminal' window, to be able to compile the program

    Navigate to the folder where you saved your 'HelloWorld.java' file and type the following command

    javac HelloWorld.java

    . This will tell the Java compiler that you want to compile the 'HelloWorld.java' program. If errors are found during compilation, the compiler will tell you what they are and what they refer to. Otherwise you shouldn't get any kind of message. Looking at the contents of the folder where you saved the 'HelloWorld.java' file, you should locate the 'HelloWorld.class' file. This is the file that the JVM will use to run your program.

    91968 9
    91968 9

    Step 6. Run the code

    Now we can run our program! From the Command Prompt window, or from a 'Terminal' window, type the following command

    java HelloWorld

    . This command will tell the JVM that you want to run the HelloWorld class. As a result you should be able to see the phrase "Hello World." On the screen.

    91968 10
    91968 10

    Step 7. Congratulations you have just created your first program written in Java

    Method 3 of 3: Input and Output

    91968 11
    91968 11

    Step 1. Now we want to extend our Hello World program to be able to receive 'input' from the user

    The Hello World program simply prints a predefined string on the screen, but the interactive part of computer programs consists precisely in the user's ability to enter information. We will now modify the program so that the user can enter their name, after which we will thank them for their help using the entered name.

    91968 12
    91968 12

    Step 2. Import the 'Scanner' class

    In Java we have the possibility to use some native class libraries of the programming language, but to do this it is necessary to 'import' them in advance in our program. One of these libraries is the 'java.util', containing the 'Scanner' object that we will use to be able to read user input. In order to import the 'Scanner' class, we need to add the following line of code at the beginning of our program:

    import java.util. Scanner;

    • This will indicate to our program that it will use the 'Scanner' object contained in the 'java.util' library.
    • If we wanted to have access to all objects in the 'java.util' library we would have to modify the line of code in this way

      import java.util. *;

    • , always inserting it at the beginning of our program.
    91968 13
    91968 13

    Step 3. Within our 'main' method, we need to create a new instance of the 'Scanner' object

    Java is an object-oriented programming language, in which concepts are represented using objects. The 'Scanner' object is an example of an object that has its own fields and methods. In order to use the 'Scanner' class within our program, we need to create a new 'Scanner' object, of which we can then populate the fields and use the methods. To do this we use the following code:

    Scanner userInputScanner = new Scanner (System.in);

    • userInputScanner

    • represents the name of the 'Scanner' object we want to create an instance of. Note: the name of this object is written using the 'Camel Notation' (CamelCase). This is the standard convention used in Java for variable names.
    • We use the operator

      new

      to create a new instance of an object. So, to create a new instance of the 'Scanner' object, we will use the following code

      new Scanner (System.in)

    • The 'Scanner' object has an input parameter that describes the object to be scanned. In our case we will enter as a parameter

      System.in

      . Code

      System.in

    • instructs the program to parse the system input which will be the means by which the user can communicate with the program.
    91968 14
    91968 14

    Step 4. Ask the user to enter the information

    We need to instruct the user to know when to enter the required information into the console. This can be done using the following code

    System.out.print

    or

    System.out.println

    System.out.print ("What is your name?");

    91968 15
    91968 15

    Step 5. Now we need to tell the 'Scanner' object to 'read' the next line that the user will type and store it in a variable

    The 'Scanner' object always stores all information regarding what the user has typed. The following lines of code will instruct the 'Scanner' object to store the information typed by the user within a variable:

    String userInputName = userInputScanner.nextLine ();

    • In Java, the following convention is used to name a method of an object

      objectName.methodName (parameters)

      . With code

      userInputScanner.nextLine ()

      we call our instance of the 'Scanner' object by the name we assigned it, then we execute the call to the method

      nextLine ()

    • which does not include any input parameters.
    • Note: we need to store the next line that will be typed in another object: the 'String' object. We called our object 'String':

      userInputName

    91968 16
    91968 16

    Step 6. Greet the user

    Now that we know the user's name, we can 'print' a personalized greeting on the screen. Remember the code

    System.out.println ("Hello World.");

    that we used in the main class? All the code we have just written will be inserted in our program before that line. We are now able to modify our line of code as follows:

    System.out.println ("Hello" + userInputName + "!");

    • The way we combine the string "Hello", the username and the string "!", Using the code

      "Hello" + userInputName + "!"

    • , it is called string concatenation.
    • What happens here is that we have three distinct strings: "Hello", userInputName and "!". Strings in Java are immutable, which means they cannot be changed. So when we go to concatenate the three strings in question, we are basically creating a fourth that will contain our greetings for the user.
    • Now we can use the obtained string as a parameter for the method

      System.out.println

    91968 17
    91968 17

    Step 7. Collect all the code seen so far and save your program

    Our code should 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 + "!"); }}

    91968 18
    91968 18

    Step 8. Compile and run the program

    From the Command Prompt window, or the 'Terminal' window, type the same commands used to compile and run the first iteration of the 'HelloWorld.java' program. First of all we need to compile our code:

    javac HelloWorld.java

    . Now we can run the program using the following command:

    java HelloWorld

    Advice

    • Object-oriented programming languages have many features specific to their programming paradigm. Below you will find three main features:

      • Encapsulation: this is the ability to restrict access to only certain components of an object. Java uses the following modifiers 'private', 'protected', and 'public' to manage access to data fields and methods.
      • Polymorphism: it is the ability of objects to acquire different identities. In Java, an object can be transformed into another object in order to use its methods.
      • Inheritance- the ability to use the data fields and methods of a class that is in the same hierarchy as the current object.
    • Java is an object-oriented programming language, so it is very useful to delve into the concepts behind object-oriented programming.

Recommended: