How does a Basic Java Program work?

How does a Basic Java Program work?A Java application is a computer program that executes when you use the java command to launch the Java Virtual Machine (JVM).

DammnnBlockedUnblockFollowFollowingMar 5google.

com/imagesLet’s consider a simple program a simple application that displays a line of text.

// simple.

java // this is to print a simple statement public class example { // main method begins execution of Java application.

public static void main (String [] args) { System.


println("This is a simple program"); } // this is where the program ends } // end of the classoutput:This is a simple programWe use line number for instructional purposes- they are not part of a Java program.

The example illustrates several important Java features.

We will see that in line 5 does the work — displaying the phrase “This is a simple program!” on the screen.

COMMENTING on YOUR PROGRAMWe insert comments to documents programs and improve their readability.

The java compiler ignores comments, so they do not cause the computer to perform any action when the program is run.

By convention, we begin every program with a comment indicating the figure number and the program’s filename.

The comment in line 1 begins with //, indicating that it’s an end of line comment, it terminates at the end of the line on which the // appears.

An end of line comment need not begin a line; it also can begin in the middle of a line and continue until the end.

Line 2 by our convention, is a comment that describes the purpose of the program.

/* This is a way that you can comment in multiple line */These begin with the delimiter /* and end with */.

The compiler ignores all text between the delimiters.

Java provides comments of a third type Javadoc comments.

These are delimited by /** and */.

The compiler ignores all text between the delimiters.

Javadoc comments enable you to embed program documentation directly in your programs.

Such comments are the preferred Java documenting format in industry.

The Javadoc utility program reads Javadoc comments and uses them to prepare program documentation in HTML5 web page format.

We use // comments throughout our code, rather than traditional or Javadoc comments, to save space.

DECLARING A CLASSLine 2 begins a class declaration for class example.

Every Java programs consist of at least one class that you define.

The class keyword introduces a class declaration and is immediately followed by the class name which is an example.

Keywords are reserved for use by Java and are spelt with all lowercase letters.

public class example {FILENAME FOR A PUBLIC CLASSA public class must be placed in a file that has a filename of the form ClassName.

java, so the class example is stored in the filename example.


CLASS NAMES AND IDENTIFIERBy convention, class names begin with a capital letter and capitalize the first letter of each word they include.

A class name is an identifier a series of character consisting of letters, digits, underscore (_) and dollar sign ($) that does not begin with a digit and does not contain spaces.

Some valid identifier is Welcome1, $value, _value_ and button7.

The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space.

Normally, an identifier that does not begin with a capital letter is not a class name.

Java is case sensitive — uppercase and lowercase letters are distinct — so value and value are different identifiers.

DECLARING A METHODLine 5 is a comment indicating the purpose of line 6 of the program.

line 5: // main method begins execution of Java application.

line 6: public static void main (String [] args) {Line 6 is the starting point of every Java application.

The parentheses after the identifier main indicate that it’s a program building block called a method.

Java class declarations normally contain one or more methods.

For a Java application, one of the methods must be called main and must be defined as in line 6, otherwise, the program will not execute.

Methods perform tasks and can return information when they complete their tasks.

Keyword void indicates that this method will not return any information.

Later, we’ll see how a method can return information.

For now, simply mimic main’s first line in your program.

The String[] args in parentheses is a required part of main’s declaration.

The left brace at the end of line 6 begins the body of the method declaration.

A corresponding right brace ends it.

Line 9 is indented between the braces.



printlnLine 7 instructs the computer to perform an action — namely, to display the characters between the double quotation marks.

The quotation marks themselves are not displayed.

Together, the quotation marks and the character between them are a string — also known as a character string or a string literal.

A white-space character in strings is not ignored by the compiler.

A string cannot span multiple lines of code.

The System.

out object which is predefined for you’ll is known as the standard output object.

It allows a program to display information in the command window from which the program executes.

Method System.


println displays a line of text in the command window.

The string in the parentheses in line 7 is the method’s argument.

When System.


println completes its task, its position the output cursor at the beginning of the next line in the command window.

This is smaller to what happens when you press the enter key while typing in a text editor — the cursor appears at the beginning of the next line in the document.

The entire line, System.


println, the argument “This is an example” in the parentheses and the semicolon (;) is called a statement.

A method typically contains statements that perform its task.

Most statements end with a semicolon.

MODIFYING YOUR PROGRAMNow we are going to modify “example.

java” using multiple statements and to print text on several lines by using a single statement.

Displaying a single line with multiple statementsThis is a simple program can be displayed in several ways.

Class example, shown below uses two statements to produce the output in a single line.

// example.

java// printing one line with multiple statement public class example { // main method public static void main (String [] args) { System.


print("This is "); System.


println("a simple program"); } // this is where the program ends} // end of the classoutput:This is a simple program Let’s see what has changed:Line 2 is an end of line comment stating the purpose of the program.

Line 4 begins the ‘example’ class declaration.

Line 7–8 in method main display one line of text.

The first statement uses System.

out’s methods to print to display a string.

Each print or println statement resumes displaying characters from where the last print or println statement stopped displaying characters.

Unlike println, after displaying its arguments, print does not position the output cursor at the beginning of the next line, the next character the program display will appear immediately after the last character that print displays.

So, line 8 positions the first character in its argument immediately after the last character that line 7 displays.

Line 2: // printing one line with multiple statement.

Line 7: System.


print(“This is “);Line 8: System.


println(“a simple program”);Displaying multiple lines of text with a single statementA single statement can display multiple lines by using newline character (.), which indicates to System.


print and println method when to position the output cursor at the beginning of the next line in the command window.

Like blank lines, space character and tab characters, newline characters are white space characters.

The next program output four lines of text, using newline characters to determine when to begin each new line.

// example.

java// this is to print a simple statementpublic class example { // this is where the main method begins public static void main (String [] args) { System.


println(" an.simple.program"); } // this is where the program ends} // end of the classThe output of the program aboveLine 7 System.


