Error Handling

Errors in Java are represented by objects holding error information.

These objects are generated when errors occur.

Errors are handled by a programmer’s statements and these error objects.

 

Handling Errors

try
{
     statements
}
catch(Throwable-type error)
{
     statements
}

In the above, the try{} block tries to run statements that can err.

The catch{} block catches its errors and handles them with statements.

Example (try it):

try
{
     int x = 1 / 0; //generate an error here
}
catch (ArithmeticException error) //catch it
{
      System.out.println(error);
}

 

Throwing Errors

method() throws Throwable=type
{
     ...
}

When you do not want to handle an error, you can throw it.

throws reserved word throws (passes off) all of a type of error that happens in a block to the calling method of the currently running method to handle it.

No try block is needed in the throwing method.

The calling method must either catch it or throw it again (think “hot potatoes”).

Example:

class Tester
{
       static void err() throws ArithmeticException //erring method
       {
              int x = 1 / 0;
       }
 
       static void catchError() //calls above and catches its error
       {
              try
              {
                     err();
              }
              catch (ArithmeticException error)
              {
                                   System.out.println(error); //prints “/ zero” error

              }
       }
 
       public static void main(String[] args)
       {
                        catchError();

       }
}

 

Checked & Unchecked

Blue - checked Red - unchecked

Some of the most well-known errors. Blue – checked, red – unchecked

Checked errors (meaning “errors checked by compiler”) are errors that are required by the compiler to be handled, or your program will terminate.

Unchecked errors are errors that do not need to be handled or are fatal (which cannot be handled anyway).

 

Finally

finally
{
     statements
}

Finally blocks follow try/catch blocks and are run right after them.

They are blocks that run no matter what happens.

Purpose is to ensure something is run right before the program would terminate on an error (but it still will terminate afterwards).

They are often used for ensuring a file is closed when working on a file.

 

Assertions

assert expression;

This statement requires that some expression evaluates to true, else the program creates an AssertionError that must be caught or the program terminates.

This AssertionError is only created if the assertion feature is enabled in the compiler that you are using.

Purpose is to help detect errors in your program.

Example:

 

int divide(int x, int y)
{
     assert y != 0;

     return x / y;
}

 

 

Creating your own Error type

Your can make your own error classes, which must subclass Throwable.

Two types of Throwable already exist:

  • Error, which represents errors so severe they are not often handled.
  • Exception, which is often handled and includes errors that do or do not need to be handled.

Example:

class NewError extends Throwable
{
}
class Tester
{
    public static void main(String[] args)
         {
              try
              {
                   if (true == true)
                        throw new NewError();
              }
              catch(NewError error)
              {
                                  System.out.println("got here");

              }
       }
}
Please like & share:

Javadoc

Capture

Example of a javadoc-generated document (for ArrayList).

Javadoc is a utility included by JDK for creating documentation for your classes, interfaces, instance and class variables, constructors, and methods.

Javadoc uses a commenting format to be able to parse your code automatically.

The comments do not affect the function of your code.

 

Format

/** [description]

    @author [author name]
    @version [version info]
    @param [parameter] description
    @return [return value] [description]
    #throws [error type] [description]
*/ 

This is placed right before the method, class, etc. that you want to document.

The things preceded by @ are called tags (like @param, @return). Tags are optional keywords used to describe something.

Multiple of the same tag can be written (like with multiple authors).

Example:

/** Toaster of Food objects.
    @author David Hsu 
    @version 1.1 11/1/11
*/
class Toaster
{
     /** temperature setting for toasting. */
     int temperature = 500;

     /** This method toasts something.
         
         @param food1 the first food fed to the oven. 
         @param food2 the second food fed to the oven. 
         @return array of toasted items.
     */
     Food[] toast(Food food1, Food food2)
     {
          food1.status = "toasted";
          food2.status = "toasted";

          Food[] foods = {food1, food2};
          return foods;
     }
}

 

Generating the Javadoc document

Some IDEs make this easy: with Eclipse (if you have it), you can generate documentation simply by going file->export in the menu bar.

