Sie sind auf Seite 1von 41

2.

Data Type

2. 1. Data Type Introduction( 11 ) 2. 25. Extracting String Characters( 8 )

2. 2. Boolean( 24 ) 2. 26. Quote( 1 )

2. 3. Integer Data Type( 12 ) 2. 27. String vs Byte Array( 11 )

2. 4. Byte( 18 ) 2. 28. String vs Char Array( 19 )

2. 5. Short( 13 ) 2. 29. String Find Search( 21 )

2. 6. Integer( 43 ) 2. 30. String Format( 38 )

2. 7. Character Data Type( 42 ) 2. 31. String Match( 20 )

2. 8. Long( 20 ) 2. 32. String Split( 11 )

2. 9. Hex Oct( 24 ) 2. 33. String Join( 11 )

2. 10. Float Point Data Type( 5 ) 2. 34. Substring( 15 )

2. 11. Float( 24 ) 2. 35. Escape Sequences( 6 )

2. 12. Double( 23 ) 2. 36. Convert from String( 13 )

2. 13. Number( 5 ) 2. 37. Convert to String( 16 )

2. 14. Number Format( 14 ) 2. 38. Date( 15 )

2. 15. Cast( 2 ) 2. 39. Calendar( 23 )

2. 16. Data Type Conversion( 13 ) 2. 40. Gregorian Calendar( 18 )

2. 17. Wrapper Classes( 6 ) 2. 41. Date Format( 43 )

2. 18. Autobox Unbox( 13 ) 2. 42. Date Calculation( 54 )

2. 19. String( 22 ) 2. 43. enum( 10 )

2. 20. String Start End( 6 ) 2. 44. enum methods( 9 )

2. 21. String Replace( 18 ) 2. 45. BigInteger( 43 )

2. 22. String Concatenation( 9 ) 2. 46. BigDecimal( 13 )

2. 23. String Compare( 12 ) 2. 47. Decimal( 20 )

2. 24. String Tokenize( 3 )


2. 1. Data Type Introduction

2. 1. 1. The Primitive Types

2. 1. 2. Size for Java's Primitive Types

2. 1. 3. Default values for primitives and references

2. 1. 4. Literals

2. 1. 5. Surprise! Java lets you overflow

Wrapping a Primitive Type in a Wrapper Object: boolean,


2. 1. 6.
byte, char, short, int, long, float, double

Print the limits of primitive types (e.g. byte, short, int ...) in
2. 1. 7.
Java

Get the minimum and maximum value of a primitive data


2. 1. 8.
types

2. 1. 9. Shows default initial values

2. 1. 10. Primitive utilities

Return primitive type the passed in wrapper type


2. 1. 11.
corresponds to

2. 1. 1. The Primitive Types

Java has eight primitive types of data: byte, short, int, long, char, float, double, and boolean.

These can be put in four groups:

Integers includes byte, short, int, and long

Floating-point numbers includes float and double

Characters includes char, like letters and numbers.

Boolean includes boolean representing true/false values.

byte

The smallest integer type


a range from -128 to 127.
useful when working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword.
byte b, c;

int

The most commonly used integer type


a signed 32-bit type
Ranging from -2,147,483,648 to 2,147,483,647
used to control loops and to index arrays.
the most efficient type

long

a signed 64-bit type

2. 1. 2. Size for Java's Primitive Types

Type Explanation

int A 32-bit (4-byte) integer value

short A 16-bit (2-byte) integer value

long A 64-bit (8-byte) integer value

byte An 8-bit (1-byte) integer value

float A 32-bit (4-byte) floating-point value

double A 64-bit (8-byte) floating-point value

char A 16-bit character using the Unicode encoding scheme

boolean A true or false value

2. 1. 3. Default values for primitives and references

Type Default Value

boolean false

byte 0

short 0

int 0

long 0L

char \u0000

float 0.0f
double 0.0d

object reference null

public class ClassInitializer1 {


static boolean bool;
static byte by;
static char ch;
static double d;
static float f;
static int i;
static long l;
static short sh;
static String str;

public static void main(String[] args) {


System.out.println("bool = " + bool);
System.out.println("by = " + by);
System.out.println("ch = " + ch);
System.out.println("d = " + d);
System.out.println("f = " + f);
System.out.println("i = " + i);
System.out.println("l = " + l);
System.out.println("sh = " + sh);
System.out.println("str = " + str);
}
}

2. 1. 4. Literals

public class MainClass {


char c = 0xffff; // max char hex value

byte b = 0x7f; // max byte hex value

short s = 0x7fff; // max short hex value

int i1 = 0x2f; // Hexadecimal (lowercase)

int i2 = 0X2F; // Hexadecimal (uppercase)

int i3 = 0177; // Octal (leading zero)

// Hex and Oct also work with long.


long n1 = 200L; // long suffix

long n2 = 200l; // long suffix (but can be confusing)

long n3 = 200;

// ! long l6(200); // not allowed


float f1 = 1;

float f2 = 1F; // float suffix

float f3 = 1f; // float suffix


float f4 = 1e-45f; // 10 to the power

float f5 = 1e+9f; // float suffix

double d1 = 1d; // double suffix

double d2 = 1D; // double suffix

double d3 = 47e47d; // 10 to the power


}

