Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

Java - convert String to long

0 contributions
4 points

In Java, we can convert String to long in couple of different ways.

Short solutions:

// solution 1
long num1 = Long.parseLong("123"); // 123

// solution 2
Long num2 = Long.valueOf("123"); // 123

1. Using Long.parseLong()

public class Example1 {

    public static void main(String[] args) {
        String str = "123";
        long num = Long.parseLong(str);
        System.out.println(num); // 123
    }
}

Output:

123

2. Using Long.valueOf()

public class Example2 {

    public static void main(String[] args) {
        String str = "123";
        Long num = Long.valueOf(str);
        System.out.println(num); // 123
    }
}

Output:

123

3. String to long with sign + or -

public class Example3 {

    public static void main(String[] args) {

        // Long.parseLong() - returns long
        System.out.println(Long.parseLong("123")); // 123
        System.out.println(Long.parseLong("+123")); // 123
        System.out.println(Long.parseLong("-123")); // -123

        // Long.valueOf() - returns Long
        System.out.println(Long.valueOf("123")); // 123
        System.out.println(Long.valueOf("+123")); // 123
        System.out.println(Long.valueOf("-123")); // -123
    }
}

Output:

123
123
-123
123
123
-123

4. Example of java.lang.NumberFormatException

public class Example4 {

    public static void main(String[] args) {
        String str = "123a";
        long num = Long.parseLong(str);
        System.out.println(num);
    }
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.parseLong(Long.java:631)

Both methods:

  • Long.parseLong("123")
  • Long.valueOf("123")

will throw java.lang.NumberFormatException if we try to parse anything else then:
digits or '+', '-' as first character.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more