Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java Application: First program in Java

java java application

  • Please log in to reply
1 reply to this topic

#1 mdebnath

mdebnath

    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 16 February 2013 - 09:32 PM

Since we have setup the environment for Java programming let's introduce Java application programming facilitating a disciplined  approach to program design. Most programs you will come across generally do three primary things – get the input, process the information and display the result. Here in this article we shall discuss with examples that demonstrate how your program can display messages and how they can obtain information from the user for processing.
 
First Program
 
Let us consider a simple application that displays a line of text
 

//simple text printing program
//file name: MyClass.java

package mypackage;

/*
* In Java everything is written within a class and the 
* filename and class name remains the same, in this case 
* MyClass.java 
*/
public class MyClass 
{    
    //main method begins execution of Java application
    public static void main(String[] args) // args refers to arguments accepted by main function 
    {        
        System.out.println("My first Java program");        
    }//end of main method    
}//end of class MyClass
 

 
Let us now consider each line of the program in order.
 
Comments
 
The program begins with //, indicating that the remainder of the line is a comment. Programmers insert comments to document programs and improve their readability. This helps other people to read and understand programs. The java compiler ignores comments, so they do not cause the computer to perform any action when the program runs. There are two way comments are inserted in Java code: one is called single line comment represented by // i.e. comment terminates at the end of line. Another is multiple line comment represented by /* */. This type of comments begin with the delimiter /* and ends with */. Also there is another type of comments called javadoc comment that are delimited by /** and */. These type of comments are used to embed program documentation directly in the program and preferred Java commenting format in the industry, but the basic idea is same for all formats of comment.

Package

The declaration package mypackage indicates a user defined package. Placing a package declaration at the beginning of a Java source file indicates that the class declared in the file is a part of the specified package.
 
User defined class
 
The declaration of class MyClass is the user defined class defined by you. Every program in Java consists of at least one such class declaration. The class is a keyword which introduces class declaration in Java and is immediately followed by the class name (here,  MyClass). Class name is an identifier consisting of letters, digits, underscores(_), dollar signs($) but cannot begin with digit and does not contain spaces.
 
Note: Keywords are nothing but reserved words used by Java. Java is case sensitive i.e. b2 and B2 are different. By convention, in Java all class names begin with capital letter and capitalize the first letter of each word they include. Also observe that each statement is delimited by a semicolon ';' to signify the end of a statement in Java, failure to indicate one is a compile time error.

Braces

A left brace, {, begins the body of a class, function, loops, conditional statement etc. And the corresponding ,}, end the body. There should always be a matching pair of braces.
 
Method

 
The parenthesis, (), after the identifier main indicate that it is a program building block called method. A Java class declaration normally contain one or more methods. For a Java Application there must be one main method otherwise the JVM will not start the execution. The main method is the starting point of a Java Application. Methods are like verbs in a sentence. It takes some information, process it and return information when they complete their task.

 
Standard object and method
 
System.out is known as standard output object. Method System.out.println displays a line of text in the console window. When it completes its task, it positions the output cursor to the beginning of the next line in the console. There are several variations of this method.
 

System.out.print("My first Java program"); 
 

 
This will print the text and the cursor will be at the end of the line.
 

System.out.println("My first Java program"); 
 

This will print the text and the cursor will be at the beginning of the next line

System.out.print("My first Java program\n"); 
 

 
This will print the text and the cursor will be at the beginning of the next line due to '\n'
 

System.out.printf("My first Java program"); 
 

 
print the text and the cursor will be at the end of the line, a formatted print function. We shall see more of this function later down the line.
 
Second Program
 
Let's modify our first program and try to print same text with similar formatted output with different print function
 
 

//simple text printing program
//file name: MyClass.java 

package mypackage;

/*
* In Java everything is written within a class and the 
* filename and class name remains the same, in this case 
* MyClass.java
* */

public class MyClass 
{    
    // main method begins execution of Java application
    
    public static void main(String[] args) 
    {        
        //with println function
        System.out.println("Using println function");
        System.out.println("Hello World");
        System.out.println("Welcome to the world of Java");
        // with print function
        System.out.print("Using print function\n");
        System.out.print("Hello World\n");
        System.out.print("Welcome to the world of Java\n");
        // with printf function
        System.out.print("Using printf function\n");
        System.out.printf("Hello World\n");
        System.out.printf("Welcome to the world of Java\n");
    }//end of main method
}//end of class MyClass
 

