Java Tutorial/Data Type/Long
Содержание
- 1 Add two long integers, checking for overflow.
- 2 A utility class for converting a long into a human readable string.
- 3 Compare Two Java long Arrays Example
- 4 Compute distance light travels using long variables
- 5 Convert from long to String
- 6 Convert from String to long
- 7 Convert Java String to Long example
- 8 Convert long primitive to Long object Example
- 9 Convert Long to numeric primitive data types example
- 10 Create a Long object
- 11 Format long with System.out.format
- 12 Gets the maximum of three long values.
- 13 Gets the minimum of three long values.
- 14 Java long Example: long is 64 bit signed type
- 15 Java Sort long Array Example
- 16 Long Integer Literal
- 17 Min and Max values of datatype long
- 18 Multiply two long integers, checking for overflow.
- 19 Subtract two long integers, checking for overflow.
- 20 Use toString method of Long class to convert Long into String.
Add two long integers, checking for overflow.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Add two long integers, checking for overflow.
*
* @param a an addend
* @param b an addend
* @return the sum <code>a+b</code>
* @throws ArithmeticException if the result can not be represented as an
* long
* @since 1.2
*/
public static long addAndCheck(long a, long b) {
return addAndCheck(a, b, "overflow: add");
}
/**
* Add two long integers, checking for overflow.
*
* @param a an addend
* @param b an addend
* @param msg the message to use for any thrown exception.
* @return the sum <code>a+b</code>
* @throws ArithmeticException if the result can not be represented as an
* long
* @since 1.2
*/
private static long addAndCheck(long a, long b, String msg) {
long ret;
if (a > b) {
// use symmetry to reduce boundry cases
ret = addAndCheck(b, a, msg);
} else {
// assert a <= b
if (a < 0) {
if (b < 0) {
// check for negative overflow
if (Long.MIN_VALUE - b <= a) {
ret = a + b;
} else {
throw new ArithmeticException(msg);
}
} else {
// oppisite sign addition is always safe
ret = a + b;
}
} else {
// assert a >= 0
// assert b >= 0
// check for positive overflow
if (a <= Long.MAX_VALUE - b) {
ret = a + b;
} else {
throw new ArithmeticException(msg);
}
}
}
return ret;
}
}
A utility class for converting a long into a human readable string.
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.io.Serializable;
/**
* TimeFormat is a utility class for converting a long into a human readable
* string.
*
*
*
* Example usage:
*
* <CODE> System.out.println("You have been online for:
* "+TimeFormat.valueOf(milliseconds)); </CODE>
*
* FIXME: expanded features need documentation. JGH
*
* @author
* @date $Date: 2008-11-14 07:45:28 -0500 (Fri, 14 Nov 2008) $
* @version $Revision: 81022 $
*/
public final class TimeFormat implements Serializable {
public static final boolean DEBUG = false;
public static final long ONE_MILLISECOND = (1);
public static final long ONE_SECOND = (ONE_MILLISECOND * 1000);
public static final long ONE_MINUTE = (ONE_SECOND * 60);
public static final long ONE_HOUR = (ONE_MINUTE * 60);
public static final long ONE_DAY = (ONE_HOUR * 24);
public static final int ROUND_TO_MILLISECOND = 5;
public static final int ROUND_TO_SECOND = 4;
public static final int ROUND_TO_MINUTE = 3;
public static final int ROUND_TO_HOUR = 2;
public static final int ROUND_TO_DAY = 1;
private long original = 0;
private long time = 0;
private long remainder = 0;
private long days = 0;
private long hours = 0;
private long minutes = 0;
private long seconds = 0;
private long milliseconds = 0;
private boolean micro = false;
private int rounding = ROUND_TO_SECOND;
/**
* construct a time format
*
*
* @param milliseconds
*/
private TimeFormat(long milliseconds, int round) {
this.rounding = round;
this.original = milliseconds;
if (milliseconds >= ONE_SECOND) {
this.remainder = milliseconds;
getTime();
} else {
micro = true;
// if less than second, we"ll just
// display
time = milliseconds;
}
}
/**
* construct a time format
*
*
* @param milliseconds
*/
private TimeFormat(long milliseconds) {
this(milliseconds, TimeFormat.ROUND_TO_MILLISECOND);
}
/**
* get days
*
* @return days
*/
public long getDays() {
return days;
}
/**
* get minutes
*
* @return minutes
*/
public long getMinutes() {
return minutes;
}
/**
* get hours
*
* @return hours
*/
public long getHours() {
return hours;
}
/**
* get seconds
*
* @return seconds
*/
public long getSeconds() {
return seconds;
}
/**
* add a timeformat
*
*
* @param t
*/
public void add(TimeFormat t) {
days += t.days;
hours += t.hours;
minutes += t.minutes;
seconds += t.seconds;
}
/**
* get days from a time format
*
*
* @param t
*/
public void getDays(TimeFormat t) {
if (t.remainder >= ONE_DAY) {
t.days = (t.remainder / ONE_DAY);
t.remainder -= (t.days * ONE_DAY);
}
}
/**
* get hours from a time format
*
*
* @param t
*/
public void getHours(TimeFormat t) {
if (t.remainder >= ONE_HOUR && t.remainder < ONE_DAY) {
t.hours = (t.remainder / ONE_HOUR);
t.remainder -= (t.hours * ONE_HOUR);
}
}
/**
* get minutes from a time format
*
*
* @param t
*/
public void getMinutes(TimeFormat t) {
if (t.remainder >= ONE_MINUTE && t.remainder < ONE_HOUR) {
t.minutes = (t.remainder / ONE_MINUTE);
t.remainder -= (t.minutes * ONE_MINUTE);
}
}
/**
* get seconds from a time format
*
*
* @param t
*/
public void getSeconds(TimeFormat t) {
if (t.remainder >= ONE_SECOND && t.remainder < ONE_MINUTE) {
t.seconds = (t.remainder / ONE_SECOND);
t.milliseconds = t.remainder -= (t.seconds * ONE_SECOND);
} else {
t.seconds = 0;
t.milliseconds = t.remainder;
}
}
/**
* update time
*
*
* @param t
*/
public void getTime(TimeFormat t) {
t.getTime();
}
/**
* update
*
*/
private void getTime() {
getDays(this);
getHours(this);
getMinutes(this);
getSeconds(this);
}
/**
* get the milliseconds
*/
public long getMilliseconds() {
return (micro ? time : milliseconds);
}
/**
* print out the time format in a string representation
*/
public String toString() {
return format(rounding);
}
/**
* set rounding - one of ROUND_TO_MILLISECONDS, etc.
*/
public void setRounding(int r) {
rounding = r;
}
/**
* return the rounding
*/
public int getRouding() {
return rounding;
}
/**
* format string based on rouding
*/
public String format(int round) {
if (DEBUG) {
System.err.println("-->time: " + time + ", round: " + round + ", micro: " + micro
+ ",remainder:" + remainder);
System.err.println("-->days: " + days);
System.err.println("-->hours: " + hours);
System.err.println("-->minutes: " + minutes);
System.err.println("-->hours: " + hours);
System.err.println("-->seconds: " + seconds);
System.err.println("-->milliseconds: " + milliseconds);
System.err.flush();
}
switch (round) {
case ROUND_TO_DAY: {
return formatDays(false);
}
case ROUND_TO_HOUR: {
return formatDays(true) + formatHours(false);
}
case ROUND_TO_MINUTE: {
return formatDays(true) + formatHours(true) + formatMinutes(false);
}
case ROUND_TO_SECOND: {
return formatDays(true) + formatHours(true) + formatMinutes(true) + formatSeconds(false);
}
case ROUND_TO_MILLISECOND: {
return formatDays(true) + formatHours(true) + formatMinutes(true) + formatSeconds(true)
+ (micro ? time : milliseconds) + " ms";
}
}
return original + " ms";
}
/**
* FIXME: Missing Method declaration
*
*
* @param empty
* @return
*/
private String formatDays(boolean empty) {
if (days <= 0) {
return empty ? "" : "0 days";
}
return format("day", "days", days);
}
/**
* FIXME: Missing Method declaration
*
*
* @param empty
* @return
*/
private String formatHours(boolean empty) {
if (hours <= 0) {
return empty ? "" : "0 hours";
}
return format("hour", "hours", hours);
}
/**
* FIXME: Missing Method declaration
*
*
* @param empty
* @return
*/
private String formatMinutes(boolean empty) {
if (minutes <= 0) {
return empty ? "" : "0 minutes";
}
return format("minute", "minutes", minutes);
}
/**
* FIXME: Missing Method declaration
*
*
* @param empty
* @return
*/
private String formatSeconds(boolean empty) {
if (seconds <= 0) {
return empty ? "" : "0 seconds";
}
return format("second", "seconds", seconds);
}
/**
* handle amt formatting
*/
private String format(String single, String plural, long amt) {
if (amt > 0) {
return amt + " " + (amt > 1 ? plural : single) + " ";
}
return "";
}
/**
* return a string formatted version of time <code>t</code> rounding to
* <code>round</code>
*
* @param t
* @param round
* @return String value
*/
public static String valueOf(long t, int round) {
TimeFormat f = new TimeFormat(t, round);
return f.toString();
}
/**
* return a string formatted version of time <code>t</code> rounding to
* <code>round</code>
*
* @param t
* @param round
* @return String value
*/
public static String valueOf(long t) {
return valueOf(t, TimeFormat.ROUND_TO_MILLISECOND);
}
/**
* format with a date time
*/
public static String format(String format, long time) {
TimeFormat f = new TimeFormat(time);
return f.parse(format, f.getDays(), f.getHours(), f.getMinutes(), f.getSeconds(), f
.getMilliseconds());
}
/**
* parse
*/
private String parse(String format, long day, long hour, long minute, long second, long millis) {
String s = "";
int start = 0;
int len = format.length();
for (int c = 0; c < len; c++) {
char tc = format.charAt(c);
int sc = c;
int l = 0;
switch (tc) {
case " ": {
s += " ";
break;
}
case "\"": {
while (++c < len && format.charAt(c) != "\"")
;
s += format.substring(sc + 1, c);
break;
}
case "D": // days
case "d":
while (++c < len && (format.charAt(c) == "d" || format.charAt(c) == "D"))
;
l = c - sc;
s += sc <= 0 || start < 0 ? "" : format.substring(start, sc);
s += zeroPad(day, l - 1);
--c;
break;
case "h": // hours
case "H":
while (++c < len && (format.charAt(c) == "h" || format.charAt(c) == "H"))
;
l = c - sc;
s += sc <= 0 || start < 0 ? "" : format.substring(start, sc);
s += zeroPad(hour, l - 1);
--c;
break;
case "m": // minutes
case "M":
while (++c < len && (format.charAt(c) == "m" || format.charAt(c) == "M"))
;
l = c - sc;
s += sc <= 0 || start < 0 ? "" : format.substring(start, sc);
s += zeroPad(minute, l - 1);
--c;
break;
case "s": // seconds
case "S":
while (++c < len && (format.charAt(c) == "s" || format.charAt(c) == "S"))
;
l = c - sc;
s += sc <= 0 || start < 0 ? "" : format.substring(start, sc);
s += zeroPad(second, l - 1);
--c;
break;
case "z": // milliseconds
case "Z":
while (++c < len && (format.charAt(c) == "z" || format.charAt(c) == "Z"))
;
l = c - sc;
s += sc <= 0 || start < 0 ? "" : format.substring(start, sc);
s += zeroPad(millis, l - 1);
--c;
break;
}
start = c + 1;
}
return s;
}
/**
* zero pad a number to len
*/
private String zeroPad(long value, int len) {
String s = String.valueOf(value);
int l = s.length();
String r = "";
for (int c = l; c <= len; c++) {
r += "0";
}
return r + s;
}
/**
* test
*
*
* @param args
*/
public static void main(String args[]) {
String FORMAT = "D "days," HH "hours," mm "minutes and " ss "seconds, "zz "milliseconds"";
System.out.println(TimeFormat.format(FORMAT, 1000));
System.out.println("ONE SECOND: " + TimeFormat.ONE_SECOND);
System.out.println("ONE MINUTE: " + TimeFormat.ONE_MINUTE);
System.out.println("ONE HOUR: " + TimeFormat.ONE_HOUR);
System.out.println("ONE DAY: " + TimeFormat.ONE_DAY);
for (int c = 0; c <= 5; c++) {
System.out.println("Round to: " + c);
System.out.println("Time: " + TimeFormat.valueOf(Long.MAX_VALUE, c));
System.out.println("Time: " + TimeFormat.valueOf(1236371400, c));
System.out.println("Time: " + TimeFormat.format(FORMAT, 1236371400));
System.out.println("Time: " + TimeFormat.valueOf(123613700, c));
System.out.println("Time: " + TimeFormat.valueOf(700, c));
System.out.println("Time: " + TimeFormat.valueOf(2001, c));
System.out.println("Time: " + TimeFormat.valueOf(2101, c));
System.out.println("Time: " + TimeFormat.valueOf(15, c));
System.out.println("Time: " + TimeFormat.valueOf(999, c));
System.out.println("Time: " + TimeFormat.valueOf(10000, c));
System.out.println("Time: " + TimeFormat.valueOf(ONE_MINUTE * 10, c));
System.out.println("Time: " + TimeFormat.valueOf(ONE_DAY * 10 + 101, c));
System.out.println("Time: " + TimeFormat.valueOf(ONE_HOUR * 10, c));
System.out.println("Time: " + TimeFormat.valueOf(ONE_HOUR + ONE_DAY + (ONE_MINUTE * 2), c));
System.out.println("Time: "
+ TimeFormat.format(FORMAT, ONE_HOUR + ONE_DAY + (ONE_MINUTE * 2)));
}
}
}
/**
* $Log: 1 Head - DO NOT USE1.0 12/3/01 2:51:16 PM jhaynie $ Revision 1.2
* 2001/08/31 22:04:24 jhaynie added parsing and formatting features
*
* Revision 1.1 2001/08/29 19:47:53 jhaynie initial checkin
*
*/
Compare Two Java long Arrays Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
long[] a1 = new long[] { 2, 8, 3 };
long[] a2 = new long[] { 2, 8, 3 };
System.out.println(Arrays.equals(a1, a2));
}
}
Compute distance light travels using long variables
public class MainClass {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
In 1000 days light will travel about 16070400000000 miles
Convert from long to String
public class Main {
public static void main(String[] args) throws Exception {
String str = Long.toString(2L);
}
}
Convert from String to long
public class Main {
public static void main(String[] args) throws Exception {
String str = "0.5";
long l = Long.valueOf(str).longValue();
// or
Long L = Long.parseLong(str);
}
}
Convert Java String to Long example
public class Main {
public static void main(String[] args) {
Long lObj1 = new Long("100");
System.out.println(lObj1);
String str = "100";
Long lObj2 = Long.valueOf(str);
System.out.println(lObj2);
}
}
Convert long primitive to Long object Example
public class Main {
public static void main(String[] args) {
long i = 10;
Long lObj = new Long(i);
System.out.println(lObj);
}
}
Convert Long to numeric primitive data types example
public class Main {
public static void main(String[] args) {
Long lObj = new Long("10");
byte b = lObj.byteValue();
System.out.println(b);
short s = lObj.shortValue();
System.out.println(s);
int i = lObj.intValue();
System.out.println(i);
float f = lObj.floatValue();
System.out.println(f);
double d = lObj.doubleValue();
System.out.println(d);
}
}
Create a Long object
public class Main {
public static void main(String[] args) {
long l = 10;
Long longObj1 = new Long(l);
Long longObj2 = new Long("5");
System.out.println(longObj1);
System.out.println(longObj2);
}
}
Format long with System.out.format
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n);
System.out.format("%08d%n", n);
System.out.format("%+8d%n", n);
System.out.format("%,8d%n", n);
System.out.format("%+,8d%n%n", n);
double pi = Math.PI;
System.out.format("%f%n", pi);
System.out.format("%.3f%n", pi);
System.out.format("%10.3f%n", pi);
System.out.format("%-10.3f%n", pi);
System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi);
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c);
System.out.format("%tl:%tM %tp%n", c, c, c);
System.out.format("%tD%n", c);
}
}
Gets the maximum of three long values.
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides extra functionality for Java Number classes.
*
* @author
* @author Eric Pugh
* @author Phil Steitz
* @since 1.0
* @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z bayard $
*
*/
public class Main {
/**
* Gets the maximum of three <code>long</code> values.
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static long maximum(long a, long b, long c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
}
Gets the minimum of three long values.
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides extra functionality for Java Number classes.
*
* @author
* @author Eric Pugh
* @author Phil Steitz
* @since 1.0
* @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z bayard $
*
*/
public class Main {
//--------------------------------------------------------------------
/**
* Gets the minimum of three <code>long</code> values.
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static long minimum(long a, long b, long c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
}
Java long Example: long is 64 bit signed type
import java.util.Date;
public class Main {
public static void main(String[] args) {
long timeInMilliseconds = new Date().getTime();
System.out.println("Time in milliseconds is : " + timeInMilliseconds);
}
}
//Time in milliseconds is : 1235149879683
Java Sort long Array Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
long[] l1 = new long[] { 3L, 2L, 5L, 4L, 1L };
for (long l: l1){
System.out.print(" " + l);
}
Arrays.sort(l1);
for (long l: l1){
System.out.print(" " + l);
}
long[] l2 = new long[] { 5, 2, 3, 1, 4 };
Arrays.sort(l2, 1, 4);
for (long l: l2){
System.out.print(" " + l);
}
}
}
Long Integer Literal
Append an L to the value to define an integer of type long.
public class MainClass {
public static void main(String[] a){
long longValue = 123456789L;
System.out.println(longValue);
}
}
123456789
Min and Max values of datatype long
public class Main {
public static void main(String[] args) {
System.out.println(Long.MIN_VALUE);
System.out.println(Long.MAX_VALUE);
}
}
/*
-9223372036854775808
9223372036854775807
*/
Multiply two long integers, checking for overflow.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Multiply two long integers, checking for overflow.
*
* @param a first value
* @param b second value
* @return the product <code>a * b</code>
* @throws ArithmeticException if the result can not be represented as an
* long
* @since 1.2
*/
public static long mulAndCheck(long a, long b) {
long ret;
String msg = "overflow: multiply";
if (a > b) {
// use symmetry to reduce boundry cases
ret = mulAndCheck(b, a);
} else {
if (a < 0) {
if (b < 0) {
// check for positive overflow with negative a, negative b
if (a >= Long.MAX_VALUE / b) {
ret = a * b;
} else {
throw new ArithmeticException(msg);
}
} else if (b > 0) {
// check for negative overflow with negative a, positive b
if (Long.MIN_VALUE / b <= a) {
ret = a * b;
} else {
throw new ArithmeticException(msg);
}
} else {
// assert b == 0
ret = 0;
}
} else if (a > 0) {
// assert a > 0
// assert b > 0
// check for positive overflow with positive a, positive b
if (a <= Long.MAX_VALUE / b) {
ret = a * b;
} else {
throw new ArithmeticException(msg);
}
} else {
// assert a == 0
ret = 0;
}
}
return ret;
}
}
Subtract two long integers, checking for overflow.
import java.math.BigDecimal;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Subtract two long integers, checking for overflow.
*
* @param a first value
* @param b second value
* @return the difference <code>a-b</code>
* @throws ArithmeticException if the result can not be represented as an
* long
* @since 1.2
*/
public static long subAndCheck(long a, long b) {
long ret;
String msg = "overflow: subtract";
if (b == Long.MIN_VALUE) {
if (a < 0) {
ret = a - b;
} else {
throw new ArithmeticException(msg);
}
} else {
// use additive inverse
ret = addAndCheck(a, -b, msg);
}
return ret;
}
/**
* Add two long integers, checking for overflow.
*
* @param a an addend
* @param b an addend
* @param msg the message to use for any thrown exception.
* @return the sum <code>a+b</code>
* @throws ArithmeticException if the result can not be represented as an
* long
* @since 1.2
*/
private static long addAndCheck(long a, long b, String msg) {
long ret;
if (a > b) {
// use symmetry to reduce boundry cases
ret = addAndCheck(b, a, msg);
} else {
// assert a <= b
if (a < 0) {
if (b < 0) {
// check for negative overflow
if (Long.MIN_VALUE - b <= a) {
ret = a + b;
} else {
throw new ArithmeticException(msg);
}
} else {
// oppisite sign addition is always safe
ret = a + b;
}
} else {
// assert a >= 0
// assert b >= 0
// check for positive overflow
if (a <= Long.MAX_VALUE - b) {
ret = a + b;
} else {
throw new ArithmeticException(msg);
}
}
}
return ret;
}
}
Use toString method of Long class to convert Long into String.
public class Main {
public static void main(String[] args) {
Long lObj = new Long(10);
String str = lObj.toString();
System.out.println("Long converted to String as " + str);
}
}