println(“ an.simple.program”); displays four lines of text in the output window.

Normally, the character in a string displayed exactly as they appear in the double quotes.

However, the paired characters and n do not appear on the screen.

The backlash is an escape character, which has special meaning to System.

out’s print and println methods.

When a backlash appears in a string, java combines it with the next character to form an escape sequence — .represents the newline character.

When a newline character appears in a string being output with System.

out, the newline character causes the screen’s output cursor to move to the beginning of the next line in the command window.



printf displays formatted data.

The next program will use this to output on two lines the string “This is a simple program ”.

// example.

java// Displaying multiple lines with method System.



public class example { // this is where the main method begins public static void main (String [] args) { System.


printf("%s%n%s%n" , "This is a","simple program"); } // this is where the program ends} // end of the classLine 7:System.


printf(“%s%n%s%n” , “This is a”,”simple program”);This line calls method System.


printf to display the program’s output.

The method call specifies three arguments.

When a method requires multiple arguments, they are placed in a comma-separated list.

Calling a method is also referred to as invoking a method.

Method printf’s first argument is a format string that may consist of fixed text and format specifiers.

Fixed text is output by printf just as it would be by print or println.

Each format specifier is a placeholder for value and specifies the type of data to output.

Format specifiers also may include optional formatting information.

Format specifiers begin with a per cent sign (%) followed by a character that represents the data type.

For example, the format specifier %s is a placeholder for a string.

The format string specifies that printf should output two strings, each followed by a newline character.

At the first format specifier’s position, printf substitute the value of the first argument after the format string.

At each subsequent format specifier’s position, printf substituted the value of the next argument.

So this example substitute “This is” for the first %s and “simple program” for the second %s.

The output shows that two lines of text are displayed on two lines.

Notice that instead of using the escape sequence., we used the %n format specifier, which is a line separator that’s portable across operating systems.

You cannot use %n in the argument to System.


print or System.


println; however, the line separator output by System.


println after it displays its arguments is portable across operating systems.

ADDING INTEGERS EXAMPLEOur next application reads two integers typed by a user at the keyboard, computers their sum and display it.

This program must keep track of the numbers supplied by the user for the calculation later in the program.

Programs remember numbers and other data in the computer’s memory and access that data through program elements called variables.

The next program demonstrates these concepts.

// example.

java// taking input and adding those two numberimport java.


Scanner; // this is to import java scannerpublic class example { // this is where the main method begins public static void main (String [] args) { Scanner input = new Scanner(System.

in); System.


print("Enter your first integer: ");// asking for first number int a = input.

nextInt(); // this will read the number and store it System.


print("Enter the second integer: ");// asking for second number int b = input.

nextInt();// this will read the number and store its value int total = a + b; // this is where we add the numbers System.


println(total); // this is where we print the total } // this is where the program ends} // end of the classoutputImport declarationsA great strength of Java is its rich set of predefined classes that you can reuse.

These classes are grouped into packages — named groups of related classes and are collectively referred to as the Java class library, or the Java Application Programming Interface.

