Print Page Print Page

Ch1 – Displaying Strings

    1. Create a new file named Hello2.java.
    2. Add two println statements to the main method.
    public class Hello2 {
      public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("How are you?");
      }
    }
    
    1. Save the file, then compile it using javac.
    javac Hello2.java
    1. Run the file from the command line by typing java Hello2.
    $ java Hello2
    Hello, World!
    How are you?
    
    1. Open the program in your editor and add two comments as follows.
    public class Hello2 {
      public static void main(String[] args) {
        System.out.println("Hello, World!"); //first line
        System.out.println("How are you?"); //second line
      }
    }
    
    1. Save, compile, and run the program.

     

  1. Note that comments were not printed. Comments can go on either their own line or at the end of lines containing code.
    1. In a new file named Goodbye.java, create a new class named Goodbye.
    2. Create a new main method and add the following code.
    public class Goodbye {
      public static void main(String[] args){
        System.out.print("Goodbye, ");
        System.out.println("cruel world.");
      }
    }
    
    1. Compile and run the program.
    $ javac Goodbye.java
    $ java Goodbye
    Goodbye, cruel world.
    

    Note that if you instead see the following output,

    $ java Goodbye
    Goodbye, 
    cruel world.

    you most likely typed

    System.out.println("Goodbye, ");

    rather than

    System.out.print("Goodbye, ");

    which erroneously added a newline to the statement.