2. 1. 5. Surprise! Java lets you overflow

public class MainClass {

public static void main(String[] args) {


int big = 0x7fffffff; // max int value
System.out.println("big = " + big);
int bigger = big * 4;
System.out.println("bigger = " + bigger);
}
}

big = 2147483647
bigger = -4

2. 1. 6. Wrapping a Primitive Type in a Wrapper Object: boolean, byte,


char, short, int, long, float, double

public class Main {


public static void main(String[] argv) throws Exception {
Boolean refBoolean = new Boolean(true);
boolean bool = refBoolean.booleanValue();

Byte refByte = new Byte((byte) 123);


byte b = refByte.byteValue();

Character refChar = new Character('x');


char c = refChar.charValue();

Short refShort = new Short((short) 123);


short s = refShort.shortValue();

Integer refInt = new Integer(123);


int i = refInt.intValue();
Long refLong = new Long(123L);
long l = refLong.longValue();

Float refFloat = new Float(12.3F);


float f = refFloat.floatValue();

Double refDouble = new Double(12.3D);


double d = refDouble.doubleValue();
}
}

2. 1. 7. Print the limits of primitive types (e.g. byte, short, int ...) in Java

public class Main {


public static void main(String args[]) {

System.out.println("Min byte value = " + Byte.MIN_VALUE);


System.out.println("Max byte value = " + Byte.MAX_VALUE);
System.out.println("Min short value = " + Short.MIN_VALUE);
System.out.println("Max short value = " + Short.MAX_VALUE);
System.out.println("Min int value = " + Integer.MIN_VALUE);
System.out.println("Max int value = " + Integer.MAX_VALUE);
System.out.println("Min float value = " + Float.MIN_VALUE);
System.out.println("Max float value = " + Float.MAX_VALUE);
System.out.println("Min double value = " + Double.MIN_VALUE);
System.out.println("Max double value = " + Double.MAX_VALUE);
}
}

2. 1. 8. Get the minimum and maximum value of a primitive data types

public class Main {


public static void main(String[] args) {
System.out.println("Byte.MIN = " + Byte.MIN_VALUE);
System.out.println("Byte.MAX = " + Byte.MAX_VALUE);
System.out.println("Short.MIN = " + Short.MIN_VALUE);
System.out.println("Short.MAX = " + Short.MAX_VALUE);
System.out.println("Integer.MIN = " + Integer.MIN_VALUE);
System.out.println("Integer.MAX = " + Integer.MAX_VALUE);
System.out.println("Long.MIN = " + Long.MIN_VALUE);
System.out.println("Long.MAX = " + Long.MAX_VALUE);
System.out.println("Float.MIN = " + Float.MIN_VALUE);
System.out.println("Float.MAX = " + Float.MAX_VALUE);
System.out.println("Double.MIN = " + Double.MIN_VALUE);
System.out.println("Double.MAX = " + Double.MAX_VALUE);
}
}

2. 1. 9. Shows default initial values


public class MainClass {
boolean t;

char c;

byte b;

short s;

int i;

long l;

float f;

double d;

void print(String s) {
System.out.println(s);
}

void printInitialValues() {
print("Data type Initial value");
print("boolean " + t);
print("char [" + c + "]");
print("byte " + b);
print("short " + s);
print("int " + i);
print("long " + l);
print("float " + f);
print("double " + d);
}

public static void main(String[] args) {


MainClass iv = new MainClass();
iv.printInitialValues();
}
}

Data type Initial value


boolean false
char []
byte 0
short 0
int 0
long 0
float 0.0
double 0.0
2. 1. 10. Primitive utilities

/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt 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.
*/

