try this - I don't what error you got, but here yah go
int x;
int y;
int [] args = new int[3];
args[0] = 1;
args[1] = 2;
x = args[0];
y = args[1];
System.out.println(x + y);
Dano
dskryzer@hotmail.com
What's your major malfunction
Apologies, I did not explained my prob...actually, I am trying to sum 2 numbers passed at command line...here args is command line argument. I think main function can only contain String args. I am not at all sure.
my code is
public class Sum {
public static void main(String[] args)
{
// sum to numbers
int x = args[0];
int y = args[1];
System.out.println(x + y);
}
}
and error on compilation is "Incompatible type of declration. Can't convert java.lang.String to int"
I know args is string and my x and y are int. But, how do i solve it?
Maybe you have already solve your problem, but I will give you a solution.
You just have to convert the strings to ints as you might expect.
So, simply do :
public class Sum {
public static void main(String[] args)
{
int x = Integer.parseInt (args[0]);
int y = Integer.parseInt (args[1]);
System.out.println(x + y);
}
}
Thank you all for your reply and time. I was not able to figure out, how to do casting. It solved my problem.
Now, to do any casting, will the syntax be always same
float x = Float.parseFloat(argu[0]); OR
Int y = 3;
String s = String.parseChar;
or it will be different. I am also bit confused with when to use Int and when Integer, when char and when String. Kind of I am confused with types and its conversions. any comments will be a guideline for me.
What we are talking about is not casting, but logical representations between very different types (i.e. String and int). You talk about casting when conversion between types has a "semantic" sense (casting a float to an int has sense, but casting a String to an int has no sense).
We often talk about "primitive casting". Primitives in the Java language are : char, byte, short, int, long, float, double, boolean, and void.
You might have heard that everything in Java is object, indeed classes instance. Objects are always created in a memory area which is not optimal. But the Java language has particular elements which are called primitives. Primitives look like objects, but are not objects at all. They are created and managed in a different way(for example int primitive is useful for loop counters). However, primitives are wrapped into objects specially made for that, such objects are called wrappers.
Integer, Float classes, for example are wrappers for primitives int and float respectively. They just provide helpful features to manage their corresponding primitives.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.