Why do we use (String args[ ]) only in Java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I was recently asked in an exam why we use main (String args[ ]) only in java? Why don't we use main (String args[ ]) in any other programming languages?

main() and other ways to shape the entry point into the application is a part of the language. The reason it is done the particular way in particular language is because the author of the language has seen the protocol between the language runtime system (an OS abstraction layer if that language needs to have an OS underneath to run) and the programmer that way.
I can assume that in Java it was made main(String[] args) because the language was inspired by C++ in a way (thus main() was preserved) and String[] args this is the Java way to pass an array of strings into the function.

Regarding…
“Why don't we use main (String ars[]) in any other programming languages?”
That’s a flawed assumption in the question.
C# example from MSDN:
// Hello3.cs
// arguments: A B C D
using System;
public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}

Why don't we use main (String ars[ ]) in any other programming languages?
Because you like to do it probably. If you're asking if you can do that in other languages (like C++, with which you marked the topic), the answer is: yes, you can.
They syntax for C++ would be:
int main(int argc, char *argv[])
Or - if you would want to also include environment variables:
int main(int argc, char *argv[], char *envp[])

Java has a built in String class so arguments to the class's main method are represented by String args[] or a String array.
Whereas in C++, there is not built in String class, so arguments are represented by char* argv whereas their count is represented by int argc.

The UNIX interface for invoking an application is to collect the individual command line tokens into an array of strings and pass that array to the entry point of the application. UNIX defined that this entry point is named "main", and that the command line tokens would be expressed as an array of pointers to C-style null-terminated strings. Since there's no other way to know the size of the array, the array size was passed as a separate parameter:
main(int argc, char* argv[])
MSDOS and Windows copied this scheme, so it has become quite standard.
Even though Java programs aren't invoked directly from the operating system, the designers of Java choose to use a similar (familiar) paradigm, where the command line tokens would be passed into a method named "main" as an array of Java String objects.

Related

What is the use of converting the array to a string in this line "System.out.println(new String(array1));"

This program is taken from the text book I use to teach the students with. In the last line of the code I do not understand what the author was trying to say new String(array2). I get the same output without the new String i.e. printing directly array2.
public class ArrayCopyDemo
{
public static void main(String [] args)
{
char [] array1 =
{'d','e','f','g','h','i','j','k','d','e','f','g','h','i','j','k'};
char [] array2 = new char[15];
System.arraycopy(array1, 3, array2, 0, 7);
System.out.println(new String(array2));
}
}
Evidently the person writing this knew about arrays not overriding toString. We've all been burned by that one, it only takes once printing out something and getting a hashcode back to make the point.
But maybe the writer didn't know that println has an override for char[]; I know I was not aware of it until a few minutes ago. You can do a lot of Java programming without ever needing that. If you in fact don't know about that then it would make sense to do the conversion explicitly like the posted code.
(Or just as likely, it could be the author did know but didn't want to assume his students knew about it. When you write code meant for beginners to read you want to avoid confusing the reader with anything unusual, if only to avoid having to field the same newbie questions over and over.)
If the question is how to explain this to students, you may want to talk about how in software everything is changing all the time, and our objective is to make working software on time pressure that is good enough even though our knowledge is imperfect.
There's also an opportunity to talk about the ramifications of design decisions, comparing how in Java we have a differentiation between Strings and char arrays, and primitives and objects, unlike say in Haskell. So we have these design choices that cause odd corner cases and ugliness in the API, and the Java implementors can't just get rid of this cruft because of their concern for backward compatibility. Java is full of unintuitive edge cases, see Bloch and Gafter's puzzle book.
Often teachers (specifically grad students) are put in a situation where on short notice they have to teach a language that they've never used before. Textbook writers are working to get their book finished and may miss something occasionally. Sometimes the language has bizarre edge cases that it's not fair to expect everybody to know. Students have to adjust their expectations to these realities.
It's helpful in case your are concatenating it with a string. Ex:-
char [] array1 =
{'d','e','f','g','h','i'};
char [] array2 = new char[15];
System.arraycopy(array1, 3, array2, 0, 7);
System.out.println(new String(array1));
If You were to print Something array1content. Say "Hello defghi"
Incorrect Code
System.out.println("Something"+array1)); //"Something 'array type' as string and char array is being concatenated.
Correct code
System.out.println("Something"+new String(array1));
It's an example to show the use. Although the use of new String() is of no significance in your code.
In generall, new String(array2) is used to convert a char[] array into a String, with the same characters as in the array itsself.
Note that there are two overloaded variants of the println method defined, see java.io.PrintStream.println(char[] x) and java.io.PrintStream.println(String x), however, they result in the same behaviour, so you could omit the new String creation.
However, you should be aware of the difference.