To do it in the computer terminal (command prompt), type the following while being in the directory of files that you want to document:

javadoc [files]

This will generate HTML pages (if it does not, check if you have installed JDK).

Example:

c:\animals> javadoc Cat.java Dog.java

Options can be included in the above command, which include:

  • -author : include author in generated pages.
  • -classpath [path] : give path of imported classes (if you need any).
  • -classpathlist [path];[path];…;[path] : same as above, but multiple paths.
  • -d [path] : Say what path to save generated pages.
  • -private : include private fields and methods (only public and protected ones are included by default).
  • -sourcepath [path] : say what path that the file you want to generate pages from is in.
  • -sourcepathlist [path];[path];…;[path] : same as above, but multiple paths.
  • -version : include version in generated pages.

 

(Optional) Preconditions and Postconditions

These things aren’t recognized in javadoc, but can be mentioned in your comments to more formalize your code (often used for design by customer contract).

Preconditions are required states of variables when a method is starting to run.

Example

/** Divide two integers.
    Precondition: divisor must not be 0.
    @param dividend left argument to the / operator
    @param divisor right argument to the / operator
*/
int divide(int dividend, int divisor)
{
     return dividend / divisor;
}

The assert statement in Java emulates preconditional checks. It requires that a condition is true, or an AssertionError is thrown (which must either be handled or the program terminates). Example:

assert divisor != 0;

Postconditions are required states of variables when a method finishes execution. Example:

/** add minutes to time.
     postconditions: 0 < hour < 24, 0 < minute < 60
*/
void addMinutes(int minutes)
{
     ...
}

 

Please like & share:

Abstraction & Interfaces

Abstraction is making something undefined (methods) or unable to be instantiated (classes).

Concretion, in contrast, is defining something and allowing it to be instantiated.

 

Abstract methods

abstract method();

These are methods that can be declared a name, type, and parameters, but have no body (no statements).

Abstract methods must be overridden.

They can only belong in abstract classes.

Purpose is for when you cannot agree on the implementation of a method, but you know it will be called, so you keep its name.

 

Abstract Classes

abstract Class
{
     ...
}

Abstract classes are classes that can have abstract and concrete methods.

Abstract classes cannot be instantiated.

Purpose is for grouping other classes together.

Example:

abstract Account //cannot be instantiated
{
}
class BankAccount extends Account
{
}

 

Interfaces

interface Interface
{
     abstract-methods
}

Interfaces are simply fully abstract classes (all methods are abstract) without variables.

Its methods are automatically declared abstract, so writing abstract is not needed.

Classes inheriting interfaces must use the reserved word implements instead of extends.

Example:

interface Menu
 {
     String button();
     String button2();
 }
 
class SimpleMenu
{
     String button()
     {
          return “yes”;
     }
     String button2()
     {
          return “no”;
     }
}
Please like & share:

Inheritance

inheritance

Inheritance means making a subclass of a class, or making a child of a parent (superclass) in other words.

Purpose is for reusing variables or methods of existing classes when creating new ones.

Extend is another word for inherit.

 

Syntax

class Class extends AnotherClass
{
     ...
}

This makes Class inherit AnotherClass.

Inheritors receive all their parent class fields and methods, but also can redefine them.

All classes automatically subclass the class Object, even without declaring so.

Example:

class Animal
{
}
class Horse extends Animal
{
}
class Donkey extends Horse
{
} 

We may refer to a subclass by its superclass name: “Horses and Donkeys are Animals.”

 

Common error: confusing super/sub classes
Super sounds like “greater”, so people mistake superclasses for an “extending” class. Super comes from the word “over” in fact, so superclasses can be thought of as being “over”, as parents are over and prior to, another.

 

Liskov Substitution Principle

substitution

This means that though a variable has a type, it can be assigned a subtype value.

Example:

Computer computer = new Iphone();

The value is used as the variable’s type, however. This means properties had by the value’s type but not the variable’s type cannot be accessed through the variable.

