Useful Tips

How to write the first Java program

Pin
Send
Share
Send
Send


As you know, Java is one of the most popular programming languages ​​in the world and its knowledge will significantly increase your importance as a programmer. So, you decided to start writing in this language. You will need to install the JDK in order to write and run Java programs. JDK is a set of software developed by Oracle, containing a compiler (javac), a runtime environment (Java Runtime Environment), a standard language library, examples and documentation. After reading this article, you will learn how to install and configure the JDK on your system, what a development environment is and what IDE options exist for Java. You will also write your first Java program.

Create Source File

First you need to write the program text in Java and save it. This will be our source file. To create the source file, any text editor is suitable, for example, the standard Notepad. However, there are other text editors that are more convenient for writing code. You can use for example Notepad ++. This is a free text editor that supports the syntax of most programming languages, including Java.

So, we open the text editor and write the Hello World program code in it, the purpose of which is to display the Hello World message on the screen!

After writing this code, the file must be saved under the name HelloWorld.java.
To do this, in your text editor, select the menu item File-> Save As ... If you use standard Windows Notepad, then in order to save the file with the .java extension, you must select when saving File Type: All Files and enter File Name: HelloWorld.java (Fig 2.1).

If you use Notepad ++ you need to choose File Type: Java source file (* .java)

Be careful! the file should be named exactly as our class is called - HelloWorld. It is also important to be case sensitive. HelloWorld andhelloworld in in this case, these are different words!

Pay also attention to the encoding in which you save the file. Must be selected Ansi . In Notepad ++, the encoding can be set in the Encodings menu.

Method 1 Writing the First Java Program

  1. 1 In order to start writing Java programs, you first need to set up a developer environment for yourself. Many programmers use an Integrated Development Environment, such as Eclipse or Netbeans, but you can create a program without it.
  2. 2 Any program like Notepad will be enough for Java programming. Some programmers prefer to use text editors based on vim and emacs. There is also a fairly good text editor that can be installed on both Windows and Linux (Mac, Ubuntu, etc.) -. We will use it in this review.
  3. 3 You will need it to compile your program.
    • If you have a Windows operating system and your environment of variables does not work correctly, it may throw a javac error on startup. Look at the article on installing the application developer kit for more detailed installation information to resolve the error.

Method 2 Hello World Program

  1. 1 First, we will create a program that will display the inscription Hello World. Create a new file in your text editor and save it as "HelloWorld.java". "HelloWorld" is the name of the class, which must match the name of the file, this is important.
  2. 2 Define the class and main method. The main method public static void main (String [] args) will be applied each time the program starts, and will be installed in each subsequent Java program.