What is exactly args and how do i used it? [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 9 years ago.
I am a new programer and I'm just starting to learn the basics of Java and I'm trying to understand what exactly "args" stands for in "public static void main(String[] args)".
I found that's it's connected to command line arguments, which I don't understand. I would like to know what "args" means.
Thank you.
When you run a Java program, it usually looks like this:
java MyProgram
However, you also have the option of including command-line arguments. For example, if your program adds two numbers, you could set it up to take input like this:
java MyProgram 12 47
In this case, arr would equal ["12", "47"]. Having input work in this way is useful because it makes it easier to automate the running of your program through batch files or the like.
args is an arbitrary name for command line arguments. Running a java class file from the command line will pass an array of Strings to the main() function. If you want to handle extra arguments, you can check for keywords at certain indices of args and perform extra functions based on them.

Assign an operator symbol to a variable and use that variable for conditional check [duplicate]

This question already has answers here:
Is it possible to pass arithmetic operators to a method in java?
(9 answers)
Closed 6 years ago.
Can I assign an operator symbol to a variable and use that variable for a conditional check?
char operator= '>';
int val1=10;
int val2=24;
if(val2 operator val1){
/* some code*/
}
Why cant I use the operator variable inside conditions?
Hey Thats not supported I think this will make sense to me.
The compiler reads in the operator when it builds your app. It has no way of knowing what the operator would be so it cant build correclty which I found in http://www.daniweb.com/software-development/csharp/threads/266385/c-using-operator-as-a-variable-in-calculations
They are talking in the context of C#, but I feel same thing makes sense here as well.
You cannot directly do that, but there are work arounds:
http://www.coderanch.com/t/568212/java/java/arithmetic-operations-operator-stored-variables
If thats really required, we have to use eval sort of thing in our code. I just tried this sample code.
package dumb;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class OperatorAsVariable
{
public static void main( String args[] ) throws ScriptException
{
String test = "+";
System.out.println( 1 + test + 2 );
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName( "js" );
System.out.println( engine.eval( 1 + test + 2 ) );
}
}
Courtesy : Is there an eval() function in Java?
Method arguments in Java must be expressions. And a operator is not an expression. This is not possible in Java.
a better way is pass objects(enums) that represents those operators
example:
public enum Operator{
GREATHERTHAN(">") {
#Override public double apply(double x1, double x2) {
return x1 > x2;
}
},LEESTHAN{
#Override public double apply(double x1, double x2) {
return x1 < x2;
}
}
}
No, you can't do it that way in Java.
To define a binary relation dynamically you need to represent the relation as an object, with a two-argument method to do the check:
if (binaryRelation.areRelated(a,b))
{
// Do something
}
Depending on your needs the standard Comparator interface may or may not be suitable.
Code written in any programming language needs to be converted to Assembly Language. When this happens, every code statement written in High Level language gets translated to instruction / set of instructions in Middle Level equivalent i.e.
JAVA code will get translated to Machine Specific instructions in Assembly Language.
Here addition operation in following statement,
int a = a + 10;
May get converted to
ADD A 1010;
And when we try to access a variables value, it may get converted to READ instruction.
So, when you try to use '>' in a variable,
char operator= '>';
int val1=10;
int val2=24;
if(val2 operator val1){
/* some code*/
}
The if statement,
if(val2 operator val1)
will convert to an invalid instruction.
Instead of generating an equivalent for comparison of two values, it will READ 'operator' variable.
This will obviously, lead to wrong interpretation.
Hence, doing such thing is not allowed.
Every compiler(java , gcc etc ) may behave differently but the target is same. If you read Complier / Compilation / Execution more, you will know more.
These are some links:
http://www.coderanch.com/t/559258/java/java/java-codes-converted-assembly-JVM
Do programming language compilers first translate to assembly or directly to machine code?
Steps for Compilation of A C program.
http://www.herongyang.com/Computer-History/C-Program-Compilation-and-Execution-Process.html
Take a look at the Comparator or Comparable interfaces and how they are used. Then define your own interface which takes two arguments and returns a boolean, and provide different implementations for them (this is OOP).
Another way would be to wait for Java 8 which will have lambda expressions.

Understanding (string args[]) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is “String args[]”? in Java
So I recently (well, three days ago) started teaching myself Java, with absolutely zero previous programming experience unless you count HTML/CSS.
Now I've been looking through both books and online tutorials, including the Sun tutorials. I don't quite understand what the purpose of (string args[]) in a method is.
What I've got from looking online is that when using the console to run a program, it substitutes whatever comes after ">Java myprogram" in place of the "args".
Firstly, is that correct? If so, why would you do that?
Cheers!
The String[] args which can be written as String args[] or String ... args is an array of the arguments you gave the program.
why would you do that?
So you can give your program inputs on the command line. It isn't used in Java programs so often but it is quite commong for command line utilities to take arguments e.g.
In this case the MyClass.java is an argument.
javac MyClass.java
Or like the following has three arguments.
java -cp . MyClass
This is, more or less, correct. Every whitespace-separated word that comes after java Program is stored into an array of Strings, which happens to be called args.
An example on how to use this for your benefit:
public class Test {
public static void main(String[] args)
{
if(args.length > 0)
{
System.out.println(args[0] + "\n");
}
}
}
Compile this with:
> javac Test.java
And then run it:
> java Test Yes
"Yes" is then printed to your screen.

Why does Java takes Input in String format only?

In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not require methods to convert them. Then why does java follows such long procedure. **What is the reason behind such an architecture of Java ?
//In java we follow the following process
public static void main(String args[])
{int i = Integer.parseInt( args[0]);// here we get input in String format and then convert it
}
//In C++ we follow the following :
void main()
{int i;
cin>>i;
}
Both C/C++ and Java takes input form Console then why java takes it in String Format and C++ does not ??
Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Java - If you use the Scanner class you can get the input in the required data type. It's not only String java accepts.
If you take an integer from the console in C, it will require you to atoi() the input.
You always get a string when reading from stdin. In C++ however, the >> operator overload used when writing to an int performs the conversion - so it's just a different way of converting but in both languages it's necessary.
You are right that it's nicer in C++ though since you can use pretty much the same code no matter what data type you have.

Categories