Like English: If an iphone is a computer, and we use the iphone as a computer, but only iphones can call someone, we cannot use it to call someone. But the iphone can be used as a computer, because it is a computer, so we can use it to compute things for example.

If you need to use the value as its own type, you must convert the variable to the subtype, shown in the Type Conversions section.

 

Overridding methods

Child classes can redefine their inherited methods or variables (not changing original).

Do this by declaring a method with the same name, in the inheriting class.

Example:

class Animal
{
     void cry()
     {
     }
}
class Horse extends Animal
{
     void cry() //overrides above cry()
     {
           System.out.println("neigh!");
     }
}
class Donkey extends Horse
{
     void cry() //overrides above cry()
     {
           System.out.println("bray!");
     }
}
Common error: overriding method declaration mismatchThis often occurs in such methods as equals(). It must be exactly:

public boolean equals(Object object)
{
	...
}

But people often put their own class in place of Object. This not only will not override the inherited equals, but will make the compiler think you are trying to add a new, overloaded method. So now you have two of the same method name, making this error hard to detect. Beware.

 

Polymorphism

This simply means calling the overridden method over the original.

(Polymorphism literally means “changing into many.”)

Example (try it):

//continuing above example.
animal.cry(); //will print neigh!
anotheranimal.cry(); //will print bray!

Since all classes inherit Object methods, overriding them is a common use for polymorphism:

  • toString() – gives a customized String representation of the object
  • equals() – customizes how to compare if something is “equal” to another object

The method System.out.println() uses toString() to print a String representation of its argument, so you can override toString() to make it print objects your way. Example:

class Animal
{
     String name;
     public String toString()
     {
           return name;
      }
}

Overriding equals() creates a customized way to compare between objects to see if they are equal. Example (try it):

class Animal
{
     String name;
     public boolean equals(Object object)
     {
           Animal other = (Animal) object;
           return this.name == other.name; //equal if same name
     }
}

 

 

Calling Parent Class Methods

Though methods can be overridden, the originals can still be accessed by the inheritors, as if they hold them. Do this by calling super.method(arguments), which denote calling their parent’s version.

Example:

class Donkey
{
     void cry()
     {
          super.cry(); //executes Horse's cry()
     }
}

 

Using Parent Class Constructor

The parent class constructor can be used for construction of its child, by using super(arguments).

super(); must only ever be the first statement in the constructor.

Example:

class Donkey
{
     Donkey()
     {
          super(); //executes the constructor Horse()
     }
}

 

Please like & share:

Lists

List is an interface of the java built-in library, implemented by:

  • java.util.ArrayList
  • java.util.LinkedList
  • java.util.Vector
  • java.util.Stack

Lists are collectors of elements like arrays, but allow easier element management. For example, they automatically shift indexes when adding or removing elements. For this reason, they are also called dynamic arrays.

The different kinds of lists do the same thing, but some are faster than others for certain tasks. Choose the one most efficient and suitable for your program.

Lists cannot take primitives as elements, but only objects. When taking primitives, they are automatically converted to an object representing the primitive (called a wrapper) first.

Import from the above package directories to use each one. Example:

import java.util.ArrayList;

 

ArrayLists

ArrayList uses a regular Array to store its elements and automatically grows or shrinks the array as needed.

Accessing elements is as fast as accessing an array’s elements, which is just one operation, because each element is in a known slot.

 

LinkedLists

LinkedList adds and removes elements faster than ArrayList, by linking elements together.

These links help to know what precedes and follows elements. Whenever an element is added between elements, new links are created.

linkedlistadd

Whenever an element is removed from the list, links are removed.

linkedlistremove

But accessing elements is slower than ArrayList, because it must traverse over elements to come to the desired element, instead of retrieving it directly.

Behind the scenes in Java, all this traversing is done by list iterators, objects of class ListIterator. Iterators can be imagined like the cursor in a text processor that moves along characters, the characters being like elements of a list.

Adding element adds it and advances the iterator position by one.

Adding element adds it and advances iterator position by one.

