Click here to close now.




















Welcome!

Java IoT Authors: VictorOps Blog, Liz McMillan, Elizabeth White, Mike Kavis, Pat Romanski

Related Topics: Java IoT

Java IoT: Article

Your First Java Program

Lesson 1: Hello World

Getting Started

The Java Development Kit (JDK) could be downloaded from the Sun Microsystems' Internet site at http://java.sun.com/j2se/1.4/ .

The installation process is pretty simple - just run the downloaded executable file and it'll install it on your disk (the default directory for Java under Microsoft Windows is  c:\j2sdk1.4).

To start writing a Java program you could use any plain text editor. In Windows, it could be an editor called Notepad. In UNIX, it could be the vi editor. The files with Java programs must be saved in a plain text format and must have names ending in .java.  For example, if you want to write a program called HelloWorld, enter its code in Notepad and save it in a class named HelloWorld.java.

Keep in mind that Java is a case sensitive language, which means that if you named the program HelloWorld with a capital H and a capital W, do not try to start the program helloworld.

Here is the infamous program that prints the words Hello World on the screen:

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


Now you need to compile this program. We'll be using the  javac compiler, which is a part of JDK.
 
Let's say you've saved your program in the directory called  c:\practice. Open a command window, change the current directory to c:\practice and compile the program:

c:\>cd \practice

c:\practice>javac HelloWorld.java

If your environment is set properly and your program does not have syntax errors, it will create a new file called HelloWorld.class in the same directory.

If an error message is displayed  saying something  like "javac  is not found", or "bad command/file name" make sure that the directory  c:\j2sdk1.4\bin  is  included to the  search path of your environment.    

- If you are using Windows 98, open the file c:\autoexec.bat
        and add  the directory where your JDK is installed to the environment
        variable PATH, for example 
 
        c:\j2sdk1.4\bin;   

-  In Windows 2000 or XP set the PATH using the menu Settings |
         Control  Panel | System | Environment Variables. 

- In Unix - add it to the shell's PATH environment variable.

You  won't see any confirmation of a successful compilation, just type dir in Windows or ls in Unix, and a new file named HelloWorld.class has to be there. This  proves that your program has been successfully compiled.

If the program has some syntax errors, the compiler will print error messages. In this case you'd need to fix the errors, and recompile the program again. You may need to do it more than once until the file HelloWorld.class is created.

Now let's run the program -  enter the following command:

c:\practice> java HelloWorld

Please note that we do not start  javac, but java , which is called the Java run-time environment or the Java Virtual Machine (JVM).

This time the error message may say that the HelloWorld.class is not found.   Even though you  have the .class file in the same directory as your .java file, JVM is not going to look for it in the current directory unless the current directory is listed in the so-called CLASSPATH variable. Don't confuse this with the variable  PATH, that's been discussed  earlier. 

The variable  CLASSPATH variable is used by the JVM to find compiled classes.  Let's do a procedure similar to what you've done with the PATH.

For example, in Windows 98, open the file autoexec.bat and add the following line to it:

set CLASSPATH=.;

The dot above represents the current directory. If you already had the CLASSPATH variables set in your machine, just add the dot and semicolon to the end of its value.

Give  your Java class and its file the same name.  There could be exceptions to this rule, but not in this simple program.

While writing Java programs, you create classes which represent objects from real life. You'll learn more about classes in the lesson called "Introduction to Object-Oriented Programming in Java".

Our HelloWorld program is also a class and it contains a  method main(). Methods in Java classes represent actions that the class could perform.  The method main() calls the method println() to display the text "Hello World" on the screen.

Here is the method signature of the method main():

public static void main(String[] args)

The method signature includes the access level - public, instructions on usage - static, return value type - void, name of the method - main, and the argument list -  String[] args.

The keyword public means that the method main() could be accessed by any other Java class. The keyword static means that you don't have to create an instance of  this class to use this method. The keyword void says that the method main() doesn't return any value to the calling program.

The keyword Stirng[] args  tells us that this method will receive an array of Strings as the argument (some values could be passed to this method from a command line).

The main() method is the starting point of your program. You can have a program that consists of more that one class, but at least one of them usually has the method main(), otherwise the program will not start. A Java class can have more than one method. For example, a class Employee can have the methods  updateAddress(), raiseSalary(),changeName(), etc.

The body of the method  main()contains the following  line :

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

The println() is a method that is used to print data on the system console (command window). Java's method names are always followed by parentheses.

