0

So I have this particular code:

import java.util.*;

class insertWordInMiddle {
    public static void main(String[] args) {
        
        String s = "Python 3.0";
        String s_split[] = s.split(" ");

        String a = new String(s_split[0]);
        String b = new String(s_split[1]);

        String c = a + " Tutorial " + b;
        System.out.println(c);
        
    }
}

I was practising and I wanted to insert a word between two words (in the form of a string). It works, however I have yet other way of doing this but cannot get why it doesn't work:

import java.util.*;

class insertWordInMiddle {
    public static void main(String[] args) {
        
        String s = "Python 3.0";
        String s_split[] = s.split(" ");
        String final = s_split[0]+" Tutorial "+s_split[1];

        System.out.println(final);
    }
}

Error:

/home/reeshabh/Desktop/java practice/insertWordInMiddle.java:14:

error: not a statement

String final = s_split[0]+" Tutorial"+s_split[1];

Community
  • 1
  • 1
MrObjectOriented
  • 274
  • 3
  • 12

4 Answers4

3

The simple answer is that final can't be the name of a variable. I can go into more detail if needed, but that's pretty much it. Try something else for your variable name.

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
0

final is a reserved keyword in Java. You can't name a variable final. Try renaming it to e.g. finalString.

Wikipedia has a list of all the reserved keywords.

Nyubis
  • 528
  • 5
  • 12
0

final is a keyword. You can't use it as a variable name.

As per the building of strings: you could use StringBuilder, but for generating one string it's not really necessary. However, concatenating strings using the + operator will create copies of all strings involved and make baby cry when used within a loop.

When to use StringBuilder in Java

Oscar de Leeuw
  • 126
  • 2
  • 6
0

You was just a bit unlucky - you used word that is reserved for other purposes in Java language. Take a look at this list, final is present here, so you can't name variables with words listed there: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21