Adding and removal works just the same as the text processor, but remove() can only be called once after calling next() or previous(), and you cannot call it immediately after calling add().

 

Stacks

bookstack

Stacks have extra methods to create a first in, last out implementation of lists:

  • push(): push an element onto stack.
  • pop(): pop the top element out of stack, returning it.

 

Vectors

Vector here means one dimensional array, not the usual definition in mathematics.

It implements List the same way as ArrayList, except that it is a synchronized version (can be used by multiple threads). ArrayList is not synchronized.

 

Adding elements

list.add(element, index);

This inserts element into list at index. It is automatically appended to the end of list, if no index is given.

When adding, each higher element is automatically shifted up 1 higher slot.

The same object can be added to a list multiple times.

Example (try it):

List list = new ArrayList();
list.add(new Object());

 

Common Error: Confusing data size syntax

Size(), length, and length() are often confused between. The correct length syntax for corresponding data types are::

Data Type Length syntax
String length()
array length
ArrayList size()

 

Accessing Elements

list.get(index)

This returns the value held by list at index.

IndexOutOfBoundsException occurs when no element exists at that index.

 

Removing elements

list.remove(element);

This removes element from list, if it is found in list.

It does not delete element (unless the compiler finds that it is assigned to no other variable).

When removing, each higher element is automatically shifted down 1 lower slot.

Example (try it):

list.remove(obj);

 

Common Error: Forgetting that indexes shift
This often occurs in loops that iterate over a list’s indexes, like this one, which is intended to remove 10 elements from a list:

while (index < 10)
{
    list.remove(index)
    index ++;
}

Programmer here forgets that removing an element at index shifts all following indexes down by one. So when removing, the next index should then be still index. so he must actually not increment index (index++) after removing an element, or he’ll be skipping some elements (half, to be exact).

Please like & share:

Arrays

array

Arrays are objects having a sequence of values of the same type.

Array slots are 0-based, meaning their first element index is 0.

 

Declaring Arrays

type[] array;

This declares an array with slots of type.

Example:

int[] array;

 

Creating Arrays

new type[num-values]

or

new type[] {value, value, ...}

or

{value, value, ...}

First format creates array only, allocating num-values slots. In this case, all slots are automatically either set to null for object types, false for booleans, or 0 for number types (like int or float).

Latter formats both create and set elements, allocating number of slots according to number of given values.

Example (try it):

char[] array = new char[]{'a', 'b', 'c'}; //make int array with 3 elements

 

Printing Array Contents

If you need a fast representation of your array, listing of all its elements, you need to import the static toString() function of the  Arrays class, located in java.util.Arrays.

Example (try it):

char[] array = new char[]{'a', 'b', 'c'};
System.out.println(Arrays.toString(array));
//output: ['a', 'b', 'c']

 

Getting Array Length

array.length

(try it) This gives you the length of an array.

Last element is at index of array.length -1.

Array lengths are fixed, which means you need to grow the array by copying its elements to a new, larger array (Use Arrays.copy() for this purpose).

 

Accessing Elements

array[index]

This accesses element at index.

Slots range from indices 0 to array length – 1.

So,

  • array[0] is the first element
  • array[1] is the second element
  • array[array.length – 1] is the last element

Accessing a nonexistent element will give you a bounds error.

Example (try it):

data[1]

 

Assigning elements

array[index] = value

This sets array slot at index to value.

Each slot is used exactly like a normal variable would be used.

Example (try it):

String[] array = new String[3]; //make an array with 3 slots
array[0] = "test"; //change first slot to hold “test”
Common Error: Assigning to an unallocated slotThis is wrong:

int[] array;
array[0] = 1; //error: array dimension missing 

because no slots have been allocated to array yet. Ensure you do:

int[] array = new int[1];
array[0] = 1; //ok

 

 

Expanding/Shrinking Arrays

This may be needed when your array gets too filled or has too much extra space, so for both cases, we need to:

1. Create another array of desired size.

Example:

int[] a = new int[]{1,2,3,4,5}; //old array