System and out are not methods, but names that represent other Java classes.

System.out means that the  variable out is defined inside the class System.

The out.println() tells us that there is an object represented by a variable called  out  and it has  a method called println().

We will be using this so-called dot notation to access class methods or variables. Say you have a class Employee that has a method changeAddress().  Here is an example:

Employee.changeAddress("25 Broadway")

Let's review the steps you would perform to create and run the HelloWorld program:

Step 1. Set the  values for the PATH and CLASSPATH system variables.

Step 2. Create a new directory called practice.

Step 3. Using a text editor, enter the code of the class 
             HelloWorld  and save it in the file  
             c:\practice\HelloWorld.java. 

Step 4.  Compile and run the program:
 
             c:\practice> javac HelloWorld.java
             c:\practice> java HelloWorld


Assignment. Write a program to print your address using  more than one statement println().

More Stories By Yakov Fain

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

Comments (4) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Peter Sweet 04/23/04 11:53:44 AM EDT

This is good stuff. The explanation of what PATH and CLASSPATH do was useful.

Andrey Postoyanets 11/19/03 11:42:21 AM EST

As a Java programmer in a college IT department, I''ve worked with quite a few college interns (and also have been approached by fellow co-workers who want to try Java.) They would usually take a college-level Java course or try self-study, but are quite scared to start on their own. Thus, the usual question is "What should I do first?" Many of them expect some magic IDE and are quite surprised with an answer that a pure Notepad would be enough :)
This lesson (and the series as a whole) would provide an invaluable help to the students and guide them step-by-step into the Java world. It contains examples which are easy to follow and understand. Such useful approach can make more people say "Hey, I can do this! Let me try further..." and attract new developers into our community.

Yakov FaAin 11/18/03 04:25:54 PM EST

Hi J.D,

I agree with you, object-oriented nature is important. But if I start with explaining OOP to people with different backgrounds, I''ll lose a half of my students right away. Guess what? I usually do this on the lesson #2 :)

Regards,
Yakov Fain

J.D. Baker 11/18/03 11:53:06 AM EST

What''s here is ok, but it ignores the object-oriented nature of the Java programming language. IMHO, the proper approach to Hello World in Java is a version published by Shengyang Shong (I forget where). This version of Hello World had a class with a main called SayHello that instantiated a Mouth that had a say() method that printed "hello". This example can be expanded, introducing constructors for the Mouth and overloaded say() methods.

J.D.

