Every Java program has at least one
method
i.e., Main method
Every Java program has at least one method
Can we pass arguments to the
main method...?
How do we pass arguments to the
- Command Prompt
main method...?
What can be passed as arguments - Inputs can be passed
to the main method...? as arguments
Command Line Arguments
public static void main(String args[])
main() function of a Java program accepts arguments from
command prompt or from other shell scripts.
String args[] – passes the arguments to main function and stored
as string array
Predict the output, if input “hello” is passed
in the command prompt
class Main{
Output:
public static void main(String args[]) {
hello
System.out.println(args[0]);
}
}
Write a program to add two numbers using command line arguments.
Sample Sample Output:
Input:
10 20 30
Add Two Numbers
import java.util.Scanner;
class Main{
public static void main(String args[]){
Command line
Scanner in = new Scanner(System.in);
arguments...?
int x = in.nextInt();
int y = in.nextInt();
int z = x + y;
System.out.println(z);
}
}
Add Two Numbers
import java.util.Scanner;
class Main{ Error
:
public static void main(String args[])
{
int sum = args[0] + args[1];
System.out.println(sum);
}
}
Parsing
Conversion of String to Number
Types of Parse Methods:
Integer.parseInt(); Convert string to
Float.parseFloat(); Integer
Float
Double
Double.parseDouble();
Add Two Numbers
import java.util.Scanner;
class main {
public static void main(String args[]) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.print(sum);
}
}
Predict the output
import java.util.Scanner;
public class main {
public static void main(String args[]) {
String s= "156";
Output
System.out.println(s + 1); 1561
}
}
Predict the output
import java.util.Scanner;
class main {
public static void main(String args[]) {
String s= "156"; Output
double x = Double.parseDouble(s);
System.out.println(x + 1);
157
}
}
THANK YOU