OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Java Statements and Command Line Arguments
Java Statements
statements are instructions that tell the program what to do. They are the building blocks of any Java program and are typically terminated with a semicolon (;
). Here is a detailed overview of Java statements:
Types of Java Statements
1. Declaration Statements
Used to declare variables and assign types.
2. Expression Statements
These include assignments, method calls, increment/decrement operations, and object creation.
3. Control Flow Statements
Used to control the flow of execution.
a. Conditional Statements
-
if
,if-else
,if-else-if
,switch
b. Looping Statements
-
for
,while
,do-while
c. Branching Statements
-
break
,continue
,return
Compound Statements / Block Statements
-
A group of statements enclosed in
{ }
. These define a block.
Empty Statement
A statement that does nothing — just a semicolon (;
).
Labeled Statements
Used with loops and branching (break
, continue
).
Example Java Program with Various Statements
Command Line Arguments
Sometimes you will want to pass information into a program when you
run it. This is accomplished by passing
command-line arguments to main( ). A command-line argument is the information
that directly follows the program’s
name on the command line when it is executed. To access the command-line arguments inside a Java program is quite
easy—they are stored as strings in a String array passed to the args parameter of main( ). The first
command-line argument is stored at args[0], the second at args[1], and so
on.
Syntax of main()
Method
-
args
is an array ofString
objects. -
These are the values provided at runtime via command line.
-
Java automatically populates the
args
array with these values.
How to Pass Command Line Arguments
Example Command (using terminal or command prompt):
In the Java Program:
Output:
Converting Arguments to Other Data Types
Since all command line arguments are String
s, you must convert them if needed:
Example Program: Add Two Numbers from Command Line
Run in Terminal:
Output:
For example,
the following program displays
all of the command-line arguments that it is
called with:
// Display all command-line
arguments.
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Try executing this program, as shown here:
java CommandLine this is a test 100
-1
When you do,
you will see the following output:
args[0]: this args[1]: is args[2]: a args[3]:
test args[4]: 100
args[5]: -1
NOTE: All command
line arguments are passed as strings. You must convert
numeric values to their internal forms manually.
Comments
Post a Comment