Site icon TestingDocs.com

Java Programs Practice

Overview

In this series, we will practice basic Java programs in Java like printing to a standard console. Run the program and observe the program output.

Problem Statement

We will print two lines of output in the program:

Print Hello, World.
System.out.println(“Hello, World.”);

Program Output

Sample Output of the Program

Hello, World!

TIP

Try to solve the program in your favorite IDE like Eclipse, IntelliJ etc. Practicing programs in IDE is a good way to start learning automation. In real-time experience, you would need to develop automation scripts and code using IDE. If you are new to eclipse, the following post would help you. ( Working with Eclipse – Basics  ) . Furthermore, this way you will get familiar with the IDE interface and frequently used operations in the IDE like creating classes, package, running the code, debugging, etc.

 

Code Snippet

package com.testingdocs.javaautomation;

public class Day1 {

   public static void main(String[] args) {
        /* Print output */
        System.out.println("Hello, World!");
      
    }
}

 

Output

Hello, World!

 

 

Now we will tweak the problem statement to read from stdin and print the same to stdout. Lets us look at how we can achieve that in the following code snippet:

We will use the Scanner class for this purpose. The Scanner is a simple text scanner that can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

For example, the code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

 

import java.util.Scanner;

public class Day1 {

   public static void main(String[] args) {
     
  Scanner scan = new Scanner(System.in); 
  // Read a line 
  String input = scan.nextLine(); 
  // Close the scanner object
  scan.close(); 
  // Print 
  System.out.println("Input Message was : " + input);
        
   }
}

 

 

Input and Output of the program

Hi there , Welcome to Java Automation Practice
Input Message was : Hi there , Welcome to Java Automation Practice

 

We encourage you to practice building small Java classes and learn Java concepts.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version