int[] b = new int[10]; //new array

2. Copy the contents of the old array to the new array.

The static method of System.arraycopy is one way for this, which looks like:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

 

Example:

System.arraycopy( a, 0, b, 0, a.length );

 

Multidimensional Arrays

Rubik_Simple

type[][] array = new type[rows][columns];

This creates a 2-dimensional array of your type, with int numbers of rows and columns.

More dimensions can be added by more [] inserted:

type[][][][] array; // 4 dimensions

Example:

Color[3][3][3] rubikscube = new Color[3][3][3];

The ways that the slots are set are by directly setting:

array[row][col] = somevalue;

Or by a loop:

for (int row = 0; row <= array.length - 1; row++)
     for (int col = 0; col <= array[row].length - 1; col++)
          array[row][col] = somevalue;

Or with initialization by nesting curly brackets in curly brackets (try it):

int[][] array = {{1, 2}, {3, 4}}; //two rows with two columns each

An array can also have varying columns for its rows:

int[][] array = {{1, 2}, {3}}; //two rows: first row with 2 columns, second row with 1 column
Please like & share:

Access Modifiers

Access modifiers are optional reserved words that specify the accessibility of something.

They can modify variables, methods, classes, or enums.

 

Private

This means accessible to the class only.

Example:

class SecretNote
{
	private String string; // only accessible to a SecretNote
}

Outer classes cannot be declared private (but inner classes can):

private class SecretNote //wrong
{
        private String string;
}

as this would not be useful to any other class, not being instantiable by them.

Common Error: believing an object’s variables are securely private  

One may believe this class definition truly has a private variable:

class Bank
{
     private Account[] accounts;
     Account getAccount(int id)
     {
          return accounts[id];                 
     }
}

The programmer here intended accounts to be private, so hopefully not changeable. But when someone calls getAccount() to retrieve an account, that person can actually change the account, because that account is an object. Objects are mutable (changeable). A solution is to clone the returned value in the method:

return accounts[id].clone();

 

This way, the caller cannot change the original account. Someone can change the clone all they want, but it will not affect the original.

 

(no specifier)

This means only accessible to classes in the same package.

 

Protected

This means only accessible to the package and to any inheriting classes that exist outside of the package.

protected BankAccount
{
} 

 

Public

This means accessible to all.

public class Newspaper
{
}
Please like & share:

Packages & Imports

jcartier_box_1

Packages are where you store your Java files and are like the folders in your computer system: they have names and hold files.

To import is to use Java file or files from another package in a Java file.

Though optional, packages’ purpose is to organize and combine like-classes (especially when your program gets big), avoid name conflicts, and control accessibility.

 

Creating packages

package package;

This statement is placed at the top of your Java file to declare it be part of package.

Example:

package animals;
class Animal
{
}
package animals;
class Cat
{
}
package animals;
class Dog
{
}

If you do not use the package statement, the file automatically belongs to an unnamed package.

If you want a package within a package, you add a dot . to the package you want to place your new package in. Example:

package animals.amphibians;

 

 

Importing Java classes

import package.package ... file;

or

import package.package ... *;

Use the above statements to perform an import. The former format imports a single file’s classes. The latter one imports the classes of all the files in a package.

Imports are written at the top of a Java file.

Example:

import folder.file // import 1 file
import folder.folder2.* //import all of folder2’s contents

If your compiler has problems locating the file you want to import, you may want to check the CLASSPATH system variable.

 

Static imports

import static package.package...

These are imports for shortcutting to a static method or variable, to not need to write a static thing’s prefix to access it like we usually need to.

Example (try it):

import static java.lang.Math.PI;
Class Tester
{
	public static void main(String[] args)
	{
		double x = PI / 2; //don't need Math. prefix anymore for PI
	}
}

You can apply * in the import to import statically all the static things that exist in a certain file.

Example:

import static java.lang.Math.*; //all the constants from the Math file  

 

 

Naming Conventions

Packages are usually all lowercase.

Companies like to name them after their internet domain name written backwards (like org.animals).

