Home arrow Java & J2EE arrow Page 3 - Java Object Initialization and Creation

Java Object Creation Example using Coffee - Java

Initializing your objects is an important part of coding in Java, if you care at all about managing your memory. You will also find that properly initialized object creation leads to fewer problems with bugs. This article will explain what objects are in Java, why you should initialize them, and how to accomplish the task of safely creating Java objects.

  1. Java Object Initialization and Creation
  2. What is a Java Object and why would I initialize one?
  3. Java Object Creation Example using Coffee
  4. Initializing a Java Object Summary
By: Katie Gatto
Rating: starstarstarstarstar / 10
August 19, 2008

print this article



For example, if you wanted to create a virtual coffee cup, and then fill it with virtual coffee, your code would look like this:

// In Source Packet in ex2/CoffeeCup.java

// Approach 1

class CoffeeCup {

private int innerCoffee = 355;

// no constructors defined in this version of CoffeeCup


Or an acceptable alternative version of the code to initialize your object could look like this:

// In Source Packet in ex5/CoffeeCup.java

// Approach 3

class CoffeeCup {

private int innerCoffee;

// Only two constructors defined in this

// version of CoffeeCup

public CoffeeCup() {


public CoffeeCup(int startingAmount) {

if (startingAmount < 0) {

String s = "Can't have negative coffee.";

throw new IllegalArgumentException(s);


innerCoffee = startingAmount;





>>> More Java & J2EE Articles          >>> More By Katie Gatto

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates


Dev Shed Tutorial Topics: