0% found this document useful (0 votes)
20 views21 pages

Understanding Java main() Method Basics

Uploaded by

ankitdb04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views21 pages

Understanding Java main() Method Basics

Uploaded by

ankitdb04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

About main()method

A simple Java program


Let us consider a simple program to find the square root of an integer.
import [Link].*; //Math class is defined in this package

class Calculator{
double i;
double x = [Link](i);
}

class Example{
public static void main(String args[]){
Calculator a = new Calculator();
a.i = 20;
[Link]("Square root of "+a.i+" is "+a.x);
}
}
Analysis of the program
Let us examine each statement step-by-step.
Import
import [Link].*;
Statements
class Calculator{
double i;
Declaration double x = [Link](i);
of class }
class Example{
public static void main(String args[]){
Calculator a = new Calculator();
a.i = 20;
Declaration of [Link]("Square root of "+a.i+" is "+a.x);
main class }
}
Significance of main class
Java program starts its execution from a method belongs to a class
only.

The main() method is the starting point of the execution of the main thread.

If there are multiple classes, then ambiguity is resolved by incorporating a


main() method into only one special class called main class.

The name of the Java program should be named after this class so that Java
interpreter unanimously choose that class to start its execution.
Understanding basic Java syntax

Java main() method


public Keyword

public

• It is an access specifier, which allows the programmer to control


the visibility of class members.

• public member may be accessed by code outside the class in


which it is declared.

• main() must be declared as public, since it must be called by


code outside of its class when the program is started.
Java main() method
Note: By default a member is public.
Other access specifiers will be discussed later.
static keyword

static

• The keyword static allows main() to be called without


having to instantiate a particular instance of the class.

• This is necessary since main() is called by Java interpreter


before any objects are made.

Note: There are more information about static which will be


Java main() method discussed shortly.
void keyword

void

• As per the Java programming language paradigm, each method


should return a value; if it does not return anything, then the
return type should be void.

• The keyword void simply tells the compiler that main()


does not return any value after its execution.

Java main() method


main() method

main

• main is the name of a method in a class.

• This method is searched by JVM as a starting point for an


application with a particular signature only.

Java main() method


Arguments in main()
String args[]

• Here, String is a class defied in [Link] API.

• args[] is an array to store objects of class String.

• Here, you could write anything, say String x[] instead of


String args[]. args[] is a common practice that every
programmer use. It is a customary.

• Java sees everything as String objects.


Java main() method
• It will help to read an input and then store into the array
args[] as String objects.
Output from Java program
Statement 12 includes the following code

[Link]("Square root of "+a.i+" is "+a.x);

System is a final class from the [Link] package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

a.i and a.x represents the names of variables to be printed.

+ is a concatenation operator, it is used to concatenate the string values.


print versus println methods
Consider the following lines to be printed as output
Debasis
Samanta

This can be done using both println() and print() functions


[Link](“Debasis”);
[Link](“Debasis”);
[Link](“\n”);
[Link](“Samanta”);
[Link](“Samanta”);

• The println(“…") method prints the string "..." and moves the cursor to a new line.
• The print("...") method instead prints just the string "...", but does not move the cursor to a
new line. Hence, subsequent printing instructions will print on the same line.

Note: The println() method can also be used without parameters, to position the cursor on the next
line.
Java Runtime Data Input
Practice another Java program
Let us run this Java program:

public class UserArgument{


public static void main(String args[]){
[Link]("Hi ");
[Link](args[0]);
[Link](", How are you?");
}
}
Numeric input to program
Let us run this Java program:
import [Link].*;

class Calculator{
double i;
double x = [Link](i);
}
class Example{
public static void main(String args[]){
Calculator a = new Calculator();
a.i = [Link](args[0]);
[Link]("Square root of "+a.i+" is "+a.x);
}
}
Input to Java program with Scanner Class

Scanner is one of the predefined class which is


used for reading the data dynamically from the
keyboard.
Example program for Scanner : Maximum
import [Link];

public class MaximumCalculator {


public static void main(String args[]) {
Scanner scnr = new Scanner([Link]);
// Calculating the maximum two numbers in Java
[Link]("Please enter two numbers to find maximum of two");
int a = [Link]();
int b = [Link]();
if (a > b) {
[Link]("Between %d and %d, maximum is %d \n", a, b, a);
}
else {
[Link]("Between %d and %d, maximum number is %d \n", a, b, b);
}
}
}
Example program with Scanner and array

import [Link].*;
class SimpleArrayList{
public static void main(String args[]){
int sum = 0;
float avg = 0;
ArrayList <Integer> l = new ArrayList<Integer>();
[Link]("Enter the input ");
Scanner input = new Scanner([Link]);
while ([Link]()) {
[Link]([Link]());
}
for (int i = 0; i < [Link](); i++) {
sum = sum+[Link](i);
}
avg = sum/([Link]());
[Link]("Average : " + avg);
Note:
}
} Press Ctrl+Z to stop scanning.
Input with DataInputStream : Calculator Program
import [Link].*;

class InterestCalculator{
public static void main(String args[ ] ) {
Float principalAmount = new Float(0);
Float rateOfInterest = new Float(0);
int numberOfYears = 0;
DataInputStream in = new DataInputStream([Link]);
String tempString;
[Link]("Enter Principal Amount: ");
[Link]();
tempString = [Link]();
principalAmount = [Link](tempString);
[Link]("Enter Rate of Interest: ");
[Link]();
tempString = [Link]();
rateOfInterest = [Link](tempString);
[Link]("Enter Number of Years: ");
[Link]();
tempString = [Link]();
numberOfYears = [Link](tempString);
// Input is over: calculate the interest
float interestTotal = principalAmount*rateOfInterest*numberOfYears;
[Link]("Total Interest = " + interestTotal);
}
}
Questions to think…

• Which type of binding that a Java program


can support?
• How recursive program in Java can be written?

Common questions

Powered by AI

The 'Scanner' class in Java provides a way to read input dynamically from various sources, including keyboard input during runtime. It offers more flexibility compared to 'DataInputStream', as it comes with built-in methods for parsing different primitive types and strings based on input tokens. This simplifies the process of reading and processing different types of data input. In contrast, 'DataInputStream' is geared towards reading binary data in a more primitive form, often needing additional parsing after data is read. While 'Scanner' is generally more user-friendly and preferred for CLI applications for its ease of use and built-in parsing capabilities, 'DataInputStream' may be used where precise control over byte-level input is necessary, for example in network or file I/O .

In the Java main() method, 'String args[]' serves as a parameter for command-line arguments passed to the program during its execution. It allows the Java application to process input data directly from the command line by storing them as an array of strings. Each element of this array corresponds to a separate command-line argument. For example, if a Java program is executed with 'java Example arg1 arg2', 'args[0]' would be 'arg1' and 'args[1]' would be 'arg2'. This mechanism supports flexible data input and allows programs to be more versatile by accepting different input configurations without altering the code .

The 'public' keyword in a Java main method is an access specifier that controls the visibility of the method. It allows the main method to be accessed by the Java interpreter, which is outside the class where the main method is declared. This access is crucial because the main method serves as the entry point for the execution of a Java application. By being public, it ensures that the Java Virtual Machine (JVM) can call the main method to start the program. Without this accessibility, the main method would not be reachable from outside its class to initiate program execution .

In Java, the '+' operator is used in combination with 'System.out.println' to concatenate strings, allowing for formatted output. It merges string literals with variables or expressions to form a single output statement. This is significant for creating human-readable output because it lets programmers present data within explanatory text. For example, in 'System.out.println("Square root of "+a.i+" is "+a.x);', the '+' operator concatenates the string literals with the values of 'a.i' and 'a.x', forming a complete message illustrating what the calculated square root is. This method is user-friendly for presenting variable data seamlessly with strings .

Java handles the 'main' class designation by identifying the class containing the 'public static void main(String args[])' method, as there can only be one such entry point in a program for execution to start. When multiple classes exist, the class with this 'main' method defined is deemed the main class, signifying the starting point of the program. This allows the Java Virtual Machine (JVM) to uniquely determine the point of commencement for execution, even amongst numerous defined classes, thus ensuring proper execution flow without ambiguity. The Java program name should reflect this class for straightforward compilation and execution .

The 'DataInputStream' class in Java is used to read an input from the console in a structured way, mainly for primitive data types. In the context of calculating interest, it facilitates input processing by allowing a program to take various numeric inputs (e.g., principal amount, rate of interest, and number of years) for the interest calculation by reading the user input as strings and converting them to respective data types using parsing methods like 'Float.valueOf()' and 'Integer.parseInt()'. However, a potential drawback is its cumbersome nature compared to newer classes like 'Scanner', as it requires explicit parsing and is associated with checked exceptions, adding complexity to error handling and increasing the amount of necessary boilerplate code .

The main method in Java must be declared as 'static' to allow it to be invoked by the Java interpreter without having to instantiate the class containing it. This is necessary because the main method is the starting point of the program, and at the moment it is called, no objects of the class have been created yet. By making it static, the method belongs to the class rather than any instance of the class, thereby allowing the JVM to call it directly to start executing the program. This static nature is crucial for bootstrapping application execution without prior object instantiation .

Using an 'ArrayList' to calculate an average of inputs in Java offers dynamic sizing capabilities, which means it can accommodate an undefined number of elements without needing to specify any size beforehand. In contrast, arrays have a fixed size determined at the time of creation. This flexibility can be beneficial when input size is unpredictable. However, ArrayLists generally incur more overhead due to potential resizing and object handling, which can affect performance compared to arrays, which have direct memory allocation and access efficiencies. The choice affects program performance in Java: ArrayLists are more convenient for growing lists, but arrays can be more efficient in terms of memory and speed where the number of elements is known. Thus, the choice between them involves trade-offs between convenience and performance, with ArrayLists being more beneficial for developer simplicity in scenarios involving dynamic input .

The primary difference between 'print()' and 'println()' methods in Java lies in cursor positioning post-execution. The 'print()' method outputs the argument passed to it without moving the cursor to a new line, which means subsequent print commands will continue on the same line. In contrast, 'println()' outputs its argument and then moves the cursor to a new line, starting subsequent output from the beginning of the next line. This distinction affects how output is formatted: 'print()' is useful for continuous output on the same line, while 'println()' is preferred when each output should begin on a new line, enhancing readability and forming well-organized data presentations .

Using 'void' in the Java main method indicates that the method does not return any value. It's a convention in Java programming as the main method serves as an entry point for the application and does not need to return data to the calling process (the JVM in this case). If a return type is necessary, such as in applications where you want to return a status code to the operating system, you can define another method with an integer return type and call this from the main method. However, the main method itself should remain 'void' in a standard Java application for proper execution handling .

You might also like