Packages that come with Java belong in java. or javax.

Please like & share:

Characters & Strings

Characters are single letters, digits, or symbols.

Strings are sequences of characters.

 

Characters

Characters are single letters, digits, or symbols as primitives of type char.

Characters are defined by using single quotes (like ‘$’). The quotes themselves are not part of the value.

Example:

char c = 'c'; 

Characters include such called escape characters: sequences of symbols rendered (made out) to be single characters. See below for more info.

 

Strings

Strings are sequences of characters as objects of type String.

Strings are defined by using double quotes (like “string”). The quotes themselves are not part of the value.

Strings can render escape characters (like “\n” to make a new line).

String is named after stringed beads.

Example:

String s = "string";

 

String Methods

This only includes the most used ones.

Method Returned value Example
charAt(int index) A char at the specified index (position). “bat”.charAt(0) //b
concat(String str) A String with this String and str joined together (same as using +). “bat”.concat(“man”) //batman
indexOf(int ch) An int of first found index of a specified value in a String (-1 if not found). “bat”.indexOf(‘a’) //1
lastIndexOf(String str) An int of last found index of a specified value in a String. “bat”.lastIndexOf(‘t’) //2
matches(String regex) A boolean (true or false) indicating whether the String matches another String (using regular expressions). “bat”.matches(“man”) //false
replace(CharSequence target, CharSequence replacement) A String with targetCharSequence (which can be a String) replaced by replacement. “bat”.replace(“bat”, “man”) //man
split(String regex) A String[] (String array) of this String split into an array of substrings using a delimiter (using regular expressions). “bat”.split(“”) // [, a, b, c]
substring(int start, int end) A String extract of start position through a number of characters. “batman”.substring(3, 6) //man
toLowerCase() A new String of this String converted to lowercase letters. “BATMAN”.toLowerCase() //batman
toUpperCase() A new String of this String converted to uppercase letters. “batman”.toLowerCase() //BATMAN
trim() A new String of both ends of this String’s whitespaces removed. “ bat “.trim() //bat
Common Error: believing String methods change strings

String methods do not change actual String objects, but only give you new ones representing what you want.In fact, string objects are never changed. Always a new String is created on string method returns.

Example:

String cat = "CAT";
cat.toLowerCase(); //wrong: cat has not been changed
cat = cat.toLowerCase(); //this is what you want

 

Substrings

string.substring(from, to);

This extracts a part of a string.

It returns the substring from character position to character position.

Character positions start from 0.

Example (try it):

String bat = "batman".substring(0, 3); //bat is now set to “bat”
String woman = "catwoman".substring(3, 8); //woman is now set to “woman”

 

Escape Characters

Escape Character Output
\’ single quote
\” double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

These are characters not taken literally, but mean something special (like ‘\t’ meaning tab).

Purpose is for representing special characters that cannot be represented any other way.

Example (try it):

Character quote = '\"';

//using escape characters in a string:
String name = "David \"Beloved\" Hsu";
 Common error: forgetting to backslash backslashes

Remember that backslashes in strings requires an extra backslash for it to render correctly:

String path = “c:\\java\\src”; //correct

 

Joining Strings

Use the + operator to join string to string (end to end).

Example (try it):

String batman = "bat" + "man"; //result: "batman"

An argument to the operator is converted to a String, if that argument is not a String, but another is. Example (try it):

String catch22 = "catch_" + 22; //result: “catch_22”

 

Converting String to other types

Wrapper classes have a static method beginning with “parse” to convert a string into a certain primitive.

Example (try it):

int i = Integer.parseInt("123"); //I is now set to 123

 

Converting other types to String

Both object and primitive types have their own way to be converted to a String:

Objects have a method called toString(), which gives a String representation of the object. Example (try it):

Object object = new Object();
object.toString();

Primitives require wrapper classes to do it. Example (try it):

Integer i = new Integer(10); //"wrapping" 10, so we can call toString()
String s = i.toString();

You can define your own way to represent your objects as a string, by defining a public method called toString() in your class definition. Example (try it):