/**
* Primitive utilities.
*
* @version <tt>$Revision: 1958 $</tt>
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
*/
public final class Primitives {
/**
* Get a Boolean from a boolean, equivalent to the java 1.4 method
* Boolean.valueOf(boolean)
*
* @param value
* the boolean
* @return the Boolean equivalent
*/
public static Boolean valueOf(boolean value) {
if (value)
return Boolean.TRUE;
else
return Boolean.FALSE;
}

/**
* Test the equality of two doubles by converting their values into IEEE 754
* floating-point "double format" long values.
*
* @param a
* Double to check equality with.
* @param b
* Double to check equality with.
* @return True if a equals b.
*/
public static boolean equals(final double a, final double b) {
return Double.doubleToLongBits(a) == Double.doubleToLongBits(b);
}

/**
* Test the equality of two doubles by converting their values into IEEE 754
* floating-point "single precision" bit layouts.
*
* @param a
* Float to check equality with.
* @param b
* Float to check equality with.
* @return True if a equals b.
*/
public static boolean equals(final float a, final float b) {
return Float.floatToIntBits(a) == Float.floatToIntBits(b);
}

/**
* Test the equality of a given sub-section of two byte arrays.
*
* @param a
* The first byte array.
* @param abegin
* The begining index of the first byte array.
* @param b
* The second byte array.
* @param bbegin
* The begining index of the second byte array.
* @param length
* The length of the sub-section.
* @return True if sub-sections are equal.
*/
public static boolean equals(final byte a[], final int abegin, final byte b[], final int bbegi
final int length) {
try {
int i = length;
while (--i >= 0) {
if (a[abegin + i] != b[bbegin + i]) {
return false;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}

return true;
}

/**
* Test the equality of two byte arrays.
*
* @param a
* The first byte array.
* @param b
* The second byte array.
* @return True if the byte arrays are equal.
*/
public static boolean equals(final byte a[], final byte b[]) {
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.length != b.length)
return false;

try {
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}

return true;
}

2. 1. 11. Return primitive type the passed in wrapper type corresponds to

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt 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.
*/

public class Main {


/**
* @param wrapper
* a primitive wrapper type
* @return primitive type the passed in wrapper type corresponds to
*/
public static Class getPrimitive(Class wrapper) {
Class primitive;
if (Integer.class == wrapper) {
primitive = int.class;
} else if (Long.class == wrapper) {
primitive = long.class;
} else if (Double.class == wrapper) {
primitive = double.class;
} else if (Boolean.class == wrapper) {
primitive = boolean.class;
} else if (Short.class == wrapper) {
primitive = short.class;
} else if (Float.class == wrapper) {
primitive = float.class;
} else if (Byte.class == wrapper) {
primitive = byte.class;
} else if (Character.class == wrapper) {
primitive = char.class;
} else {
throw new IllegalArgumentException("The class is not a primitive wrapper type: " + wrapper
}
return primitive;
}
}

2. 2. Boolean
2. 2. 1. java.lang.Boolean

2. 2. 2. Java boolean value

2. 2. 3. Boolean Data Type

2. 2. 4. Boolean Literals

2. 2. 5. Boolean Variables

2. 2. 6. Using the boolean type

2. 2. 7. valueOf(): parse a String to a Boolean object

2. 2. 8. toString(): return the string representation of a boolean

2. 2. 9. Convert String to Boolean

2. 2. 10. Convert Boolean to String

2. 2. 11. Convert Java boolean Primitive to Boolean object

2. 2. 12. Convert Java String Object to Boolean Object

2. 2. 13. Create an Boolean object from boolean value

2. 2. 14. Compare Two Java boolean Arrays Example

2. 2. 15. Convert integer to boolean

2. 2. 16. Convert boolean to integer

2. 2. 17. Convert boolean value to Boolean


2. 2. 18. Create a boolean variable from string

2. 2. 19. Autoboxing/unboxing a Boolean and Character.

2. 2. 20. Converts a String to a Boolean.

2. 2. 21. Converts a boolean to a String returning 'yes' or 'no'

2. 2. 22. Converts an Integer to a boolean specifying the conversion values.

2. 2. 23. Converts an int to a boolean specifying the conversion values.

2. 2. 24. Performs an xor on a set of booleans.

2. 2. 1. java.lang.Boolean

The java.lang.Boolean class wraps a boolean. You can construct a Boolean object from a boolean or a String
using one of these constructors.
public Boolean (boolean value)
public Boolean (String value)

For example:
Boolean b1 = new Boolean (false);
Boolean b2 = new Boolean ("true");

To convert a Boolean to a boolean, use its booleanValue method: public boolean booleanValue()
public class MainClass {

public static void main(String[] args) {


Boolean b1 = new Boolean(false);
Boolean b2 = new Boolean("true");

System.out.println(b1.booleanValue());
System.out.println(b2.booleanValue());
}

false
true

2. 2. 2. Java boolean value

public class Main {


public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
boolean b3 = (10 > 2) ? true : false;
System.out.println("Value of boolean variable b1 is :" + b1);
System.out.println("Value of boolean variable b2 is :" + b2);
System.out.println("Value of boolean variable b3 is :" + b3);
}
}
/*
Value of boolean variable b1 is :true
Value of boolean variable b2 is :false
Value of boolean variable b3 is :true
*/

2. 2. 3. Boolean Data Type

public class Main {


public static void main(String[] args) {
boolean t = true;
System.out.println("t is " + t);

int x = 10;
boolean y = (x > 15);
System.out.println("y is " + y);
}
}

2. 2. 4. Boolean Literals

The boolean type has two values, represented by literals 'true' and 'false'.
The following code declares a boolean variable includeSign and assigns it the value of true.
public class MainClass {

public static void main(String[] args) {


boolean includeSign = true;

System.out.println(includeSign);
}

2. 2. 5. Boolean Variables

1. Variables of type boolean can have only one of two values, true or false.
2. The values 'true' and 'false' are boolean literals.
3.

public class MainClass{

public static void main(String[] arg){


boolean state = true;
state = false;
System.out.println(state);
}
}

false

2. 2. 6. Using the boolean type

public class MainClass {


public static void main(String args[]) {
boolean b;

b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);

// a boolean value can control the if statement


if(b) System.out.println("This is executed.");

b = false;
if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value


System.out.println("10 > 9 is " + (10 > 9));
}
}

b is false
b is true
This is executed.
10 > 9 is true

2. 2. 7. valueOf(): parse a String to a Boolean object

The static method valueOf parses a String to a Boolean object: public static Boolean valueOf (String string)
public class MainClass {

public static void main(String[] args) {


Boolean b = Boolean.valueOf("true");
System.out.println(b);
}

true

2. 2. 8. toString(): return the string representation of a boolean


The static method toString() returns the string representation of a boolean: public static String toString (boolea
boolean)
public class MainClass {

public static void main(String[] args) {


Boolean b = Boolean.valueOf("true");
System.out.println(b.toString());
}

true

2. 2. 9. Convert String to Boolean

public class Main {


public static void main(String[] args) {
String strBoolean = "true";

//String to boolean conversion


boolean theValue = Boolean.parseBoolean(strBoolean);

System.out.println(theValue);
}
}
//true

2. 2. 10. Convert Boolean to String

public class Main {

public static void main(String[] args) {


boolean theValue = true;

//boolean to String conversion


String theValueAsString = new Boolean(theValue).toString();

System.out.println(theValueAsString);
}
}
//true

2. 2. 11. Convert Java boolean Primitive to Boolean object

public class Main {


public static void main(String[] args) {
boolean b = true;
// using constructor
Boolean blnObj1 = new Boolean(b);
// using valueOf method of Boolean class.
Boolean blnObj2 = Boolean.valueOf(b);
}
}

2. 2. 12. Convert Java String Object to Boolean Object

public class Main {


public static void main(String[] args) {
String str = "false";
// Convert using constructor
Boolean blnObj1 = new Boolean(str);
System.out.println(blnObj1);

// Use valueOf method of Boolean class. This is a static method.


Boolean blnObj2 = Boolean.valueOf(str);
System.out.println(blnObj2);
}
}

2. 2. 13. Create an Boolean object from boolean value

public class Main {

public static void main(String[] args) {

Boolean blnObj1 = new Boolean(true);


Boolean blnObj2 = new Boolean("false");
System.out.println(blnObj1);
System.out.println(blnObj2);
}
}
/*
true
false
*/

2. 2. 14. Compare Two Java boolean Arrays Example

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
boolean[] a1 = new boolean[] { true, false, true };
boolean[] a2 = new boolean[] { true, false, true };
System.out.println(Arrays.equals(a1, a2));
}
}

2. 2. 15. Convert integer to boolean


public class Main {
public static void main(String[] args) throws Exception {
int i=10;
boolean b = (i != 0);

System.out.println(b);
}
}
//true

2. 2. 16. Convert boolean to integer

public class Main {


public static void main(String[] args) throws Exception {
boolean b = true;
int i = (b) ? 1 : 0;
}
}

2. 2. 17. Convert boolean value to Boolean

public class Main {


public static void main(String[] args) {
boolean b = true;
Boolean bool = Boolean.valueOf(b);
System.out.println("bool = " + bool);

if (bool.equals(Boolean.TRUE)) {
System.out.println("bool = " + bool);
}

String s = "false";

Boolean bools = Boolean.valueOf(s);


System.out.println("bools = " + bools);

String f = "abc";
Boolean abc = Boolean.valueOf(f);
System.out.println("abc = " + abc);
}
}

2. 2. 18. Create a boolean variable from string

public class Main {


public static void main(String[] args) {
// Parsing string "true" will result boolean true
boolean boolA = Boolean.parseBoolean("true");
System.out.println("boolA = " + boolA);

// Parsing string "TRUE" also resutl boolean true


boolean boolB = Boolean.parseBoolean("TRUE");
System.out.println("boolB = " + boolB);

}
}

2. 2. 19. Autoboxing/unboxing a Boolean and Character.

class AutoBox5 {
public static void main(String args[]) {

Boolean b = true;

if (b)
System.out.println("b is true");

Character ch = 'x'; // box a char


char ch2 = ch; // unbox a char

System.out.println("ch2 is " + ch2);


}
}

2. 2. 20. Converts a String to a Boolean.

/*
* 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.
*/

/**
* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/
public class Main {
/**
* Converts a String to a Boolean.
*
* <code>'true'</code>, <code>'on'</code> or <code>'yes'</code>
* (case insensitive) will return <code>true</code>.
* <code>'false'</code>, <code>'off'</code> or <code>'no'</code>
* (case insensitive) will return <code>false</code>.
* Otherwise, <code>null</code> is returned.</p>
*
* <pre>
* BooleanUtils.toBooleanObject(null) = null
* BooleanUtils.toBooleanObject("true") = Boolean.TRUE
* BooleanUtils.toBooleanObject("false") = Boolean.FALSE
* BooleanUtils.toBooleanObject("on") = Boolean.TRUE
* BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
* BooleanUtils.toBooleanObject("off") = Boolean.FALSE
* BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
* BooleanUtils.toBooleanObject("blue") = null
* </pre>
*
* @param str the String to check
* @return the Boolean value of the string,
* <code>null</code> if no match or <code>null</code> input
*/
public static Boolean toBooleanObject(String str) {
if ("true".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("false".equalsIgnoreCase(str)) {
return Boolean.FALSE;
} else if ("on".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("off".equalsIgnoreCase(str)) {
return Boolean.FALSE;
} else if ("yes".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("no".equalsIgnoreCase(str)) {
return Boolean.FALSE;
}
// no match
return null;
}
}

2. 2. 21. Converts a boolean to a String returning 'yes' or 'no'

/*
* 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.
*/

/**
* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/
public class Main {
/**
* Converts a boolean to a String returning <code>'yes'</code>
* or <code>'no'</code>.
*
* <pre>
* BooleanUtils.toStringYesNo(true) = "yes"
* BooleanUtils.toStringYesNo(false) = "no"
* </pre>
*
* @param bool the Boolean to check
* @return <code>'yes'</code>, <code>'no'</code>,
* or <code>null</code>
*/
public static String toStringYesNo(boolean bool) {
return toString(bool, "yes", "no");
}

/**
* Converts a boolean to a String returning one of the input Strings.
*
* <pre>
* BooleanUtils.toString(true, "true", "false") = "true"
* BooleanUtils.toString(false, "true", "false") = "false"
* </pre>
*
* @param bool the Boolean to check
* @param trueString the String to return if <code>true</code>,
* may be <code>null</code>
* @param falseString the String to return if <code>false</code>,
* may be <code>null</code>
* @return one of the two input Strings
*/
public static String toString(boolean bool, String trueString, String falseString) {
return bool ? trueString : falseString;
}
}

2. 2. 22. Converts an Integer to a boolean specifying the conversion


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.
*/

/**
* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/
public class Main {

/**
* Converts an Integer to a boolean specifying the conversion values.
*
* <pre>
* BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false
* BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true
* BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false
* BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true
* BooleanUtils.toBoolean(null, null, new Integer(0)) = true
* </pre>
*
* @param value the Integer to convert
* @param trueValue the value to match for <code>true</code>,
* may be <code>null</code>
* @param falseValue the value to match for <code>false</code>,
* may be <code>null</code>
* @return <code>true</code> or <code>false</code>
* @throws IllegalArgumentException if no match
*/
public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {
if (value == null) {
if (trueValue == null) {
return true;
} else if (falseValue == null) {
return false;
}
} else if (value.equals(trueValue)) {
return true;
} else if (value.equals(falseValue)) {
return false;
}
// no match
throw new IllegalArgumentException("The Integer did not match either specified value")
;
}
}

. 2. 23. Converts an int to a boolean specifying the conversion 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.
*/

/**
* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/
public class Main {
/**
* Converts an int to a boolean specifying the conversion values.
*
* <pre>
* BooleanUtils.toBoolean(0, 1, 0) = false
* BooleanUtils.toBoolean(1, 1, 0) = true
* BooleanUtils.toBoolean(2, 1, 2) = false
* BooleanUtils.toBoolean(2, 2, 0) = true
* </pre>
*
* @param value the Integer to convert
* @param trueValue the value to match for <code>true</code>
* @param falseValue the value to match for <code>false</code>
* @return <code>true</code> or <code>false</code>
* @throws IllegalArgumentException if no match
*/
public static boolean toBoolean(int value, int trueValue, int falseValue) {
if (value == trueValue) {
return true;
} else if (value == falseValue) {
return false;
}
// no match
throw new IllegalArgumentException("The Integer did not match either specified value")
;
}
}

2. 2. 24. Performs an xor on a set of booleans.


/*
* 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.
*/

/**
* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/
public class Main {
/**
* Performs an xor on a set of booleans.
*
* <pre>
* BooleanUtils.xor(new boolean[] { true, true }) = false
* BooleanUtils.xor(new boolean[] { false, false }) = false
* BooleanUtils.xor(new boolean[] { true, false }) = true
* </pre>
*
* @param array an array of <code>boolean<code>s
* @return <code>true</code> if the xor is successful.
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty.
*/
public static boolean xor(boolean[] array) {
// Validates input
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}

// Loops through array, comparing each item


int trueCount = 0;
for (int i = 0; i < array.length; i++) {
// If item is true, and trueCount is < 1, increments count
// Else, xor fails
if (array[i]) {
if (trueCount < 1) {
trueCount++;
} else {
return false;
}
}
}

// Returns true if there was exactly 1 true item


return trueCount == 1;
}
/**
* Performs an xor on an array of Booleans.
*
* <pre>
* BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) = Boolean.FALSE
* BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
* BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) = Boolean.TRUE
* </pre>
*
* @param array an array of <code>Boolean<code>s
* @return <code>true</code> if the xor is successful.
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty.
* @throws IllegalArgumentException if <code>array</code> contains a <code>null</code>
*/
public static Boolean xor(Boolean[] array) {
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
} else if (array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
boolean[] primitive = null;
try {
primitive = toPrimitive(array);
} catch (NullPointerException ex) {
throw new IllegalArgumentException("The array must not contain any null elements")
;
}
return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Converts an array of object Booleans to primitives.
*
* This method returns <code>null</code> for a <code>null</code> input array.
*
* @param array a <code>Boolean</code> array, may be <code>null</code>
* @return a <code>boolean</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
public static boolean[] toPrimitive(Boolean[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return new boolean[0];
}
final boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].booleanValue();
}
return result;
}
}