Line 3:import java.


ScannerThis is an important declaration that helps the compiler locate a class that’s used in this program.

It indicates that the program uses the predefined scanner class from the package named java.


The compiler then ensures that you see the class correctly.

A variable is a location in the computer’s memory where a value can be stored for use later in a program.

All java variables must be declared with a name and a type before they can be used.

A variable’s name enables the program to access the variable’s value in memory.

A variable name can be any valid identifier again, a series of characters consisting of letters, digit and underscores(_) and dollar sign ($) that does not begin with a digit and does not contain spaces.

A variable’s type specifies what kind of information is stored at that location in memory.

Like other statements, declaration statement end with a semicolon (;).

Line 9:Scanner input = new Scanner(System.

in)This is a variable declaration statement that specifies the name (input) and type (Scanner) of a variable that’s used in the program.

A Scanner enables a program to read data for use in the program.

The data can come from many sources, such as the user at the keyboard or a file on the disk.

Before using a Scanner, you must create it and specify the source of the data.

The = in line 9 indicates that Scanner variable input should be initialized in its declaration with the result of the expression to the right of the equals sign — new Scanner(System.


This expression uses the new keyword to create a Scanner object that reads characters typed by the user at the keyboard.

The standard input object, System.

in, enables applications to read bytes of data typed by the user.

The scanner translates these bytes into types that can be used in a program.

Line 11:System.


print(“Enter the first integer: ”); // asking for first number This line uses System.


print to display the message “Enter the first integer: ”.

This message is called a prompt because it directs the user to take a specific action.

We use method print here rather than println so that user’s input appears on the same line as the prompt.

Line 12:int a = input.

nextInt();// this will read the number and store it The variable declaration in this line declares that variable a holds data of type int — that is, an integer value, which are whole numbers such as 73,968,34 and 0.

The range of values for an int is -2,147,483,648 to +2,147,483,647.

The int values you use in a program may not contain commas; however, for, readability, you can place underscores in numbers.

So 323_234_342 represents int value of 323234342.

Some other types of data are a float and double, for holding real numbers, and char for holding character data.

Real numbers contain decimal points, such as in 3.

4, 0.

1 and even in negative.

Variables of type char represent individual characters, such as an uppercase letter, a digit, a special character or an escape sequence.

The type int, float, double and char are called primitive types.

Primitive types of names are keywords and must appear in all lowercase letters.

The = in line 12 indicates that int variable a should be initialized in its declaration with the result of input.


This uses the Scanner object input’s nextInt method to obtain an integer from the user at the keyboard.

At this point, the program waits for the user to type the number and press the Enter key to submit the number to the program.

My program assumes that the user enters a valid integer value.

If not, a logic error will occur, and the program will terminate.

Through this method only we will input the value of the second number and store it in variable b.

CALCULATIONLine 17:int total = a + b;// this is where we add the numbersIn this line the int variable sum and initializes it with the result of a + b.

When the program encounters the addition operations, it performs the calculation using the values stored in the variables a and b.

In the preceding statement, the addition operator is a binary operator, because it has two operands which are a and b.

Portions of the statement that contains calculation are called expressions.

In fact, an expression is any portion of a statement that has a value.

The value of the expression a and b is the sum of the numbers.

Similarly, the value of the expression input.

nextInt() is the integer-typed by the user.

RESULTLine 19:System.


println(total); // this is where we print the totalI think till now, you can easily understand what is happening in this statement.

It is pretty much straight forward.

MEMORY CONCEPTVariables names such as a,b and total actually correspond to locations in the computer’s memory.

Every variable has a name, a type, and a size and a value.

Line 11int a = input.

nextInt(); //this will read and store the number In this line, the number typed by the user is placed into a memory location corresponding to the name a.

Suppose that the user enters 89.

The computer places that integer value into a location a, replacing the previous values if any provided before in that location.

The previous value is lost, so this process is said to be destructive.

This same thing happens to int b.

The computer places that integer value into location b.

After the program obtains a value for both a and b, it adds the values and places the total into variable sum.

Line 16 perform the addition, then replaces any previous value in total (if there is any).

The value of a and b appears exactly as when it has been entered by the user and they are exactly the same when calculating.

After adding both the number, the value is stored in total which remains unchanged (till the time you don’t enter a new number).

These values were used, but not destroyed, as the computer performed these calculations.

When a value is read from a memory location, then the process if called nondestructive.

.. More details

Leave a Reply