Escape sequence
The \n used in the above programs is called an escape sequence. There are several escape sequences in Java as follows

  • \n    Newline. Position the screen cursor at the beginning of the nextline.
  • \t    Horizontal tab. Move the screen cursor to the next tab stop.
  • \r    Carriage return. Position the screen cursor at the beginning of the current line and do not advance to the next line. Any character written after the carriage return overwrites the character previously output on that line.
  • \\    Backslash, used to print backslash '\' character (imagine, how will you print \ in the output without double backslash, \\)
  • \”    Double quote, used to print double quote. Imagine how to print exactly this line – Teacher says, “Very Good”.

Third Program

Let's write a program to input two numbers from the user, add them up and show the result.
 

package mymath;
import java.util.Scanner;
public class SimpleMath {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a;
        int b;
        int sum;
        System.out.print("Enter first number: ");
        a = input.nextInt();
        System.out.print("Enter second number: ");
        b = input.nextInt();
        sum = a + b;
        System.out.printf("Sum is %d\n", sum);
    }
}

 
Here,
 

import java.util.Scanner
 

is an import declaration that helps the compiler locate a class that is used in this program. A great strength of Java is its rich set of predefined classes that programmers can reuse rather than invent themselves. These classes are grouped into packages – named collection of classes. These packages are collectively referred to as Java class library or the Java API (Application Program Interface). Programmers use import declarations to identify the predefined classes used in a Java program. In the above program import declaration indicates that this example uses Java's predefined Scanner class from package java.util.
 

Scanner input = new Scanner(System.in);
 

is a variable declaration statement that specifies the type and name of a variable (input) that is used in this program. A variable is a location in the computer's memory where values can be stored for use later in the program. All variables must be declared with a  name and a type before they are used. A Scanner is a built in Java class that enables a program to read data for use in a program and initialize the input variable with equal sign (=). The expression new Scanner(System.in) creates a Scanner object that reads data typed by the user at the keyboard. System.in is a standard input object (Similarly, System.out is a standard output  object) that enables Java application to read information typed by the user. 
 
 

   int a;
   int b;
   int sum;
 

 
these variables will hold integers values and are of primitive data type int. Other such primitive data types are – boolean, byte, short, char, long, float and double. We shall see their usages in other programs down the line.The primitive data types start with lower case letter, unlike all other classes in Java which start with capital one (like Scanner)
 

sum = a + b;
 

 
Here values contained in a and in b are added through + operator and assigned to the variable sum.
 
Arithmetic operators
 
table1.jpg
 
 
Relational Operators
 
table2.jpg
 

System.out.printf("Sum is %d\n", sum);
 

 
The format specifier %d is a place holder for an int value - the letter d indicates decimal integer
 
 Quizzes

 1. Which one is a standard input object
(1) System.out
(2) println
(3) System.in
(4) printf

 2. Which one is a standard output object
(1) System.out
(2) println
(3) System.in
(4) printf

 3. The method from which Java program starts is called
(1) class
(2) main
(3) printf
(4) None of the above

 4. which of the following is a primitive data type
(1) int
(2) float
(3) char
(4) All of the above

 5. Which package contains Scanner object
(1) java.util
(2) java.io
(3) java.net
(4) java.sql

 6. Which of the following is a valid comment
(1) /* ...*/
(2) /**... */
(3) //...
(4) All of the above

 7. Which of the following is not a valid variable declaration
(1) int 67val
(2) double char99
(3) char b23$
(4) boolean _11;

 8. Java considers variables number and NuMbEr to be same
(1) True
(2) False
(3) Most of the time true
(4) Sometimes false

 9. Every statement ends with
(1) =
(2) }
(3) )
(4) ;

 10. ________ are reserved for use by Java
(1) methods
(2) Packages
(3) Keywords
(4) All of the above

 11. Parenthesis and braces always need to balance in Java code
(1) True
(2) False

 12. The predefined classes of Java are called
(1) Packages
(2) Methods
(3) Java API
(4) User defined classes


Spoiler



Tasks: Try yourself

  • Write a application that asks the user to enter two integers, obtain them from the user and prints their sum, product, difference and quotient.
  • Write an application that inputs three integers from the user and displays the average.

 
 
Previous: Introduction to Java | Next: Control statements | Back to Table of content


Edited by mdebnath, 08 March 2013 - 01:27 AM.

  • 0

#2 XB23

XB23

    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 03 July 2014 - 03:44 PM

\r    Carriage return. Position the screen cursor at the beginning of the current line and do not advance to the next line. Any character written after the carriage return overwrites the character previously output on that line.

This didn't work for me.


  • 0





Also tagged with one or more of these keywords: java, java application