How to split a String in Java ?

I have a string like “040-286595” that I want to split into two strings:

string1=040
string2=286595

That means the first string will contain the characters before ‘-’, and the second string will contain the characters after ‘-’. I also want to check if the string has ‘-’ in it. If not, I will throw an exception. How can I do this, please help me?

for doing this operation one method is present in java that is string.Split("string"); this method takes parameter as String, and it returns the String[] array 

 

 

String string = "040-286595";

 

String[] str = string.Split("-");

 

String str1 = parts[0]; // 040

String str2 = parts[1]; //286595