2. 3. Integer Data Type


2. 3. 1. Integer Data Types in Java: memory and length

2. 3. 2. Integer Calculations

2. 3. 3. Add two integers, checking for overflow.

2. 3. 4. Multiply two integers, checking for overflow.

2. 3. 5. Subtract two integers, checking for overflow.

2. 3. 6. Binary and Decimal value table

2. 3. 7. Min and Max values of datatype int

2. 3. 8. Hexadecimal Numbers and its corresponding Decimal and binary value

2. 3. 9. Gets the maximum of three int values.

2. 3. 10. Gets the minimum of three int values.


Given an integer, return a string that is in an approximate, but human readable
2. 3. 11.
format
2. 3. 12. int array to byte array

2. 3. 1. Integer Data Types in Java: memory and length

1. There are four types of integer data variables.


2. They can store both negative and positive values.

Data Type Value Memory


byte -128 -- +127 occupy 1 byte (8 bits) in memory
short -32768 -- 32767 occupy 2 bytes (16 bits) in memory
int -2147483648 -- 2147483647 occupy 4 bytes (32 bits) in memory
long -9223372036854775808 -- 9223372036854775807 occupy 8 bytes (64 bits) in memory

2. 3. 2. Integer Calculations

1. The basic operators in calculations are +, -, *, and /. They have the usual meanings: add, subtract,
multiply, and divide, respectively.
2. Using parentheses in arithmetic calculations to change the sequence of operations.