class MyObject
{
	public String toString()
	{
		return "my object";
	}
}

 

Comparing Strings

== tests if two Strings are identical objects.

equals() tests if two Strings have the same sequence of characters.

Example (try it):

String cat = "cat";
String cat2 = "cat";
 
boolean result;
result = cat == cat2; //false: not identical
result = cat2.equals(cat2); //true: same characters 

However, a rather strange irregularity is how testing the identity of two Strings created in this way comes out true. Example (try it):

boolean test = "cat" == "cat"; //true (!)

null is not equal nor identical to “” (empty string). Example (try it):

boolean isNullIdenticalToEmptyString = null == ""; //false


isEmpty() is often used as a shortcut for testing for an empty string: Example (try it):

boolean isempty = "".isEmpty(); //true
 Common Error: Using == to test for same charactersRemember that == is for testing identity of objects, not for same characters, in the case of Strings. I know this can be confusing, because it is not used the same way for primitives (it is used for similar value there).

 

Character Wrapper Class

A character wrapper class, Character, exists to represent the primitive char as an object.

Purposes, like with other wrapper classes, include being able to add characters to arrays and convert them to string.

Example (try it):

Character c = new Character('c');
Please like & share:

Numbers

Math Number and Symbols

6 primitive number types exist in Java:

  • 4 are whole numbers: int, short, long, byte
  • 2 are real numbers (are fractional): float, double

Example:

2 //whole number
2.33 //real number

Types differ in precision and therefore memory size, so choose types based on needed memory.

See Values for each type’s memory size.

 

Syntax

Decimal point (.) cannot be used in whole numbers, only real numbers.

Example (try it):

double x = 2.0; //ok
int y = 2.0; //wrong

Adding a decimal point to a whole number automatically makes it a real number.

Example (try ti):

double x = 1 + .1;; //1.1

Commas (,) cannot be used in numbers.

Example:

int x = 1,000; //no

Exponents are represented by the form En., and the result is a double

Example (try it):

double x = 1.2E-3; //same as 1.2 * 10^-3;

 

Common Error: Roundoff errors

Roundoff errors occur with certain numbers. For example, multiplying 4.35 gives strange results:

4.35 * 100 // 434.99999999999994

This is because computers represent numbers in the binary number system, causing digits to be lost. For this reason, some numbers like 4.35 cannot be perfectly represented by the computer hardware. In fact, no irrational number (a number with an infinite number of decimal places) can be represented perfectly by computers.

To fix this, use Math.round() function to round off the number.

Math.round(4.35 * 100); // 435

Converting types

(type) value-to-convert

Numbers can be converted from one to another by the casting (type) statement.

Example (try it):

float f = 1.0;
int i = (int) f; //set i to 1

Converting to int discards all decimal places (what is right of .). Example:

int i = (int) 1.5; //set i to 1

 

Errors

NumberFormatException occurs when trying to convert a String to a number type when it cannot. Example:

Integer.toString(“one”); //error

OverflowException occurs when trying to assign a number value outside of a type’s range. Example:

byte b = 1000000000000; //error

 

Wrapper types

Primitive Type Corresponding Wrapper Class
byte Byte
double Double
float Float
int Integer
long Long
short Short

Wrapper types are special classes that represent primitive number types as objects.

Purposes for these vary, like adding numbers to ArrayList (since they cannot take primitives), and converting between types.

Java  automatically uses wrappers to convert primitive numbers to their object counterparts when needed.

Methods belonging to each wrapper object:

  • ___Value() – Converts the value of this wrapper object to the primitive type ___ that it corresponds to and returns it.
  • compareTo() – Compares this wrapper object to the argument
  • equals() – Returns true or false whether this number object is equal to the argument.
  • toString() – Returns a String representing this wrapper object.

Static methods belonging to each wrapper class:

  • valueOf() – Returns a wrapper object representing the value of the specified primitive.
  • parse___() – Converts a String to a primitive of type ____ that the wrapper corresponds to and returns the primitive.
Please like & share: