What's the difference between String and String[]? - java

Could anyone help me understand the difference? I need to understand for my class and they seem the same to me.
String or String[]

String is -> a series of characters in your code that is enclosed in double quotes.
More details a bout String
String[] -> An array is a container object that holds a fixed number of values of a Strings.
More about Arrays

The difference between String and String[] is that String is used to declare a single instance of a String object:
String name = "Cupcake";
On the other hand, String[] is used to declare an array of multiple strings:
String[] names = new String[] { "Joe", "Alice" };
In Java generally, arrays of type <Type> are declared using the following syntax:
<Type>[] types;
From the official Java documentation for arrays:
An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.

String is used to create a single object of type String
String[] is an Array, containing a specified number of String objects.

String is a class, and String a represents an object of this class (the String class represents an object containing a sequence of characters). While String a[] represents an array of objects of this type.
An array is a kind of container. It can contain various objects inside. In this case with String[] you are specifying that this container has only String objects
String a = "abc"; /*this is a String, notice it references only to one
object, which is a sequence of characters*/
String b[] = new String[]{"abc", "def"}; /*this is a String array.
It is instantiated with 2 String objects, and it cannot
contain anything else other than String or its sub classes (i.e: no Integers or neither Object). */

Similar to array, String[] is used to store more than one string at a time.
Following is a sample program for String[]
public class JavaStringArrayExample {
public static void main(String args[]) {
// declare a string array with initial size
String[] schoolbag = new String[4];
// add elements to the array
schoolbag[0] = "Books";
schoolbag[1] = "Pens";
schoolbag[2] = "Pencils";
schoolbag[3] = "Notebooks";
// this will cause ArrayIndexOutOfBoundsException
// schoolbag[4] = "Notebooks";
// declare a string array with no initial size
// String[] schoolbag;
// declare string array and initialize with values in one step
String[] schoolbag2 = { "Books", "Pens", "Pencils", "Notebooks" }
// print the third element of the string array
System.out.println("The third element is: " + schoolbag2[2]);
// iterate all the elements of the array
int size = schoolbag2.length;
System.out.println("The size of array is: " + size);
for (int i = 0; i < size; i++) {
System.out.println("Index[" + i + "] = " + schoolbag2[i]);
}
// iteration provided by Java 5 or later
for (String str : schoolbag2) {
System.out.println(str);
}
}
}
Hope this will give you an idea.

Related

How to type-cast a nested Array of Objects into a nested List of Strings

Cannot create nested ArrayList from Array in Java
I am trying to create a nested list from an array.
But I have a problem while converting Object to String:
Object[] array = new Object[] {
new String[] {"add, hack"},
new String[] {"add, hackerrank"},
new String[] {"find, hac"},
new String[] {"find, hak"}
};
List<List<String>> list = Arrays.asList(Arrays.asList((array.toString())));
So, how can I convert it properly?
Here is the method that reserves the List<List<String>>:
public static List<Integer> contacts(List<List<String>> queries) {
for (List<String> query : queries) {
String operation = query.get(0); // --> gives "add, hack" (I expect "add")
String word = query.get(1);
}
}
Every array inside the source array in your code like new String[] {"add, hack"} is treated as Object - that's all the compiler knows about it because array has been declared as Object[] (i.e. array of objects, not array of arrays objects, or array of arrays of strings).
Arrays.asList(array.toString()) - creates a list with a single element of type String. And when you invoke toString() on an array of any type, you will obtain a string containing the array's type and hash-based sequence of symbols after the at-sign #. In order to get a string representation of the array contents, you need to use static method toString() of the Arrays class.
This way you can approach the problem of casting an array of Object type
public static void main(String[] args) {
Object[][] array = new Object[][]{
new String[] {"add, hack"},
new String[] {"add, hackerrank"},
new String[] {"find, hac"},
{"find, hak"} // you can omit new String[] when assigning array while at the same time with initialization
};
List<List<String>> list = arraysToList(array, String.class);
System.out.println(list);
}
Generic method for casting, that expects a Class object as a parameter:
public static <T> List<List<T>> arraysToList(Object[][] array, Class<T> clazz) {
return Stream.of(array)
.map(arr -> Stream.of(arr).map(clazz::cast).toList())
.collect(Collectors.toList());
}
Output
[[add, hack], [add, hackerrank], [find, hac], [find, hak]]
Your Question is unclear as to your goal. Perhaps you want to generate text in a specific format. If so, add a method to the record class Query that returns a String object in your desired format.
If you need to split a single string containing non-alphabetic symbols into separate words, you can make use of the split() method:
str.split("[^\\p{Alpha}]+"); // returns an array of strings comprised of alphabetic symbols only
Use objects, not lists of arrays
The other Answers seem to be correct about your various problems. I will look at the bigger picture… Your design approach has ignored the the best feature of Java: object-oriented programming.
Your query pieces should be packaged as a class, a record.
record Query ( String verb , String noun ) {}
Apparently you are starting with a comma-separated string as inputs. So add a static factory method to parse each input.
record Query ( String verb , String noun ) {
// Factory method to instantiate `Query` object by parsing input string containing a pair of comma-separated values.
public static Query parse( final String input ) {
String[] parts = input.split( ", " ) ;
return new Query ( parts[0] , parts[1] ) ;
}
}
Skip the arrays, and use List or Set for their convenience.
List< Query > queries =
List.of(
Query.parse( "add, hack" ) , // Instantiates a `Query` object.
Query.parse( "add, hackerrank" ) ,
Query.parse( "find, hac" ) ,
Query.parse( "find, hak" )
)
;
Generating text
Report contents.
System.out.println( "queries = " + queries );
queries = [Query[verb=add, noun=hack], Query[verb=add, noun=hackerrank], Query[verb=find, noun=hac], Query[verb=find, noun=hak]]
Your Question is not clear as to its end goal. If your goal is to generate text in a particular format, add a method to your class. Here we add a method called report.
String report ( ) { return String.format( "{ %s, %s }" , this.verb , this.noun ); }
To use that report method, loop your objects, generating text for each.
queries.forEach( query -> System.out.println( query.report() ) );
{ add, hack }
{ add, hackerrank }
{ find, hac }
{ find, hak }
Caveat: In real work, we would do more to verify and validate. For example we would validate our input data to make sure the input string is non-null, non-blank, and composed of two parts. I omitted such code to keep the demo short and on-point.
One more solution assuming you want to start from Object[] array - first transforms to list of String[] using casting and then maps every String[] to List:
List<String[]> arrList = new ArrayList<>();
for (Object o : array)
arrList.add((String[]) o);
List<List<String>> strList = arrList.stream()
.map(Arrays::asList)
.collect(Collectors.toList());
In order to be an "array of arrays" it would need to be a 2-dimensional array:
String[][] arrays = new String[][] {new String[] {"add, hack"}, ...}
Then you could convert each array inside the array into an item in the list
List<List<String>> list = new ArrayList<>();
for (String[] array : arrays) {
list.add(Arrays.asList(array));
}
You can stream the array and then collect to a List:
Object[] array = new Object[] {
new String[] {"add, hack"},
new String[] {"add, hackerrank"},
new String[] {"find, hac"},
new String[] {"find, hak"}};
List<List<String>> list = Arrays.stream(array)
.map(String[].class::cast)
.map(arr -> arr[0].split(", "))
.map(Arrays::asList)
.collect(Collectors.toList());
System.out.println(list);
Output:
[[add, hack], [add, hackerrank], [find, hac], [find, hak]]
With JDK 16+ you can do:
List<List<String>> list = Arrays.stream(array)
.map(String[].class::cast)
.map(arr -> arr[0].split(", "))
.map(Arrays::asList)
.toList();

