User talk:Janjurada

Primitive types are the most basic data types available within the Java language; these include boolean, byte, char, short, int, long, float and double. These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind. Because these data types are defined into the Java type system by default, they come with a number of operations predefined. You can not define a new operation for such primitive types. In the Java type system, there are three further categories of primitives:

Numeric primitives: short, int, long, float and double. These primitive data types hold only numeric data. Operations associated with such data types are those of simple arithmetic (addition, subtraction, etc.) or of comparisons (is greater than, is equal to, etc.) Textual primitives: byte and char. These primitive data types hold characters (that can be Unicode alphabets or even numbers). Operations associated with such types are those of textual manipulation (comparing two words, joining characters to make words, etc.). However, byte and char can also support arithmetic operations. Boolean and null primitives: boolean and null. All the primitive types have a fixed size. Thus, the primitive types are limited to a range of values. A smaller primitive type (byte) can contain less values than a bigger one (long).

Category	Types	Size (bits)	Minimum Value	Maximum Value	Precision	Example Integer	byte	8	-128	127	From +127 to -128	byte b = 65; char	16	0	216-1	All Unicode characters	char c = 'A'; char c = 65; short	16	-215	215-1	From +32,767 to -32,768	short s = 65; int	32	-231	231-1	From +2,147,483,647 to -2,147,483,648	int i = 65; long	64	-263	263-1	From +9,223,372,036,854,775,807 to -9,223,372,036,854,775,808	long l = 65L; Floating-point	float	32	2-149	(2-2-23)·2127	From 3.402,823,5 E+38 to 1.4 E-45	float f = 65f; double	64	2-1074	(2-2-52)·21023	From 1.797,693,134,862,315,7 E+308 to 4.9 E-324	double d = 65.55; Other	boolean	1	--	--	false, true	boolean b = true; void	--	--	--	--	-- Integer primitive types silently overflow:

Example	Code section 3.52: Several operators. int i = Integer.MAX_VALUE; System.out.println(i); i = i + 1; System.out.println(i); System.out.println(Integer.MIN_VALUE); Computer code	Console for Code section 3.52 2147483647 -2147483648 -2147483648 As Java is strongly typed, you can't assign a floating point number (a number with a decimal point) to an integer variable:

Warning	Code section 3.53: Setting a floating point number as a value to an int (integer) type. int age; age = 10.5; A primitive type should be set by an appropriate value. The primitive types can be initialized with a literal. Most of the literals are primitive type values, except String Literals, which are instance of the String class.

Numbers in computer science[edit] Programming may not be as trivial or boring as just crunching huge numbers any more. However, huge chunks of code written in any programming language today, let alone Java, obsessively deal with numbers. Be it churning out huge prime numbers,[1] or just calculating a cost of emission from your scooter. In 1965, Gemini V space mission escaped a near-fatal accident because of a programming error.[2] And again in 1979, a computer program calculated the ability of five nuclear reactors to withstand earthquakes as overestimated; this caused the plants to be shut down temporarily.[3] There is one thing common to both these programming errors: the subject data, being computed at the time the errors occurred, was numeric. Out of past experience, Java came bundled with revised type checking for numeric data and puts lots of emphasis on correctly identifying different types of it. So you must recognise the importance of numeric data when it comes to programming.

Numbers are stored in memory using a binary system. The memory is like a grid of cells:

Each cell can contain a binary digit (shortened to bit), that is to say, zero or one:

0 	 1 	 1 	 0 	 0 	 1 	 0 	 1 Actually, each cell does contain a binary digit, as one bit is roughly equivalent to 1 and an empty cell in the memory signifies 0. A single binary digit can only hold two possible values: a zero or a one.

Memory state	Value 0 	0  	   	   	   	   	   	   	 1 	1 Multiple bits held together can hold multiple permutations — 2 bits can hold 4 possible values, 3 can hold 8, and so on. For instance, the maximum number 8 bits can hold (11111111 in binary) is 255 in the decimal system. So, the numbers from 0 to 255 can fit within 8 bits.

Memory state	Value 0 	 0 	 0 	 0 	 0 	 0 	 0 	 0 	0 0 	 0 	 0 	 0 	 0 	 0 	 0 	 1 	1 0 	 0 	 0 	 0 	 0 	 0 	 1 	 0 	2 0 	 0 	 0 	 0 	 0 	 0 	 1 	 1 	3

