COS 212 Resources

COS 212 Resources

  • Docs

›Java Crash Course

Getting Started

  • Introduction
  • Installing Linux
  • Development Environment

Java Crash Course

  • Hello World
  • Compiling and Running
  • Makefile
  • Comments
  • Variables and Types
  • Operators
  • Slides

Tools

  • Version Control
  • Hello World with Git

Notes

  • Self Organising Lists

Variables and Types

TypeSizeRange
booleandependstrue, false
char2 bytesUnicode characters
byte1 byte[-128, 127]
short2 bytes[-32768, 32767]
int4 bytes[-2147483648, 2147483647]
long8 bytes[-9223372036854775808, 9223372036854775807]
float4 bytes[-3.4E38, 3.4E38]
double8 bytes[-1.7E308, 1.7E308]

Source: Drozdek, A. (2013). Data structures and algorithms in Java. 4th ed. Singapore: CENAGE Learning.

  • Unlike C++, Java has a boolean type which does not support numeric operations

Declarations

<type> <name>

Examples:

int myInt = 5;

boolean myBool = false;

char capitalC = 'C';

// Floating-point literals are 64 bit by default, therefore
// needs to be cast for `float` type
float myFloat = 45.64f;
float myFloat = (float) 46.64;

Wrapper Classes

The above data types are Primitive Data Types, they are the only types that are not Objects.

Many classes in the java.util package operate on Objects such as Integer and Boolean. Note that the Java platform will box the primitive type in its wrapper class for you when a method expects an Object. Similarly it will unbox the Object if a method expects a primitive. See Autoboxing and Unboxing.

There are some cases when you want to use an Object instead of a primitive:

  • When converting between numbers and strings
    Integer myInt = 5;
    String myString = myInt.toString();
    
    Integer MyInt = Integer.parseInt("5");
    
  • When a method expects an Object

Primitive type and corresponding wrapper class:

Primitive typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble

Further Reading (Optional)

  • The Number Classes
  • Autoboxing and Unboxing
Last updated on 2/9/2019 by Evert Geldenhuys
← CommentsOperators →
  • Declarations
  • Wrapper Classes
    • Further Reading (Optional)
COS 212 Resources
Docs
Getting Started
GitHubStar
Facebook Open Source
Copyright © 2019 Evert Geldenhuys