public class MainClass{


public static void main(String[] argv){
int a = (20 - 3) * (3 - 9) / 3;
int b = 20 - 3 * 3 - 9 / 3;

System.out.println(a);
System.out.println(b);
}

-34
8

2. 3. 3. Add two 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 integers, checking for overflow.
*
* @param x an addend
* @param y an addend
* @return the sum <code>x+y</code>
* @throws ArithmeticException if the result can not be represented as an
* int
* @since 1.1
*/
public static int addAndCheck(int x, int y) {
long s = (long)x + (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int)s;
}
}
2. 3. 4. Multiply two 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 integers, checking for overflow.
*
* @param x a factor
* @param y a factor
* @return the product <code>x*y</code>
* @throws ArithmeticException if the result can not be represented as an
* int
* @since 1.1
*/
public static int mulAndCheck(int x, int y) {
long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: mul");
}
return (int)m;
}
}

2. 3. 5. Subtract two 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 integers, checking for overflow.
*
* @param x the minuend
* @param y the subtrahend
* @return the difference <code>x-y</code>
* @throws ArithmeticException if the result can not be represented as an
* int
* @since 1.1
*/
public static int subAndCheck(int x, int y) {
long s = (long)x - (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: subtract");
}
return (int)s;
}
}

2. 3. 6. Binary and Decimal value table

