Java/Data Type/long
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Add two long integers, checking for overflow.
- 2 A utility class for converting a long into a human readable string.
- 3 Calculate factorial of integers up to this value
- 4 Compare Two Java long Arrays Example
- 5 Compute prime numbers
- 6 Convert bytes to megabytes
- 7 Convert from long to String
- 8 Convert from String to long
- 9 Converting a String to a long type Number
- 10 Convert Java String to Long example
- 11 Convert long primitive to Long object Example
- 12 Convert Long to numeric primitive data types example
- 13 Convert String to long Example
- 14 Create a Long object
- 15 Gets the maximum of three long values.
- 16 Gets the minimum of three long values.
- 17 Java long Example: long is 64 bit signed type
- 18 Java Sort long Array Example
- 19 Long class creates primitives that wrap themselves around data items of the long data type
- 20 Min and Max values of datatype long
- 21 Returns the sign for long value x
- 22 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.
*
* <P>
*
* 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
*
*/
Calculate factorial of integers up to this value
public class Factorial {
public static void main(String[] args) {
long limit = 20;
long factorial = 1;
for (int i = 1; i <= limit; i++) {
factorial = 1; // Initialize factorial
int j = 2;
while (j <= i)
factorial *= j++;
System.out.println(i + "!" + " is " + factorial);
}
}
}
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 prime numbers
/* Compute prime numbers, after Knuth, Vol 1, Sec 1.3.2, Alg. "P".
* Unlike Knuth, I don"t build table formatting into
* computational programs; output is one per line.
* <p>
* Note that there may be more efficient algorithms for finding primes.
* Consult a good book on numerical algorithms.
* @author Ian Darwin
*/
public class Primes {
/** The default stopping point for primes */
public static final long DEFAULT_STOP = 4294967295L;
/** The first prime number */
public static final int FP = 2;
static int MAX = 10000;
public static void main(String[] args) {
long[] prime = new long[MAX];
long stop = DEFAULT_STOP;
if (args.length == 1) {
stop = Long.parseLong(args[0]);
}
prime[1] = FP; // P1 (ignore prime[0])
long n = FP+1; // odd candidates
int j = 1; // numberFound
boolean isPrime = true; // for 3
do {
if (isPrime) {
if (j == MAX-1) {
// Grow array dynamically if needed
long[] np = new long[MAX * 2];
System.arraycopy(prime, 0, np, 0, MAX);
MAX *= 2;
prime = np;
}
prime[++j] = n; // P2
isPrime = false;
}
n += 2; // P4
for (int k = 2; k <= j && k < MAX; k++) { // P5, P6, P8
long q = n / prime[k];
long r = n % prime[k];
if (r == 0) {
break;
}
if (q <= prime[k]) { // P7
isPrime = true;
break;
}
}
} while (n < stop); // P3
for (int i=1; i<=j; i++)
System.out.println(prime[i]);
}
}
Convert bytes to megabytes
public class Main {
public static void main(String args[]) {
long l = 9999999990L;
long MEGABYTE = 1024L * 1024L;
long b = l / MEGABYTE;
System.out.println(b + " Mb");
}
}
//
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);
}
}
Converting a String to a long type Number
public class Main {
public static void main(String[] argv) throws Exception {
long l = Long.parseLong("123");
System.out.println(l);
}
}
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);
}
}
Convert String to long Example
public class Main {
public static void main(String[] args) {
String str = new String("10");
long l = Long.parseLong(str);
System.out.println(l);
}
}
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);
}
}
Gets the maximum of three long values.
/*
* 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Gets the maximum of three <code>long</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static long max(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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @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 {
//--------------------------------------------------------------------
/**
* <p>Gets the minimum of three <code>long</code> values.</p>
*
* @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 class creates primitives that wrap themselves around data items of the long data type
public class MainClass {
public static void main(String[] args) {
long l = 10000000l;
Long l2 = new Long(l);
System.out.println(l2.longValue());
}
}
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
*/
Returns the sign for long value x
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 {
/**
* Returns the
* for long value <code>x</code>.
* <p>
* For a long value x, this method returns +1L if x > 0, 0L if x = 0, and
* -1L if x < 0.</p>
*
* @param x the value, a long
* @return +1L, 0L, or -1L, depending on the sign of x
*/
public static long sign(final long x) {
return (x == 0L) ? 0L : (x > 0L) ? 1L : -1L;
}
}
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);
}
}