3 Enter the line of code "Hello World."

  • Consider the components of this line of code:
    • System refers to the system and forces it to perform certain actions.
    • Out tells the system that we are going to enter some data
    • Println input line. We tell the system to display the value
    • The brackets around "Hello World" indicate that the System.out.println () method selects this value as a parameter.
  • Take note of a few rules that you must follow when programming in Java:
    • At the end of each line of code you need to put a semicolon
    • Java is case sensitive, so you must write the values ​​of the method, variables, and class name to match it.
    • Blocks of code that relate to a particular method are separated by curly braces.
  • 4 Put everything together. Ultimately, your Hello World program should look like this:

  • 5 Save your file and open a command prompt or terminal to compile the program. Go to the folder where you saved the HelloWorld.java file and enter HelloWorld.java in the Javac (optimizing java compiler). Thus, you will let the compiler know that you want to convert the file. If errors occur in the process, the compiler will notify you of what you did wrong. Ideally, you should not have any notifications from the compiler at all during the file conversion process. If after finishing you look at the folder where the HelloWorld.java file was saved, you should see the HelloWorld file. > Run the program. Finally we got to this point! At a command prompt or terminal, type in java HelloWorld. The virtual machine will understand that you want to run the HelloWorld class. You should see HelloWorld in the console.
  • 7 Congratulations, you created your first Java program.
  • Method 3 Input and Output

    1. 1 Now we need to expand our Hello World program to accommodate user input. In our program, we printed a line that is visible to the user, but in interactive programs, users enter data in applications. Our task is to expand the program so that it can ask the user for a name, and then greet him by name.
    2. 2 Import the Scanner class. Java has built-in libraries that we have access to, but we need to import them. One of these libraries is java.util, which contains the Scanner object, which we need for user input. In order to import this class, we need to add the following line to the source code.

    • This tells the program that we want to use the Scanner object that exists in the java.util package.
    • If we want to access all the objects in the java.util. Library, we just need to import java.util. * At the beginning of the code.
  • 3 You must enter a new variable in the method for the Scanner object. Java is an object-oriented programming language that operates on variables through objects. A scanner is an example of an object that has fields and methods. In order to use the Scanner class, you need to create a new Scanner object, we need to create the corresponding object with which we can fill in the fields. To write this, you must:

    • userInputScanner is the name of the scanner object that we just installed. Take note that the name is written in the "hunchback register". This is a convention for using variable names in Java.
    • We use the new operator in order to create a new instance of the object. In our case, we created a new instance of the Scanner object, specifying new Scanner (System.in) in the code.
    • The Scanner object picks up a parameter that tells the object what to scan. In this case, System.in is a parameter. System.in tells the program that it is necessary to scan the data entered by the user.
  • 4 Next, make it clear to the user the need to enter data into the console. This can be done using the System.out.print or System.out.println command.

    5 Make the Scanner object pick up the next line that the user enters and save it as a variable. Scanner should always collect user input. The following line of code will instruct the Scanner object to recognize the user-written name and save it as a variable:

    What is the Java programming language?

    In 1991, the Green Team, a division of Sun Microsystems led by James Gosling, created a programming language for consumer electronic devices. At that time it was called Oak ("Oak"). Why "Oak"? Just because this tree grew outside the window of Gosling's office.

    The Green Team demonstrated the use of Oak on an interactive TV. But for digital cable television in those years, this technology was too advanced. At the same time, the Internet was gaining popularity, for which the new programming language was best suited.

    After a while, the new language was renamed to Green, and after that - in Java, in honor of coffee from the island of Java. Therefore, the Java logo depicts a coffee mug.

    During the development of Java, C / C ++ was popular, so Gosling made the language syntax similar to C / C ++ and implemented the principle “write once - run anywhere” for it. In 1995, Sun Microsystems released the first official version of Java. And at the same time, it was announced that Java would be part of the Netscape Navigator browser.

    In 2010, Sun Microsystems, along with the Java programming language, was acquired by Oracle.

    Java Version History

    1. June 1991 - the start of the Java programming language project.
    2. JDK 1.0 - January 1996.
    3. JDK 1.1 - February 1997.
    4. J2SE 1.2 - December 1998.
    5. J2SE 1.3 - May 2000.
    6. J2SE 1.4 - February 2002.
    7. J2SE 5.0 - September 2004.
    8. Java SE 6 - December 2006.
    9. Java SE 7 - July 2011.
    10. Java SE 8 - March 18, 2014.
    11. Java SE 9 - September 21, 2017.

    Java - cross-platform language

    Java code written on one platform (i.e. the operating system) can be run unchanged on other platforms.

    To run Java, the Java Virtual Machine (JVM) is used. The JVM processes the byte code, after which the processor processes the code received from the JVM. All virtual machines work the same way, so the same code works the same on all operating systems, which makes Java a cross-platform programming language.

    Object Oriented Programming Language

    There are various programming styles, and one of the most popular is object-oriented programming. With this approach, a complex problem is broken into smaller ones by creating objects. Thanks to what the code can be reused.

    Object-oriented functions are found in many programming languages, including Java, Python, and C ++. If you are serious about programming, an object-oriented approach should be included in your training plan.

    Compiling the source file

    The source file with the program code has been created, now let's move on to compilation. The compiler is designed to compile Java javac, which is part of the JDK package that we installed in the first lesson.

    In order to compile the source file, open the command line. To do this, in the Windows Start menu in the search bar, type cmd and press Enter. After that a command window will open.

    Now in it you need to change the current directory to the one in which our source file is located (for example, C: studyjava ). To do this, enter the following command:

    and press Enter.

    After the directory has changed, enter the compilation command

    After that, the command prompt window should look like this (Figure 2.2):

    That is, we will not receive any confirmation that the program compiled successfully. However, in the folder with our source file, the file should appear HelloWorld.class. This can be verified using the command

    This command displays a list of all files in the selected directory (Fig. 2.3).

    If file HelloWorld.class is present in this list, it means that the program compiled successfully.

    If there is an error in the program code, then the Java compiler will notify us when compiling it.

    Let's run an experiment: Open our file in a text editor HelloWorld.java and delete the last closing curly bracket “>”. Save the file and try to compile it again. As a result, we get an error message (Figure 2.4).

    To fix the error, you need to reopen the file for editing, fix the error, save the file and compile it again.

    Program launch

    We pass to the last stage - launching the program.

    Enter in the command window:

    and if everything before this was done correctly, then we get the result - the output of the message “Hello World!” (Fig. 2.5).

    Pay attention to case sensitivity in Java. If you write helloworld instead of HelloWorldthen the program is running will not be, because Java simply will not find a file with that name.

    As your homework, you can experiment and display your own message instead of Hello World !.

    Of course, for writing, compiling and running Java programs, there is a more convenient tool than Notepad and the command line. This so-called IDE Integrated Processing Environment. We will talk about this in the next lesson.

    Install Java Development Kit

    1. Go to the Oracle website and download the JDK for your platform.
    2. After downloading, extract the resulting archive and run the extracted application.
    3. During the installation, select the “Development Tool” option and click “Next”.
    4. After some time, the installation will complete.

    So you have installed the Java Development Kit, but that is not all. You must configure it for your system.

    Windows JDK setup

    1. Go to the folder% ProgramFiles% Java \% version of the jdk% bin you installed, click on the properties of any file in this folder and copy the path to it.
    2. Go to the properties of your computer, open the "Advanced" tab, click "Environment Variables ...". In the window that opens, create a new variable, name it Path, paste the path you copied earlier into its value.
    3. Now the most important thing. Open a command prompt and type javac to verify that the JRE is installed and configured. If you get a list of arguments to the javac command, then congratulations, you have successfully installed and configured everything you need to use Java!

    After installing the JDK and JRE it will not hurt to install one of the IDEs on the computer.

    IDE Installation

    First, let's figure out what is IDE.

    IDE (Integrated Development Environment) is a set of software tools used by programmers to develop software. The IDE makes it easy to write, run, debug, and test code.

    For writing complex programs, it is advisable to use an IDE. We will consider the most popular.

    Yes, and in a notebook you can write code! For development, you only need to install the JDK and specify the path to it. Write code in notepad, compile using the command line. However, for the development of complex programs, this is not the best option due to the lack of any additional features present in advanced IDEs.

    NetBeans is the choice of professional Java developers. It has unique features and tools that will allow you to make your program cross-platform, and the code readable. NetBeans not only supports Java, but also other programming languages ​​for desktop and web development. It is completely free, you can download it from the official site. Here are just a few of its features:

    • code formatting,
    • installation of third-party libraries,
    • simple graphical interface
    • and many many others…

    Eclipse, like Netbeans, is one of the most popular IDEs. It provides an impressive intuitive interface and a productive development environment that allows you to comfortably develop Java applications. Eclipse can be downloaded for free from the official site. Benefits:

    • the ability to format the code as you like,
    • support for breaking code into modules,
    • ease of use of the same code in different projects,
    • drag-and-drop
    • viewing the contents of libraries,
    • convenient interface.

    IntelliJ IDEA

    IntelliJ IDEA is a well-known IDE for Java, written, oddly enough, in Java. It is equipped with unique tools and allows you to navigate the program without problems. Finding bugs and debugging code has never been so easy as with IntelliJ IDEA.

    JCreator is the advanced and fastest Java IDE written in C ++.

    Java is fast

    Early versions of the Java programming language were often criticized for being slow. But today the situation has changed dramatically. Newer versions of the JVM are much faster, and the processors that interpret them are getting faster.

    Today Java is one of the fastest programming languages. Well-optimized Java code runs almost as fast as low-level programming languages ​​such as C / C ++ and much faster than Python, PHP, etc.

    Extensive base library

    One of the reasons Java is so widespread is its huge standard library. In it you can find hundreds of classes and methods from various packages that make life easier for developers. For example,

    java.lang are advanced functions for strings, arrays, etc.

    java.util - a library for working with data structures, regular expressions, date and time, etc.

    kava.io - library for file input / output, exception handling, etc.

    Java platform application

    Before learning Java programming from scratch, you need to know that more than 3 billion devices worldwide work on this platform. What exactly can it be used for:

    1. Android applications - for developing Android applications, the Java programming language is often used in conjunction with the Android SDK (from the English software development kit - software development kit).
    2. Web Applications - Java is used to create network applications using server programs, the Struts framework, and JSP. Here are some popular web applications written in Java: Google.com, Facebook.com, eBay.com, LinkedIn.com.

    It is worth noting that these sites are not necessarily written exclusively in Java, and can use other programming languages.

    1. Разработка программного обеспечения – на Java написаны такие программы как Eclipse , OpenOffice , Vuze , MATLAB и многие другие.
    2. Обработка Big Data – для обработки « больших данных » можно воспользоваться фреймворком Hadoop , написанным на Java .
    3. Трейдинговые системы – используя платформу Oracle Extreme Java Trading Platform , можно писать программы для трейдинга.
    4. Встраиваемые устройства – на основе технологии Java Embedded от Oracle сегодня работают миллиарды устройств, таких как телевизоры, SIM-карты , проигрыватели Blu-ray и т.д.

    Также программирование на Java используется для разработки игр, научных приложений ( к примеру, для обработки естественного языка ) и во многих других областях.

    Терминология Java, которую следует знать

    Java – это набор технологий ( язык программирования и компьютерная платформа ), предназначенных для создания и запуска программного обеспечения. Однако термином Java часто обозначают и сам язык программирования.

    Язык программирования Java – межплатформенный объектно-ориентированный язык программирования общего назначения, обладающий широкими возможностями.

    Java 9 – последняя на момент написания данной статьи версия Java .

    Java EE, Java Me, and Java SE - these names mean Java Enterprise Edition, Micro Edition, and Standard Edition, respectively.

    Java EE targets applications running on servers. Java ME is designed for power-limited devices such as embedded devices. Java SE is the standard Java edition for writing regular programs.

    If you are new to Java programming, we recommend starting with Java SE.

    JVM - Java Virtual Machine ("Java Virtual Machine") is a program that allows a computer to run programs written in Java.

    JRE - The Java Runtime Environment includes the JVM, associated libraries, and other components necessary to run programs. But there is no compiler, debugger, or other development tools in the JRE.

    JDK - The Java Development Kit (Java development kit) contains JRE and other development tools such as compilers, debuggers, etc.

    How to run Java on Mac OS

    Here's what you need to do for Java programming from scratch and install the platform on Mac OS X or macOS:

    1. Download the latest Java version (JDK) from the Java SE download page.
    2. Double-click on the downloaded DMG file and follow the instructions of the installer.
    3. To verify the installation, open a terminal and enter the following command:

    javac –version

    If Java is installed correctly, the version of the program will be displayed on the screen (for example, javac 1.8.0_60).

    The next step is to install an IDE (integrated development environment) for writing and running Java code. We will install the free version of IntelliJ IDEA and run Java on it. Here's what you need to do to do this:

    1. Go to the IntelliJ download page and download the free version of Community Edition.

    1. Open the downloaded DMG file and follow the installation instructions. For quick access, you can move IntelliJ IDEA to the Applications folder.
    2. Open IntelliJ IDEA. Select the “Don’t import settings” option and click “Ok.” After that, accept the Jetbrains privacy policy by clicking on the “Accept” button.
    3. Now you can customize the interface for yourself. You can also skip this step and leave everything as default. If you’re not sure, just skip this step by clicking on the “Skip All and Set Defaults” button.

    1. The program will show you a welcome page. Click on the “Create New Project” button.
    2. In the next window, select “Java” in the left pane and click “New” at the top of the program window to select “JDK”. Here you need to select the place where you installed the JDK, and then click Next.

    1. You will have the option to create a project from a template (“Create project from template”). Ignore it and click on the “Next” button.
    2. In the next step of installing the Java programming language, enter the name of the project and click the "Finish" button.
    3. In the left panel you will see your project. If the panel is not visible, go to Views> Tool Windows> Project.
    4. Go to Hello> New> Java and set the class name. We called it First.

    1. Write Java code and save the project.
    2. To start the program you just wrote, go to Run> Run ... Click on First (that is, the name of the file we created) - the program will compile the file and run it.

    How to run Java on Linux

    To run Java programming examples from scratch Java on Linux, you need the JAVA SE Development Kit (JDK) and IDE to develop your projects. Follow the steps step by step to get started with Java.

      Open a terminal and type the following command to install Java:

    Your first Java program

    To introduce users to the new programming language, use the program Hello World ("Hello world!"). This is a simple program that displays the words Hello, World! In this section, we will teach you how to write this program in Java using IntelliJ IDEA.

    1. Open IntelliJ IDEA.
    2. Go to File> New> Project ...> Java (in the left navigation bar).
    3. Set the Project Name from the J a va programming course. We will call it Hello World and click Finish.
    4. Now you need to create a new Java class.
    5. Select the src folder in the left pane, then go to File> New> Java Class and set the name of the new class to HelloWorld.
    6. Copy the following code into the HelloWorld.java file and save it.

    1. Click the Run button. If everything is in order, you will see Hello, World!

    Recommended Java Books

    If you really want to learn Java programming, buy a good book. Of course, 1000 pages cannot be read in one day. But a good tutorial will help you learn programming.

    Java: The Complete Guide (10th Edition)

    A great book for those who are just starting to learn Java. The latest edition includes all Java 8 release features.

    The book describes everything you need to know about programming in Java, including syntax, keywords and the fundamentals of programming, as well as the Java API library, Java applets and much more.

    Java Philosophy (4th Edition)

    If you are switching to Java from a different programming language, this book is for you. If you start from scratch, it is best to read it along with another.

    Java 8. Pocket Guide: First Aid to Java Programmers

    This book contains clear answers to the questions that arise when learning J ava programming from scratch. She briefly talks about all the basic concepts of Java (including Java 9). Don't want to flip through hundreds of pages looking for the right line? Buy this book.

    Instead of a conclusion

    If you start learning Java, make no mistake - it is a promising programming language full of a wide variety of possibilities.

    Before you start learning Java, use a few tips:

    • Do not read tutorials and examples like a novel. The only way to become a good programmer is to write a lot of code.
    • If you switch from another programming language (say, C #), you do not need to write code in the style of C #.
    • Find online Java communities. When you learn how to write simple Java programs, find popular Java sites and forums. Try to solve problems that other programmers have. This is a great way to expand your own knowledge. In addition, if you have a snag, you will know where to ask for help.

    We hope this article encourages you to learn Java and help you get started with your first programs.

    This publication is a translation of the article “Learn Java Programming. The Definitive Guide ”, prepared by the friendly team of the Internet technology.ru project

    Pin
    Send
    Share
    Send
    Send