Binary Decimal
0000 0000 0
1000 0000 128
0000 0001 1
1000 0001 129
0000 0010 2
1000 0010 130
0001 0000 16
1001 0000 144
0001 0001 17
1001 0001 145
0111 1100 124
1111 1100 252
0111 1101 125
1111 1101 253
0111 1110 126
1111 1110 254
0111 1111 127
1111 1111 255
2. 3. 7. Min and Max values of datatype int

public class Main {


public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
}
}
/*
-2147483648
2147483647
*/

2. 3. 8. Hexadecimal Numbers and its corresponding Decimal


and binary value

Hexadecimal Decimal Binary


0 0 0000
1 1 0001
2 2 0010
3 4 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
A 10 1010
B 11 1011
C 12 1100
D 13 1101
E 14 1110
F 15 1111

2. 3. 9. Gets the maximum of three int 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 <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author Stephen Colebourne
* @author <a href="mailto:steve.downey@netfolio.com">Steve Downey</a>
* @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>int</code> values.
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static int maximum(int a, int b, int c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
}

2. 3. 10. Gets the minimum of three int 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 <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author Stephen Colebourne
* @author <a href="mailto:steve.downey@netfolio.com">Steve Downey</a>
* @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>int</code> values.
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static int minimum(int a, int b, int c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
}