How can i remove an element from array in Java

Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}

Bubble Sorting string in an array

I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c
Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.
There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];
public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....
You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.

Merging string-Array / arrayList without using loop

I was trying to do something like:
ArrayList<String> getMerged ( String host, String port, String filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy.split(",")); //which is invalid
return merged;
}
I want to know if we can add elements of filesToCopy.split(",") with out having the overhead of using a loop.
Also, if the above operation can be done in a string array, say String[] merged (can pass filesToCopy also as String[] if needed), it would be even better coz in the end, I'll be converting this arrayList into an array.
I'm novice in Java programming, so please don't mind if this is a silly question.
You could do this in a single array:
String[] files = filesToCopy.split(","); // filesToCopy is an ArrayList, so I'm not
// sure how this works; I'm assuming it's
// a typo. Just get the files array somehow
String[] merged = new String[2 + files.length];
merged[0] = host;
merged[1] = port;
for (int i = 2; i < merged.length; i++) {
merged[i] = files[i-2];
}
Or, without "the overhead of a loop":
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
Of course, this still uses a loop "behind the scenes," which is unavoidable.
ArrayList.addAll method requires a Collection as a parameter, so just pass the filesToCopy:
String [] getMerged ( String host, String port, ArrayList<String> filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy);
return merged.toArray(new String[merged.size());
}
PS: I just a matter of opinion, but if I can choose between arrays and Collections, I always prefer to work with Collections (List, Set). Variable size and easy insertions are things to take into account.
I am not sure about what your need is.But i am sure anyone of the below methods will surely help you..
1.Covert String With Comma To A ArrayList
Program:
import java.util.Arrays;
....
String name="java,php,c";
List<String> list=Arrays.asList(name.split(","));
System.out.println(" "+list);
OutPut:
[java, php, c]
2.Covert ArrayList To StringArray
Here we can convert the same arraylist that we got in 1st method to string array.
Program:
String []names=list.toArray(new String[list.size()]);
for(String s:names){
System.out.println(""+s);
}
OutPut:
java
php
c
3.Covert ArrayList To Comma Seperated String
Here we can convert the same arraylist that we got in 1st method to string array.
For this you need To add commons-lang3-3.2.1.jar into your classpath or project libarary.
You can Download The commons-lang3-3.2.1.jar (HERE)
Program:
import org.apache.commons.lang3.StringUtils;
.....
String name=StringUtils.join(list, ",");
System.out.println("name="+name);
OutPut:
name=java,php,c
4.Updated Program
This might me the method that you needed
public String[] getMerged(String host, String port, String filesToCopy) {
String files[] = filesToCopy.split(",");
String[] merged = new String[(2 + files.length)];
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
return merged;
}
Check out these methods and notify me if your need is something other than these methods..

Java: how to initialize String[]?

Error
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
Code
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}
You need to initialize errorSoon, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.
If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.
As a side note, you could also initialize the String array inside braces, { } as so,
String[] errorSoon = {"Hello", "World"};
which is equivalent to
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
In Java 8 we can also make use of streams e.g.
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
In case we already have a list of strings (stringList) then we can collect into string array as:
String[] strings = stringList.stream().toArray(String[]::new);
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
String[] arr = {"foo", "bar"};
If you pass a string array to a method, do:
myFunc(arr);
or do:
myFunc(new String[] {"foo", "bar"});
String[] errorSoon = new String[n];
With n being how many strings it needs to hold.
You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
You can use below code to initialize size and set empty value to array of Strings
String[] row = new String[size];
Arrays.fill(row, "");
String Declaration:
String str;
String Initialization
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
String[] string=new String[60];
System.out.println(string.length);
it is initialization and getting the STRING LENGTH code in very simple way for beginners

Categories

Resources