@ThingsExpo Stories
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
For IoT to grow as quickly as analyst firms’ project, a lot is going to fall on developers to quickly bring applications to market. But the lack of a standard development platform threatens to slow growth and make application development more time consuming and costly, much like we’ve seen in the mobile space. In his session at @ThingsExpo, Mike Weiner, Product Manager of the Omega DevCloud with KORE Telematics Inc., discussed the evolving requirements for developers as IoT matures and conducted a live demonstration of how quickly application development can happen when the need to comply wit...
The Internet of Everything (IoE) brings together people, process, data and things to make networked connections more relevant and valuable than ever before – transforming information into knowledge and knowledge into wisdom. IoE creates new capabilities, richer experiences, and unprecedented opportunities to improve business and government operations, decision making and mission support capabilities.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Architect for the Internet of Things and Intelligent Systems, described how to revolutionize your archit...
MuleSoft has announced the findings of its 2015 Connectivity Benchmark Report on the adoption and business impact of APIs. The findings suggest traditional businesses are quickly evolving into "composable enterprises" built out of hundreds of connected software services, applications and devices. Most are embracing the Internet of Things (IoT) and microservices technologies like Docker. A majority are integrating wearables, like smart watches, and more than half plan to generate revenue with APIs within the next year.
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Opening Keynote at 16th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, d...
In his keynote at 16th Cloud Expo, Rodney Rogers, CEO of Virtustream, discussed the evolution of the company from inception to its recent acquisition by EMC – including personal insights, lessons learned (and some WTF moments) along the way. Learn how Virtustream’s unique approach of combining the economics and elasticity of the consumer cloud model with proper performance, application automation and security into a platform became a breakout success with enterprise customers and a natural fit for the EMC Federation.
The Internet of Things is not only adding billions of sensors and billions of terabytes to the Internet. It is also forcing a fundamental change in the way we envision Information Technology. For the first time, more data is being created by devices at the edge of the Internet rather than from centralized systems. What does this mean for today's IT professional? In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists addressed this very serious issue of profound change in the industry.
Discussions about cloud computing are evolving into discussions about enterprise IT in general. As enterprises increasingly migrate toward their own unique clouds, new issues such as the use of containers and microservices emerge to keep things interesting. In this Power Panel at 16th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the state of cloud computing today, and what enterprise IT professionals need to know about how the latest topics and trends affect their organization.
It is one thing to build single industrial IoT applications, but what will it take to build the Smart Cities and truly society-changing applications of the future? The technology won’t be the problem, it will be the number of parties that need to work together and be aligned in their motivation to succeed. In his session at @ThingsExpo, Jason Mondanaro, Director, Product Management at Metanga, discussed how you can plan to cooperate, partner, and form lasting all-star teams to change the world and it starts with business models and monetization strategies.
Converging digital disruptions is creating a major sea change - Cisco calls this the Internet of Everything (IoE). IoE is the network connection of People, Process, Data and Things, fueled by Cloud, Mobile, Social, Analytics and Security, and it represents a $19Trillion value-at-stake over the next 10 years. In her keynote at @ThingsExpo, Manjula Talreja, VP of Cisco Consulting Services, discussed IoE and the enormous opportunities it provides to public and private firms alike. She will share what businesses must do to thrive in the IoE economy, citing examples from several industry sectors.
There will be 150 billion connected devices by 2020. New digital businesses have already disrupted value chains across every industry. APIs are at the center of the digital business. You need to understand what assets you have that can be exposed digitally, what their digital value chain is, and how to create an effective business model around that value chain to compete in this economy. No enterprise can be complacent and not engage in the digital economy. Learn how to be the disruptor and not the disruptee.
Akana has released Envision, an enhanced API analytics platform that helps enterprises mine critical insights across their digital eco-systems, understand their customers and partners and offer value-added personalized services. “In today’s digital economy, data-driven insights are proving to be a key differentiator for businesses. Understanding the data that is being tunneled through their APIs and how it can be used to optimize their business and operations is of paramount importance,” said Alistair Farquharson, CTO of Akana.
Business as usual for IT is evolving into a "Make or Buy" decision on a service-by-service conversation with input from the LOBs. How does your organization move forward with cloud? In his general session at 16th Cloud Expo, Paul Maravei, Regional Sales Manager, Hybrid Cloud and Managed Services at Cisco, discusses how Cisco and its partners offer a market-leading portfolio and ecosystem of cloud infrastructure and application services that allow you to uniquely and securely combine cloud business applications and services across multiple cloud delivery models.
The enterprise market will drive IoT device adoption over the next five years. In his session at @ThingsExpo, John Greenough, an analyst at BI Intelligence, division of Business Insider, analyzed how companies will adopt IoT products and the associated cost of adopting those products. John Greenough is the lead analyst covering the Internet of Things for BI Intelligence- Business Insider’s paid research service. Numerous IoT companies have cited his analysis of the IoT. Prior to joining BI Intelligence, he worked analyzing bank technology for Corporate Insight and The Clearing House Payment...
"Optimal Design is a technology integration and product development firm that specializes in connecting devices to the cloud," stated Joe Wascow, Co-Founder & CMO of Optimal Design, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.
SYS-CON Events announced today that CommVault has been named “Bronze Sponsor” of SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. A singular vision – a belief in a better way to address current and future data management needs – guides CommVault in the development of Singular Information Management® solutions for high-performance data protection, universal availability and simplified management of data on complex storage networks. CommVault's exclusive single-platform architecture gives companies unp...
Electric Cloud and Arynga have announced a product integration partnership that will bring Continuous Delivery solutions to the automotive Internet-of-Things (IoT) market. The joint solution will help automotive manufacturers, OEMs and system integrators adopt DevOps automation and Continuous Delivery practices that reduce software build and release cycle times within the complex and specific parameters of embedded and IoT software systems.
"ciqada is a combined platform of hardware modules and server products that lets people take their existing devices or new devices and lets them be accessible over the Internet for their users," noted Geoff Engelstein of ciqada, a division of Mars International, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.
Internet of Things is moving from being a hype to a reality. Experts estimate that internet connected cars will grow to 152 million, while over 100 million internet connected wireless light bulbs and lamps will be operational by 2020. These and many other intriguing statistics highlight the importance of Internet powered devices and how market penetration is going to multiply many times over in the next few years.