2. 3. 11. Given an integer, return a string that is in an


approximate, but human readable format

/**
* 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.
*/

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;

/**
* General string utils
*/
public class StringUtils {

final public static char COMMA = ',';


final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = '\\';
private static DecimalFormat oneDecimal = new DecimalFormat("0.0");

/**
* Given an integer, return a string that is in an approximate, but human
* readable format.
* It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3.
* @param number the number to format
* @return a human readable form of the integer
*/
public static String humanReadableInt(long number) {
long absNumber = Math.abs(number);
double result = number;
String suffix = "";
if (absNumber < 1024) {
// nothing
} else if (absNumber < 1024 * 1024) {
result = number / 1024.0;
suffix = "k";
} else if (absNumber < 1024 * 1024 * 1024) {
result = number / (1024.0 * 1024);
suffix = "m";
} else {
result = number / (1024.0 * 1024 * 1024);
suffix = "g";
}
return oneDecimal.format(result) + suffix;
}
}

2. 3. 12. int array to byte array

/*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

public class ArrayCopy {

public static byte[] int2byte(int[]src) {


int srcLength = src.length;
byte[]dst = new byte[srcLength << 2];

for (int i=0; i<srcLength; i++) {


int x = src[i];
int j = i << 2;
dst[j++] = (byte) ((x >>> 0) & 0xff);
dst[j++] = (byte) ((x >>> 8) & 0xff);
dst[j++] = (byte) ((x >>> 16) & 0xff);
dst[j++] = (byte) ((x >>> 24) & 0xff);
}
return dst;
}
}

2. 4. Byte
Java byte: byte is smallest Java integer type.byte is 8 bit signed type
2. 4. 1.
ranges from �128 to 127.

2. 4. 2. Using byte data type


Convert byte to String: Using the static toString method of the Byte
2. 4. 3.
class
Convert byte to String: Using simple concatenation with an empty
2. 4. 4.
String
Convert byte to String: Creating a byte array and passing it to the String
2. 4. 5.
constructor
2. 4. 6. Convert String to byte

2. 4. 7. Use toString method of Byte class to convert Byte into String

2. 4. 8. Use Byte constructor to convert byte primitive type to Byte object

2. 4. 9. Compare Two Java byte Arrays Example

2. 4. 10. Convert an UNSIGNED byte to a JAVA type

2. 4. 11. To convert a byte to it's hexadecimal equivalent


2. 4. 12. byte Array To Hex String

2. 4. 13. hex String To Byte Array

2. 4. 14. Convert byte[ ] array to String

2. 4. 15. Convert String to byte array

2. 4. 16. Convert Byte to numeric primitive data types example

2. 4. 17. Min and Max values of datatype byte

2. 4. 18. Byte Range

2. 4. 1. Java byte: byte is smallest Java integer type.byte is 8 bit signed


type ranges from �128 to 127.

public class Main {


public static void main(String[] args) {
byte b1 = 100;
byte b2 = 20;
System.out.println("Value of byte variable b1 is :" + b1);
System.out.println("Value of byte variable b1 is :" + b2);
}
}
/*
Value of byte variable b1 is :100
Value of byte variable b1 is :20
*/

2. 4. 2. Using byte data type

public class MainClass {

public static void main(String[] arg) {


byte luckyNumber = 7;
System.out.println(luckyNumber);
}

2. 4. 3. Convert byte to String: Using the static toString method of the Byt
class
public class Main {
public static void main(String[] args) {
byte b = 65;

System.out.println(Byte.toString(b));

}
}

2. 4. 4. Convert byte to String: Using simple concatenation with an empty


String

public class Main {


public static void main(String[] args) {
byte b = 65;

System.out.println(b + "");

}
}
//65

2. 4. 5. Convert byte to String: Creating a byte array and passing it to the


String constructor

public class Main {


public static void main(String[] args) {
byte b = 65;

System.out.println(new String(new byte[] {b}));

}
}
//A

2. 4. 6. Convert String to byte

public class Main {

public static void main(String[] args) {


String s = "65";

byte b = Byte.valueOf(s);

System.out.println(b);

// Causes a NumberFormatException since the value is out of range


System.out.println(Byte.valueOf("129"));
}
}
/*
65
Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radi
at java.lang.Byte.parseByte(Byte.java:153)
at java.lang.Byte.valueOf(Byte.java:184)
at java.lang.Byte.valueOf(Byte.java:208)
at Main.main(Main.java:11)

*/

2. 4. 7. Use toString method of Byte class to convert Byte into String

public class Main {


public static void main(String[] args) {
Byte bObj = new Byte("10");

String str = bObj.toString();


System.out.println(str);
}
}

2. 4. 8. Use Byte constructor to convert byte primitive type to Byte object

public class Main {


public static void main(String[] args) {
byte i = 10;

Byte bObj = new Byte(i);


System.out.println(bObj);
}
}

2. 4. 9. Compare Two Java byte Arrays Example

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
byte[] a1 = new byte[] { 7, 25, 12 };
byte[] a2 = new byte[] { 7, 25, 12 };

System.out.println(Arrays.equals(a1, a2));
}
}

