It is allowed to perform the operation module % with double number in java, and how to change a single position of a string in java?

Asked

Viewed 46 times

-3

My doubts..

  • It is allowed to perform the operation module % with floating point number in java, and why? Because in compilers like c++ this operation is not allowed.

  • How do I access an element of a string and change it ? Example, I have a string. String s = "ola"; How to change the position 0 of the element by a letter or scale ?

  • It is allowed to access a String as an array ? example str[i].

  • 1

    I think you should ask three different questions instead of putting three very different things into one.

  • 1

    https://ideone.com/xixih2

  • Each question should be expected, with a time of 40 minutes.

  • 1

    You can [Dit] this, let the doubt you deem most important and in the future open the other questions.

1 answer

2


1:

class Teste {
    public static void main(String[] args) {
        System.out.println(6.25 % 2.5);
    }
}

Output: 1.25.

2: Strings are immutable! That is, you would have to create a new String instead of changing the existing one. For example:

String s = "ola";
String s2 = "x" + s.substring(1);
System.out.println(s2);

The exit is xla.

3: No. But you can do something like this:

String s = "teste";
char[] array = s.toCharArray();
array[2] = 'x';
String s2 = new String(array);
  • But like, in case it is impossible to use Java and keep changing the string to char right ? it is better to mount another..

  • @Victorocv The strings in Java have as one of their premises the fact that they can never be changed. If this were allowed, it would become chaos. The approach is you always assemble another, and for this you can use char[], can use class own methods String who create other Strings and can use the classes StringBuilder and StringJoiner.

  • I get it, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.