Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
How to get String , starting from 1 and ending at n?

How to do that, When user inputs n=4 then it should generate a string like str="1234"?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use a simple loop for example :

int n = 4;
String str = "";
for (int i = 1; i <= n; i++) {
    str+=i;
}

can we directly get int= 1234

In this case you can parse it like this :

int result = Integer.parseInt(str);

If you want to avoid this and get int from the begging you can use :

int n = 4;
int result = 0;
for (int i = 1; i <= n; i++) {
    result *= 10;
    result += i;
}
over 4 years ago · Santiago Trujillo Report

0

int n = 10;
StringBuffer s = new StringBuffer();
for(int i=1;i<=n;i++){
s = s.append(i); 
}
System.out.println(s.toString());
over 4 years ago · Santiago Trujillo Report

0

Note: Do not use String concatenation in for, instead it use StringBuilder.

Take a look at this question.

In your case n is a small value and because it is not so important. If n has a big value it will be a vast of memory.

Java 8 way

int n = 4;

StringBuilder sb = new StringBuilder();
IntStream.rangeClosed(1, n).forEach(sb::append);
String str = sb.toString();

Java 7 way

int n = 4;

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
    sb.append(i);
}
String str = sb.toString();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!