2. 4. 10. Convert an UNSIGNED byte to a JAVA type

public class Main {


public static void main(String args[]) {
byte b1 = 127;
System.out.println(b1);
System.out.println(unsignedByteToInt(b1));
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}

2. 4. 11. To convert a byte to it's hexadecimal equivalent

public class Main {


public static void main(String[] argv) {
System.out.println(byteToHex((byte) 123));
}

public static String byteToHex(byte b) {


int i = b & 0xFF;
return Integer.toHexString(i);
}
}
//7b

2. 4. 12. byte Array To Hex String

public class Main {

public static void main(String arg[]) {


byteArrayToHexString(("abc").getBytes());
}

public static String byteArrayToHexString(byte[] b) {


StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}

2. 4. 13. hex String To Byte Array

public class Main {

public static byte[] hexStringToByteArray(String s) {


byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
}

2. 4. 14. Convert byte[ ] array to String

public class Main {


public static void main(String[] args) {
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
System.out.println(value);
}
}
//WOW...

2. 4. 15. Convert String to byte array

public class Main {


public static void main(String[] args) {
String stringToConvert = "this is a test";

byte[] theByteArray = stringToConvert.getBytes();

System.out.println(theByteArray.length);
}
}
//14

2. 4. 16. Convert Byte to numeric primitive data types example

public class Main {

public static void main(String[] args) {


Byte bObj = new Byte("10");
byte b = bObj.byteValue();
System.out.println(b);
short s = bObj.shortValue();
System.out.println(s);
int i = bObj.intValue();
System.out.println(i);
float f = bObj.floatValue();
System.out.println(f);
double d = bObj.doubleValue();
System.out.println(d);
long l = bObj.longValue();
System.out.println(l);

2. 4. 17. Min and Max values of datatype byte

public class Main {


public static void main(String[] args) {
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
}
}
/*
-128
127
*/

2. 4. 18. Byte Range

/*
* 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.
*/

/**
* @version $Id: ByteRange.java 587751 2007-10-24 02:41:36Z vgritsenko $
*/
final public class ByteRange {

private final long start;


private final long end;

public ByteRange(long start, long end) {


this.start = start;
this.end = end;
}

public ByteRange(String string) throws NumberFormatException {


string = string.trim();
int dashPos = string.indexOf('-');
int length = string.length();
if (string.indexOf(',') != -1) {
throw new NumberFormatException("Simple ByteRange String contains a comma.");
}
if (dashPos > 0) {
this.start = Integer.parseInt(string.substring(0, dashPos));
} else {
this.start = Long.MIN_VALUE;
}
if (dashPos < length - 1) {
this.end = Integer.parseInt(string.substring(dashPos + 1, length));
} else {
this.end = Long.MAX_VALUE;
}
if (this.start > this.end) {
throw new NumberFormatException("Start value is greater than end value.");
}
}

public long getStart() {


return this.start;
}

public long getEnd() {


return this.end;
}

public long length() {


return this.end - this.start + 1;
}

public ByteRange intersection(ByteRange range) {


if (range.end < this.start || this.end < range.start) {
return null;
} else {
long start = (this.start > range.start) ? this.start : range.start;
long end = (this.end < range.end) ? this.end : range.end;
return new ByteRange(start, end);
}
}

public String toString() {


return this.start + "-" + this.end;
}

2. 5. Short
2. 5. 1. Java short: short is 16 bit signed type ranges from �32,768 to 32,767.

2. 5. 2. Using short data type

2. 5. 3. Min and Max values of datatype short

2. 5. 4. Compare Two Java short Arrays

2. 5. 5. Cast back to short

2. 5. 6. Cast result of plus opertion to byte

2. 5. 7. Convert Java String to Short

2. 5. 8. Use toString method of Short class to convert Short into String.


2. 5. 9. Use Short constructor to convert short primitive type to Short object

2. 5. 10. Convert String to short primitive

2. 5. 11. Convert Short to numeric primitive data types

2. 5. 12. Java Sort short Array

2. 5. 13. Computation with Shorter Integer Types

Das könnte Ihnen auch gefallen