... ... 1 	 1 	 1 	 1 	 1 	 1 	 1 	 1 	255 It is all good, but this way, we can only host positive numbers (or unsigned integers). They are called unsigned integers. Unsigned integers are whole number values that are all positive and do not attribute to negative values. For this very reason, we would ask one of the 8 bits to hold information about the sign of the number (positive or negative). This leaves us with just 7 bits to actually count out a number. The maximum number that these 7 bits can hold (1111111) is 127 in the decimal system.

Positive numbers	Negative numbers Memory state	Value 0 		 0 	 0 	 0 	 0 	 0 	 0 	 0 	0 0 		 0 	 0 	 0 	 0 	 0 	 0 	 1 	1 0 		 0 	 0 	 0 	 0 	 0 	 1 	 0 	2 0 		 0 	 0 	 0 	 0 	 0 	 1 	 1 	3

...

... ... 0 		 1 	 1 	 1 	 1 	 1 	 1 	 1 	127 Memory state	Value 1 		 0 	 0 	 0 	 0 	 0 	 0 	 0 	-128 1 		 0 	 0 	 0 	 0 	 0 	 0 	 1 	-127 1 		 0 	 0 	 0 	 0 	 0 	 1 	 0 	-126 1 		 0 	 0 	 0 	 0 	 0 	 1 	 1 	-125

...

... ... 1 		 1 	 1 	 1 	 1 	 1 	 1 	 1 	-1 Altogether, using this method, 8 bits can hold numbers ranging from -128 to 127 (including zero) — a total of 256 numbers. Not a bad pay-off one might presume. The opposite to an unsigned integer is a signed integer that have the capability of holding both positive and negative values.

But, what about larger numbers. You would need significantly more bits to hold larger numbers. That's where Java's numeric types come into play. Java has multiple numeric types — their size dependant on the number of bits that are at play.

In Java, numbers are dealt with using data types specially formulated to host numeric data. But before we dive into these types, we must first set some concepts in stone. Just like you did in high school (or even primary school), numbers in Java are placed in clearly distinct groups and systems. As you'd already know by now, number systems includes groups like the integer numbers (0, 1, 2 ... ∞); negative integers (0, -1, -2 ... -∞) or even real and rational numbers (value of Pi, ¾, 0.333~, etcetera). Java simply tends to place these numbers in two distinct groups, integers (-∞ ... 0 ... ∞) and floating point numbers (any number with decimal points or fractional representation). For the moment, we would only look into integer values as they are easier to understand and work with.

Integer types in Java[edit] With what we have learned so far, we will identify the different types of signed integer values that can be created and manipulated in Java. Following is a table of the most basic numeric types: integers. As we have discussed earlier, the data types in Java for integers caters to both positive and negative values and hence are signed numeric types. The size in bits for a numeric type determines what its minimum and maximum value would be. If in doubt, one can always calculate these values.

Lets see how this new found knowledge of the basic integer types in Java fits into the picture. Say, you want to numerically manipulate the days in a year — all 365 days. What type would you use? Since the data type byte only goes up to 127, would you risk giving it a value greater than its allowed maximum. Such decisions might save you from dreaded errors that might occur out of the programmed code. A much more sensible choice for such a numeric operation might be a short. Oh, why couldn't they make just one data type to hold all kinds of numbers? Wouldn't you ask that question? Well, let's explore why.

When you tell a program you need to use an integer, say even a byte, the Java program allocates a space in the memory. It allocates whole 8 bits of memory. Where it wouldn't seem to matter for today's memory modules that have place for almost a dozen trillion such bits, it matters in other cases. Once allocated that part of the memory gets used and can only be claimed back after the operation is finished. Consider a complicated Java program where the only data type you'd be using would be long integers. What happens when there's no space for more memory allocation jobs? Ever heard of the Stack Overflow errors. That's exactly what happens — your memory gets completely used up and fast. So, choose your data types with extreme caution.

Enough talk, let's see how you can create a numeric type. A numeric type begins with the type's name (short, int, etc.) and then provides with a name for the allocated space in the memory. Following is how it's done. Say, we need to create a variable to hold the number of days in a year.

Example	Code section 3.54: Days in a year. short daysInYear = 365; Here, daysInYear is the name of the variable that holds 365 as it's value, while short is the data type for that particular value. Other uses of integer data types in Java might see you write code such as this given below:

Example	Code section 3.55: Integer data types in Java. byte maxByte = 127; short maxShort = 32767; int maxInt = 2147483647; long maxLong = 9223372036854775807; Integer numbers and floating point numbers[edit] The data types that one can use for integer numbers are byte, short, int and long but when it comes to floating point numbers, we use float or double. Now that we know that, we can modify the code in the code section 3.53 as:

Example	Code section 3.56: Correct floating point declaration and assignment. double age = 10.5; Why not float, you say? If we'd used a float, we would have to append the number with a f as a suffix, so 10.5 should be 10.5f as in:

Example	Code section 3.57: The correct way to define floating point numbers of type float. float age = 10.5f; Floating-point math never throws exceptions. Dividing a non-zero value by 0 equals infinity. Dividing a non-infinite value by infinity equals 0.

Test your knowledge Data conversion (casting)[edit] Data conversion (casting) can happen between two primitive types. There are two kinds of casting:

Implicit: casting operation is not required; the magnitude of the numeric value is always preserved. However, precision may be lost when converting from integer to floating point types Explicit: casting operation required; the magnitude of the numeric value may not be preserved Example	Code section 3.58: Implicit casting (int is converted to long, casting is not needed). int i = 65; long l = i; Example	Code section 3.59: Explicit casting (long is converted to int, casting is needed). long l = 656666L; int i = (int) l; The following table shows the conversions between primitive types, it shows the casting operation for explicit conversions:

from byte	from char	from short	from int	from long	from float	from double	from boolean to byte	-	(byte)	(byte)	(byte)	(byte)	(byte)	(byte)	N/A to char		-	(char)	(char)	(char)	(char)	(char)	N/A to short		(short)	-	(short)	(short)	(short)	(short)	N/A to int				-	(int)	(int)	(int)	N/A to long					-	(long)	(long)	N/A to float						-	(float)	N/A to double							-	N/A to boolean	N/A	N/A	N/A	N/A	N/A	N/A	N/A	- Unlike C, C++ and similar languages, Java can't represent false as 0 or null and can't represent true as non-zero. Java can't cast from boolean to a non-boolean primitive data type, or vice versa.

stringjava
String is a class built into the Java language defined in the java.lang package. It represents character strings. Strings are ubiquitous in Java. Study the String class and its methods carefully. It will serve you well to know how to manipulate them skillfully. String literals in Java programs, such as "abc", are implemented as instances of this class like this:

Example	Code section 3.81: String example. String str = "This is string literal"; On the right hand side a String object is created represented by the string literal. Its object reference is assigned to the str variable.

Immutability[edit] Strings are immutable; that is, they cannot be modified once created. Whenever it looks as if a String object was modified actually a new String was created. For instance, the String.trim method returns the string with leading and trailing whitespace removed. Actually, it creates a new trimmed string and then returns it. Pay attention on what happens in Code section 3.82:

Example	Code section 3.82: Immutability. String badlyCutText = "    Java is great.     "; System.out.println(badlyCutText); badlyCutText.trim; System.out.println(badlyCutText); Standard input or output	Output for Code section 3.82 Java is great. Java is great. The trim method call does not modify the object so nothing happens. It creates a new trimmed string and then throws it away.

Example	Code section 3.83: Assignment. String badlyCutText = "    Java is great.     "; System.out.println(badlyCutText); badlyCutText = badlyCutText.trim; System.out.println(badlyCutText); Standard input or output	Output for Code section 3.83 Java is great. Java is great. The returned string is assigned to the variable. It does the job as the trim method has created a new String instance.

Concatenation[edit] The Java language provides special support for the string concatenation with operator +:

Example	Code section 3.84: Examples of concatenation. System.out.println("First part"); System.out.println(" second part"); String str = "First part" + " second part"; System.out.println(str); Standard input or output	Output for Code section 3.84 First part second part First part second part The concatenation is not always processed at the same time. Raw string literals concatenation is done at compile time, hence there is a single string literal in the byte code of the class. Concatenation with at least one object is done at runtime.

+ operator can concatenate other objects with strings. For instance, integers will be converted to strings before the concatenation:

Example	Code section 3.85: Concatenation of integers. System.out.println("Age=" + 25); Standard input or output	Output for Code section 3.85 Age=25 Each Java object has the String toString inherited from the Object class. This method provides a way to convert objects into Strings. Most classes override the default behavior to provide more specific (and more useful) data in the returned String:

Example	Code section 3.86: Concatenation of objects. System.out.println("Age=" + new Integer(31)); Standard input or output	Output for Code section 3.86 Age=31 Using StringBuilder/StringBuffer to concatenate strings[edit] Remember that String objects are immutable objects. Once a String is created, it can not be modified, takes up memory until garbage collected. Be careful of writing a method like this:

Example	Code section 3.87: Raw concatenation. public String convertToString(Collection words) { String str = ""; // Loops through every element in words collection for (String word : words) { str = str + word + " "; } return str; } On the + operation a new String object is created at each iteration. Suppose words contains the elements ["Foo", "Bar", "Bam", "Baz"]. At runtime, the method creates thirteen Strings:

"" "Foo" " " "Foo " "Foo Bar" " " "Foo Bar " "Foo Bar Bam" " " "Foo Bar Bam " "Foo Bar Bam Baz" " " "Foo Bar Bam Baz " Even though only the last one is actually useful.

To avoid unnecessary memory use like this, use the StringBuilder class. It provides similar functionality to Strings, but stores its data in a mutable way. Only one StringBuilder object is created. Also because object creation is time consuming, using StringBuilder produces much faster code.

Example	Code section 3.88: Concatenation with StringBuilder. public String convertToString(Collection words) { StringBuilder buf = new StringBuilder; // Loops through every element in words collection for (String word : words) { buf.append(word); buf.append(" "); } return buf.toString; } As StringBuilder isn't thread safe (see the chapter on Concurrency). You can't use it in more than one thread. For multi-thread environment, use StringBuffer instead, which does the same and is thread safe. However, as StringBuffer is slower, so only use it when it is required. Moreover, only StringBuffer existed before Java 5.

Comparing Strings[edit] Comparing strings is not as easy as it may first seem. Be aware of what you are doing when comparing String's using ==:

Example	Code section 3.89: Dangerous comparison. String greeting = "Hello World!"; if (greeting == "Hello World!") { System.out.println("Match found."); } Standard input or output	Output for Code section 3.89 Match found. The difference between the above and below code is that the above code checks to see if the String's are the same objects in memory which they are. This is as a result of the fact that String's are stored in a place in memory called the String Constant Pool. If the new keyword is not explicitly used when creating the String it checks to see if it already exists in the Pool and uses the existing one. If it does not exist, a new Object is created. This is what allows Strings to be immutable in Java. To test for equality, use the equals(Object) method inherited by every class and defined by String to return true if and only if the object passed in is a String containing the exact same data:

Example	Code section 3.90: Right comparison. String greeting = "Hello World!"; if (greeting.equals("Hello World!")) { System.out.println("Match found."); } Standard input or output	Output for Code section 3.90 Match found. Remember that the comparison is case sensitive.

Example	Code section 3.91: Comparison with lowercase. String greeting = "Hello World!"; if (greeting.equals("hello world!")) { System.out.println("Match found."); } Standard input or output	Output for Code section 3.91 To order String objects, use the compareTo method, which can be accessed wherever we use a String datatype. The compareTo method returns a negative, zero, or positive number if the parameter is less than, equal to, or greater than the object on which it is called. Let's take a look at an example:

Example	Code section 3.92: Order. String person1 = "Peter"; String person2 = "John"; if (person1.compareTo(person2) > 0) { // Badly ordered String temp = person1; person1 = person2; person2 = temp; } The code section 3.92 is comparing the String variable person1 to person2. If person1 was to be different, even in the slightest manner we will get a value above or below 0 depending on the exact difference. The result is negative if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. Take a look at the Java API for more details.

Splitting a String[edit] Sometimes it is useful to split a string into separate strings, based on a regular expressions. The String class has a split method, since Java 1.4, that will return a String array:

Example	Code section 3.93: Order. String person = "Brown, John:100 Yonge Street, Toronto:(416)777-9999"; ... String[] personData = person.split(":"); ... String name   = personData[0]; String address = personData[1]; String phone  = personData[2]; Another useful application could be to split the String text based on the new line character, so you could process the text line by line.

Substrings[edit] It may also be sometimes useful to create substrings, or strings using the order of letters from an existing string. This can be done in two methods.

The first method involves creating a substring out of the characters of a string from a given index to the end:

Example	Code section 3.94: Truncating string. String str = "coffee"; System.out.println(str.substring(3)); Standard input or output	Output for Code section 3.94 fee The index of the first character in a string is 0.

c	o	f	f	e	e 0	1	2	3	4	5 By counting from there, it is apparent that the character in index 3 is the second "f" in "coffee". This is known as the beginIndex. All characters from the beginIndex until the end of the string will be copied into the new substring.

The second method involves a user-defined beginIndex and endIndex:

Example	Code section 3.95: Extraction of string. String str = "supporting"; System.out.println(str.substring(3, 7)); Standard input or output	Output for Code section 3.95 port The string returned by substring would be "port".

s	u	p	p	o	r	t	i	n	g 0	1	2	3	4	5	6	7	8	9 Please note that the endIndex is not inclusive. This means that the last character will be of the index endIndex-1. Therefore, in this example, every character from index 3 to index 6, inclusive, was copied into the substring.

Note	It is easy to mistake the method substring for subString (which does not exist and would return with a syntax error on compilation). Substring is considered to be one word. This is why the method name does not seem to follow the common syntax of Java. Just remember that this style only applies to methods or other elements that are made up of more than one word. String cases[edit] The String class also allows for the modification of cases. The two methods that make this possible are toLowerCase and toUpperCase.

Example	Code section 3.96: Case modification. String str = "wIkIbOoKs"; System.out.println(str.toLowerCase); System.out.println(str.toUpperCase); Standard input or output	Output for Code section 3.96 These methods are useful to do a search which is not case sensitive:

Example	Code section 3.97: Text search. String word = "Integer"; String text = "A number without a decimal part is an integer." + " Integers are a list of digits."; ... // Remove the case String lowerCaseWord = word.toLowerCase; String lowerCaseText = text.toLowerCase; // Search int index = lowerCaseText.indexOf(lowerCaseWord); while (index != -1) { System.out.println(word   + " appears at column "    + (index + 1)    + "."); index = lowerCaseText.indexOf(lowerCaseWord, index + 1); }

An object is composed of fields and methods. The fields, also called data members, characteristics, attributes, or properties, describe the state of the object. The methods generally describe the actions associated with a particular object. Think of an object as a noun, its fields as adjectives describing that noun, and its methods as the verbs that can be performed by or on that noun.

For example, a sports car is an object. Some of its fields might be its height, weight, acceleration, and speed. An object's fields just hold data about that object. Some of the methods of the sports car could be "drive", "park", "race", etc. The methods really don't mean much unless associated with the sports car, and the same goes for the fields.

The blueprint that lets us build our sports car object is called a class. A class doesn't tell us how fast our sports car goes, or what color it is, but it does tell us that our sports car will have a field representing speed and color, and that they will be say, a number and a word (or hex color code), respectively. The class also lays out the methods for us, telling the car how to park and drive, but these methods can't take any action with just the blueprint — they need an object to have an effect.

In Java, a class is located in a file similar to its own name. If you want to have a class called SportsCar, its source file needs to be SportsCar.java. The class is created by placing the following in the source file:

Computer code	Code listing 3.13: SportsCar.java public class SportsCar { /* Insert your code here */ } The class doesn't do anything yet, as you will need to add methods and field variables first.

The objects are different from the primitive types because:

The primitive types are not instantiated. In the memory, only their value is stored, directly. No reference to an instance is stored. In the memory, the allocated space is fixed, whatever their value. The allocated space of an object vary, for instance either the object is intantiated or not. The primitive types don't have methods callable on them. A primitive type can't be inherited. Instantiation and constructors[edit] In order to get from class to object, we "build" our object by instantiation. Instantiation simply means to create an instance of a class. Instance and object are very similar terms and are sometimes interchangeable, but remember that an instance refers to a specific object, which was created from a class.

This instantiation is brought about by one of the class's methods, called a constructor. As its name implies, a constructor builds the object based on the blueprint. Behind the scenes, this means that computer memory is being allocated for the instance, and values are being assigned to the data members.

In general there are four constructor types: default, non-default, copy, and cloning.

A default constructor will build the most basic instance. Generally, this means assigning all the fields values like null, zero, or an empty string. Nothing would stop you, however, from your default sports car color from being red, but this is generally bad programming style. Another programmer would be confused if your basic car came out red instead of say, colorless.

Example	Code section 3.79: A default constructor. SportsCar car = new SportsCar; A non-default constructor is designed to create an object instance with prescribed values for most, if not all, of the object's fields. The car is red, goes from 0-60 in 12 seconds, tops out at 190mph, etc.

Example	Code section 3.80: A non-default constructor. SportsCar car = new SportsCar("red", 12, 190); A copy constructor is not included in the Java language, however one can easily create a constructor that do the same as a copy constructor. It's important to understand what it is. As the name implies, a copy constructor creates a new instance to be a duplicate of an already existing one. In Java, this can be also accomplished by creating the instance with the default constructor, and then using the assignment operator to equivocate them. This is not possible in all languages though, so just keep the terminology under your belt.

Java has the concepts of cloning object, and the end results are similar to copy constructor. Cloning an object is faster than creation with the new keyword, because all the object memory is copied at once to destination cloned object. This is possible by implementing the Cloneable interface, which allows the method Object.clone to perform a field-by-field copy.

Example	Code section 3.81: Cloning object. SportsCar car = oldCar.clone; Type[edit] When an object is created, a reference to the object is also created. The object can not be accessed directly in Java, only through this object reference. This object reference has a type assigned to it. We need this type when passing the object reference to a method as a parameter. Java does strong type checking.

Type is basically a list of features/operations, that can be performed through that object reference. The object reference type is basically a contract that guarantees that those operations will be there at run time.

When a car is created, it comes with a list of features/operations listed in the user manual that guarantees that those will be there when the car is used.

When you create an object from a class by default its type is the same as its class. It means that all the features/operations the class defined are there and available, and can be used. See below:

Example	Code section 3.82: Default type. (new ClassName).operations; You can assign this to a variable having the same type as the class:

Example	Code section 3.83: A variable having the same type as the class. ClassName objRefVariable = new ClassName; objRefVariable.operations; You can assign the created object reference to the class, super class, or to an interface the class implements:

Example	Code section 3.84: Using the super class. SuperClass objectRef = new ClassName; // features/operations list are defined by the SuperClass class ... Interface inter = new ClassName; // features/operations list are defined by the interface In the car analogy, the created car may have different Type of drivers. We create separate user manuals for them, Average user manual, Power user manual, Child user manual, or Handicapped user manual. Each type of user manual describes only those features/operations appropriate for the type of driver. The Power driver may have additional gears to switch to higher speeds, that are not available to other type of users...

When the car key is passed from an adult to a child we replacing the user manuals, that is called Type Casting.

In Java, casts can occur in three ways:

up casting going up in the inheritance tree, until we reach the Object up casting to an interface the class implements down casting until we reach the class the object was created from Autoboxing/unboxing[edit] Autoboxing and unboxing, language features since Java 1.5, make the programmer's life much easier when it comes to working with the primitive wrapper types. Consider this code fragment:

Example	Code section 3.85: Traditional object creation. int age = 23; Integer ageObject = new Integer(age); Primitive wrapper objects were Java's way of allowing one to treat primitive data types as though they were objects. Consequently, one was expected to wrap one's primitive data type with the corresponding primitive wrapper object, as shown above.

Since Java 1.5, one may write as below and the compiler will automatically create the wrap object. The extra step of wrapping the primitive is no longer required. It has been automatically boxed up on your behalf:

Example	Code section 3.86: Autoboxing. int age = 23; Integer ageObject = age; Note	Keep in mind that the compiler still creates the missing wrapper code, so one doesn't really gain anything performance-wise. Consider this feature a programmer convenience, not a performance booster. Each primitive type has a class wrapper:

Primitive type	Class wrapper byte	java.lang.Byte char	java.lang.Character short	java.lang.Short int	java.lang.Integer long	java.lang.Long float	java.lang.Float double	java.lang.Double boolean	java.lang.Boolean void	java.lang.Void Unboxing uses the same process in reverse. Study the following code for a moment. The if statement requires a boolean primitive value, yet it was given a Boolean wrapper object. No problem! Java 1.5 will automatically unbox this.

Example	Code section 3.87: Unboxing. Boolean canMove = new Boolean(true); if (canMove) { System.out.println("This code is legal in Java 1.5"); } Test your knowledge Methods in the Object class[edit] Methods in the java.lang.Object class are inherited, and thus shared in common by all classes.

The clone method[edit] The java.lang.Object.clone method returns a new object that is a copy of the current object. Classes must implement the marker interface java.lang.Cloneable to indicate that they can be cloned.

The equals method[edit] The java.lang.Object.equals(java.lang.Object) method compares the object to another object and returns a boolean result indicating if the two objects are equal. Semantically, this method compares the contents of the objects whereas the equality comparison operator "==" compares the object references. The equals method is used by many of the data structure classes in the java.util package. Some of these data structure classes also rely on the Object.hashCode method—see the hashCode method for details on the contract between equals and hashCode. Implementing equals isn't always as easy as it seems, see 'Secrets of equals' for more information.

The finalize method[edit] The java.lang.Object.finalize method is called exactly once before the garbage collector frees the memory for object. A class overrides finalize to perform any clean up that must be performed before an object is reclaimed. Most objects do not need to override finalize.

There is no guarantee when the finalize method will be called, or the order in which the finalize method will be called for multiple objects. If the JVM exits without performing garbage collection, the OS may free the objects, in which case the finalize method doesn't get called.

The finalize method should always be declared protected to prevent other classes from calling the finalize method.

protected void finalize throws Throwable { ... } The getClass method[edit] The java.lang.Object.getClass method returns the java.lang.Class object for the class that was used to instantiate the object. The class object is the base class of reflection in Java. Additional reflection support is provided in the java.lang.reflect package.

The hashCode method[edit] The java.lang.Object.hashCode method returns an integer (int) that is used as a hash code for storing the object in an associative array. Classes that implement the java.util.Map interface provide associative arrays and rely on the hashCode method. A good hashCode implementation will return a hash code that is stable (does not change) and evenly distributed (the hash codes of unequal objects tend to be unequal and the hash codes are evenly distributed across integer values).

Because associative arrays depend on both the equals and hashCode methods, there is an important contract between these two methods that must be maintained if the objects are to be inserted into a Map:

For two objects a and b a.equals(b) == b.equals(a) if a.equals(b) then a.hashCode == b.hashCode In order to maintain this contract, a class that overrides the equals method must also override the hashCode method, and vice versa, so that hashCode is based on the same properties (or a subset of the properties) as equals.

A further contract that the map has with the object is that the results of the hashCode and equals methods will not change once the object has been inserted into the map. For this reason, it is generally a good practice to base the hash function on immutable properties of the object.

Two equal objects must have the same hashcode. However, 2 different objects are NOT required to have different hashcodes.

The toString method[edit] The java.lang.Object.toString method returns a java.lang.String that contains a text representation of the object. The toString method is implicitly called by the compiler when an object operand is used with the string concatenation operators (+ and +=).

The wait and notify thread signaling methods[edit] Every object has two wait lists for threads associated with it. One wait list is used by the synchronized keyword to acquire the mutex lock associated with the object. If the mutex lock is currently held by another thread, the current thread is added to the list of blocked threads waiting on the mutex lock. The other wait list is used for signaling between threads accomplished through the wait and notify and notifyAll methods.

Use of wait/notify allows efficient coordination of tasks between threads. When one thread needs to wait for another thread to complete an operation, or needs to wait until an event occurs, the thread can suspend its execution and wait to be notified when the event occurs. This is in contrast to polling, where the thread repeatedly sleeps for a short period of time and then checks a flag or other condition indicator. Polling is both more computationally expensive, as the thread has to continue checking, and less responsive since the thread won't notice the condition has changed until the next time to check.

The wait methods[edit] There are three overloaded versions of the wait method to support different ways to specify the timeout value: java.lang.Object.wait, java.lang.Object.wait(long) and java.lang.Object.wait(long, int). The first method uses a timeout value of zero (0), which means that the wait does not timeout; the second method takes the number of milliseconds as a timeout; the third method takes the number of nanoseconds as a timeout, calculated as 1000000 * timeout + nanos.

The thread calling wait is blocked (removed from the set of executable threads) and added to the object's wait list. The thread remains in the object's wait list until one of three events occurs:

another thread calls the object's notify or notifyAll method; another thread calls the thread's java.lang.Thread.interrupt method; or a non-zero timeout that was specified in the call to wait expires. The wait method must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify. When the thread is placed in the wait list, the thread releases the object's mutex lock. After the thread is removed from the wait list and added to the set of executable threads, it must acquire the object's mutex lock before continuing execution.

The notify and notifyAll methods[edit] The java.lang.Object.notify and java.lang.Object.notifyAll methods remove one or more threads from an object's wait list and add them to the set of executable threads. notify removes a single thread from the wait list, while notifyAll removes all threads from the wait list. Which thread is removed by notify is unspecified and dependent on the JVM implementation.

The notify methods must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify.

bignumber
The integer primitive type with the largest range of value is the long, from -263 to 263-1. If you need greater or lesser values, you have to use the BigInteger class in the package java.math. A BigInteger object can represent any integer (as large as the RAM on the computer can hold) as it is not mapped on a primitive type. Respectively, you need to use the BigDecimal class for great decimal numbers.

However, as these perform much slower than primitive types, it is recommended to use primitive types when it is possible.

BigInteger[edit] The BigInteger class represents integers of almost any size. As with other objects, they need to be constructed. Unlike regular numbers, the BigInteger represents an immutable object - methods in use by the BigInteger class will return a new copy of a BigInteger.

To instantiate a BigInteger, you can create it from either byte array, or from a string. For example:

Example	Code section 3.23: 1 quintillion, or 10^18. Too large to fit in a long. BigInteger i = new BigInteger("1000000000000000000"); BigInteger cannot use the normal Java operators. They use the methods provided by the class.

Example	Code section 3.24: Multiplications and an addition. BigInteger a = new BigInteger("3"); BigInteger b = new BigInteger("4"); // c = a^2 + b^2 BigInteger c = a.multiply(a).add(b.multiply(b)); It is possible to convert to a long, but the long may not be large enough.

Example	Code section 3.25: Conversion. BigInteger aBigInteger = new BigInteger("3"); long aLong = aBigInteger.longValue; BigDecimal[edit] The BigInteger class cannot handle decimal numbers. The BigDecimal class represents a floating point value of arbitrary precision. It is composed of both a BigInteger, and a scale value (represented by a 32-bit integer).

random numbers
To generate random numbers the Math.random method can be used, which returns a double, greater than or equal to 0.0 and less than 1.0.

The following code returns a random integer between n and m (where n <= randomNumber < m):

Example	Code section 3.30: A random integer. int randomNumber = n + (int)(Math.random * ( m - n )); Alternatively, the java.util.Random class provides methods for generating random booleans, bytes, floats, ints, longs and 'Gaussians' (doubles from a normal distribution with mean 0.0 and standard deviation 1.0). For example, the following code is equivalent to that above:

Example	Code section 3.31: A random integer with Gaussian. Random random = new Random; int randomNumber = n + random.nextInt(m - n); As an example using random numbers, we can make a program that uses a Random object to simulate flipping a coin 20 times:

Computer code	Code listing 3.25: CoinFlipper.java import java.util.Random; public class CoinFlipper { public static void main(String[] args) { // The number of times to flip the coin final int TIMES_TO_FLIP = 20; int heads = 0; int tails = 0; // Create a Random object Random random = new Random; for (int i = 0; i < TIMES_TO_FLIP; i++) { // 0 or 1 int result = random.nextInt(2); if (result == 1) { System.out.println("Heads"); heads++; } else { System.out.println("Tails"); tails++; }   }    System.out.println("There were "            + heads            + " heads and "            + tails            + " tails"); } } Computer code	Possible output for code listing 3.25 Heads Tails Tails Tails Heads Tails Heads Heads Heads Heads Heads Heads Tails Tails Tails Tails Heads Tails Tails Tails There were 9 heads and 11 tails Of course, if you run the program you will probably get different results.

Truly random numbers[edit] Both Math.random and the Random class produce pseudorandom numbers. This is good enough for a lot of applications, but remember that it is not truly random. If you want a more secure random number generator, Java provides the java.security.SecureRandom package. What happens with Math.random and the Random class is that a 'seed' is chosen from which the pseudorandom numbers are generated. SecureRandom increases the security to ensure that the seed which is used by the pseudorandom number generator is non-deterministic — that is, you cannot simply put the machine in the same state to get the same set of results. Once you have created a SecureRandom instance, you can use it in the same way as you can the Random class.

If you want truly random numbers, you can get a hardware random number generator or use a randomness generation service.