Begin: Hello Word in Java

HelloJava
In the tradition of introductory programming texts, we are going to begin with Java’s equivalent of the archetypical “Hello World” application, HelloJava.
It will be taking four passes at this instance before we’re done (Hello World, Hello Java , etc.), adding options and introducing new ideas on the way. however let’s begin with the minimalist version

       
public class HelloJava {
public static void main( String[] args ) {
System.out.println("Hello, Java!");
}
}

This five-line program declares a class known as HelloJava and a method known as main() . It uses a predefined method known as println() to put in writing some text as output. this can be a command-line program, which implies that it runs in an exceedingly shell or DOS window and prints its output there. That’s a small amount old-school for our style, thus before we tend to go to any extent further, we’re attending to offer HelloJava a graphical user interface (GUI). Don’t worry regarding the code yet; simply follow at the side of the progression here, and we’ll return for explanations in an exceedinglymoment.

In place of code lines containing the println() method, we’re goingto use a JFrame object to place a window on the screen. we will begin by replacing the println line with the subsequent 3 lines:
       
JFrame frame = new JFrame( "Hello, Java!" );

frame.setSize( 300, 300 );

frame.setVisible( true );

This snippet creates a JFrame object with the title “Hello, Java!” The JFrame will be graphical window. to display this, we have to define its size on the screen by using the predefined method called setSize() and create it visible by calling another method setVisible().


Now from here we’d see an empty window on the screen with the “Hello, Java!” banner as its title. We would like our message inside the window, not just scrawled at the top of it. To put something in the window, we need a couple more lines to our codes. The following complete example adds a JLabel object to display the text centered in our window. The additional import line at the top is necessary to tell Java where to locate the JFrame and JLabel classes (by definitioning the JFrame and JLabel objects that we’re using).
       
import javax.swing.*;

public class HelloJava {

public static void main( String[] args ) {

JFrame frame = new JFrame( "Hello, Java!" );

JLabel label = new JLabel("Hello, Java!", JLabel.CENTER );

frame.add(label);

frame.setSize( 300, 300 );

frame.setVisible( true );

}
}

Now to compile and run this source Codes.
Keep visiting for more tips on java programming

Leave a Reply

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