Hosting      Domains       Support       Contacts

Java Tutorial Home 2 3 4 5 6 7 8 9

Object Oriented Programming

Using classes

In this class we will discuss:
  • Class Basics and Benefits
  • Creating Objects Using Constructors
  • Calling Methods
  • Using Object References
  • Calling Static Methods and Using Static Class Variables
  • Using Predefined Java Classes


Flow of Control
Java Classes
User-Defined Classe
Java Applet
Java Arrays
Java Exceptions
Java performance Tips

Java Frameworks
Java Collections

Classes combine data and the methods (code) to manipulate the data, you can think of a class as a template used to create specific objects. From that template you can instantiate (create) many objects. All Java programs consist of at least one class.

Example Student class

Data: name, year, and grade point average
Methods: store/get the value of each piece of data, promote to next year, etc.
An instance of the Student Class would look like this:
    Student Object: student1
     Data: John Doe, Sophomore, 3.2

Object Terminology:

Object reference: identifier of the object. Object reference holds address of object ClassName objectReference; or ClassName objectRef1, objectRef2; Example: Date d1;

Instantiating an object: creating an object of a class. Objects MUST be instantiated before they can be used. Call a constructor using new keywordConstructor has the same name as class. Syntax: objectReference = new ClassName( arg list ); Arg list (argument list) is comma-separated list of initial values to assign to object data.Date independenceDay;independenceDay = new Date( 7, 4, 1776 );Date defaultDate = new Date( );

Constructor: special method that creates an object and assigns initial values to data. Date( ) is the constructor of the Date class that creates a Date object with initial month, day, and year values of 1, 1, 1999 for example.

Instance of the class: the object.

Methods: the code to manipulate the object data.

Calling a method: invoking a service for an object (sending a message to an object via invoking it method). For example

     WebName SiteName = new WebName();
   SiteName.setName(“Tech”, “HostITWISE.COM”); setName is a method of the WebName class.

Instance variables: variables defined in the class and given values in the object.

Fields: instance variables and static variables (we'll define static later).
Members of a class: the class's fields and methods.
Fields can be: any primitive data type (int, double, char, long, boolean, etc.) or objects.
Instance data this category of data is the internal representation of a specific object. It records the object’s state. Example:

public class Name {
// Instance variables
String first;
String middle;
String last;

Class data this category of data is accessible to all objects of a class (one copy for all objects, unlike instance data where there is a copy for each object of a class). Fields declared as static belong to the class rather than to a specific instance. For Example:

public class Name {
// Class constant
static final String PUNCT = “, ”; . . .

To call class (also known as static data or fields) we use the dot notation with the class name as opposed to the instance or object name (Color.BLUE; Name.PUNCT;)

Local data this category of data is specific to a given call of a method (data that is local to that method). The JVM allocates space for this data when the method is called and deallocates/Destroys it when the method returns.

        public int compareTo(Name otherName) {
                        int result; // Local variable
                        . . .
                    return result;

Encapsulation Instance variables are usually declared to be private, which means users of the class must reference the data of an object by calling methods of the class (set and get methods). Thus the methods provide a protective shell around the data. We call this encapsulation. Benefit: the class methods can ensure that the object data is always valid.

Reusability, when reusing a class its code is already written and tested, so you build a new application faster and it is more reliable. For example: A Date class could be used in a calendar program, appointment program, or online shopping program. To reuse a class you don't need to know how the class is written. You do need to know the application programming interface (API) of the class. The API is published and tells you: how to create objects, what methods are available, and How to call the methods.

Class method is a method that belongs to a class rather than it object instances; has modifier static: Date.setDefaultFormat(Date.MONTH_DAY_YEAR); class methods also called static methods can be called without instantiating an object. In the method API, keyword static precedes return type in static methods. To call a static method we use dot syntax with class name instead of object reference. Syntax: ClassName.methodName( args ).
Example: int absValue = Math.abs( -9 ); abs is a static method of the Math class that returns the absolute value of its argument (here, -9).

Class field is a field that belongs to a class rather than its object instances; has modifier static.

Value-returning method is a method that returns a value to the calling program.


String first; String last;
Name name;
System.out.print(“Enter first name: “);
first = inData.readLine();
System.out.print(“Enter last name: “);
last = inData.readLine();
name.setName(first, last);

public String firstLastFormat() //firstLastformat is a value returning method
return first + “ “ + last;


Using Java Predefined Classes, Included in the Java SDK are more than 2,000 classes that can be used to add functionality to your programs APIs (the complete list is published on www.java.sun.com. in this class we will cover reusing the following Java predefined classes/objects:

  • The String Class
  • Using System.out
  • Formatting Output
  • The Math Class
  • The Wrapper Classes
  • Dialog Boxes
  • System.in object
  • Console Input Using the Scanner Class

Classes are grouped in packages according to functionality here are some packages examples:


java.lang this package includes basic functionality common to many programs, such as the String and Math classes
java.awt this package includes graphics classes for drawing and using colors
javax.swing this package includes user-interface components
java.text  this package includes classes for formatting numeric output
java.util this package includes the Scanner class and other miscellaneous classes

Classes in java.lang are automatically available to use. Classes in other packages need to be "imported" using this syntax:

import package.ClassName;


import package.*;


import java.text.DecimalFormat;


import java.text.*;

The String Class

A string is a representation of a sequence of characters. A string is a sequence of characters enclosed in double quotes. For example “Noha and Adam” , “I Like Arthur.”
“A” (a one character string) are strings. The empty string contains no characters and is written as “”. The String class constructors are as follows:

String( String str ) allocates a String object with the value of str, which can be String object or a String literal.

String( ) allocates an empty String
Strings can be concatenated (attached to each other) using the + operator.
For example:

final int DATE = 2003;
final String phrase1 = “I like to eat apple “;
final String phrase2 = “and banana “;
String songTitle;
bookTitle = phrase1 + phrase2;

String class API (methods):


API Description Example
int length( ) returns the number of characters in the String   String hello = "Hello";
int len = hello.length( );

The value of len is 5
String toUpperCase( ) returns a copy of the String will all letters uppercase  String hello = "Hello";
hello = hello.toUpperCase( );

The value of hello is "HELLO"
String toLowerCase( ) returns a copy of the String will all letters lowercase String hello = "HELLO";
hello = hello.toLowerCase ( );

The value of hello is "hello"
int indexOf( String searchString ) returns the index of the first character of searchString or -1 if not found   The index of the first character of a String is 0.
String hello = "Hello";
int index = hello.indexOf( 'e' );

The value of index is 1.
int indexOf( char searchChar ) returns the index of the first character of searchChar or -1 if not found  
String substring(int startIndex, int endIndex) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index ( endIndex – 1 ) String hello = "Hello";
String lo
= hello.substring( 3, hello.length( ) );
String toString( ) converts the object data to a String for printing All classes have a toString method. (they inherit the toString method of the object class automatically)

The Math Class

Comes with java.lang and hence is automatically available 9no need to import it). Most Java Math Class Constants and methods are static, ie. you use the class name rather than instantiating an object first.

Java Math Class constants: Two static constants
PI - the value of pi 3.141592653589793
E - the base of the natural logarithm 2.718281828459045


   System.out.println( Math.PI );
   System.out.println( Math.E );

output is:

- The most important thing is to remember is that they are static and can be called with the Math class name.
min/max. Is the min method overloaded? Yes. i.e. if you pass two doubles rather than an integer it will return a double.
Overloading example:

   Math {
    int min(int one, int two) {
     if t1 > t2
     return t2
    return t2

if you enter 2.3 and 2.7 and this is considered equal because of the int or you can use overloading with this double min(double, double) { }
The name is overloaded but the compiler knows how to compile depending on how
you call it and what parameters you use.

public class Minimum {
            public static void main( String [] args ) {
                 int number1, number2;
                 number1 = ( int ) ( Math.random( ) * 101 );
                number2 = ( int ) ( Math.random( ) * 101 );
                System.out.println( "The numbers are " + number1 + " and " + number2 );
                int smaller = Math.min( number1, number2 );
                System.out.println( "The smaller number is " + smaller );

Random numbers: pseudorandom - if you use the date as the seed, you can get two of the same number in a row if you do it fast enough.

public class myMathRandomMethod1 {
          public static void main( String[] args ) {
                double d = Math.random( );
                System.out.println( "My random number is " + d );
                 int die = 1 + (int)( Math.random( ) * 6 );
                System.out.println( "\nThe die roll is " + die );

public class myMathRandomMethod2 {
        public static void main( String[] args ) {
            int start = 33, end = 201;
            int number = start + (int)( Math.random( ) * ( end - start ) );
            System.out.println( "\nMy random number between " + start
                      + " and " + ( end - 1 ) + " is " + number );

- Typecasting - casting output of random, which is always double to turn to an integer.

Methods of the Math Class

All Methods of the Math Class are static

dataTypeOfArg abs( dataType arg )

 returns the absolute value of the argument arg, which can be a double, float, int or long.

double log( double a )

 returns the natural logarithm (in base e) of its argument.

double sqrt( double a )

returns the positive square root of a
double pow( double base, double exp )  returns the value of base raised to the power of exp

Wrapper classes:
- Java gives 8 primitive data type (double float long int short byte char boolean), i.e. given by the compiler. In event driven programmer there are many methods that require an object not a primitive. So java wraps these to give you an object of a primitive type. Wrapper classes "wraps" the value of a primitive data type into an object which is useful when methods require an object argument and also useful for converting Strings to an int or double.

Primitive Data  Type Wrapper Class
double  Double
float Float
long Long
int Integer
short Short
byte Byte
char Character
boolean Boolean

Example to convert int variable to an Integer object: int intValue=12;

Integer IntObject = new Integer(new Value);
or you can use autoboxing (wrapping):
Integer intObject = intValue (instantiation above doesn't need to be as above.)
There is also unboxing from Integer to int:
int inValue2 = intValue * intObject; (The Compilier converts intObject to int primitive to do this correctly.)

- Every wrapper class has a parse method to accept a string and turn it into an integer. This is useful because you read information in as strings but to do math operations you have to convert to the datatype.

- parseInt returns String as primitive datatype
- valueOf method returns object of Integer
Wrapper classes Example:

public class WrapperExample {

public static void main( String[] args ) {
int intPrimitive = 923;
Integer integerObject = intPrimitive;
System.out.println( "The int is " + intPrimitive );
System.out.println( "The Integer object is " + integerObject );
int sum = intPrimitive + integerObject;
System.out.println( "The sum is " + sum );
int i1 = Integer.parseInt( "65" ); // convert "65" to an int
Integer i2 = Integer.valueOf( "65" ); // convert "65" to Integer
System.out.println( "\nThe value of i1 is " + i1 );
System.out.println( "The value of i2 is " + i2 );
double d1Primitive = Double.parseDouble( "57.22" );
Double d2Object = Double.valueOf( "58.22" );
System.out.println( "\nThe value of d1 is " + d1Primitive );
System.out.println( "The value of d2 is " + d2Object );


Autoboxing, conversion between a primitive type and a wrapper object when a primitive type is used where an object is expected
Integer intObject = 42;
Unboxing, automatic conversion between a wrapper object and a primitive data type when a wrapper object is used where a primitive data type is expected
int fortyTwo = intObject;

The Figure below shows Java Primitive Data Types

Using Dialog boxes
- JOptionPane from javax.swing with only two methods: showInputDialog for inputting values and showMessageDialog for sending messages to user. To use this you must import the class. You can use import javax.swing.*, but then you get every class in java.swing and this will bloat your program. Whatever the user types comes in a string. You have to convert it to use it in your program. Dialog boxes Example

import javax.swing.JOptionPane;
public class DialogBoxExample {
  public static void main( String [] args ) {
    String input = JOptionPane.showInputDialog( null,"Please enter your Age" );
    int age = Integer.parseInt( input );
    JOptionPane.showMessageDialog( null, "Your age is " + age );

    double average = Double.parseDouble(JOptionPane.showInputDialog( null,"Enter your grade point average between 0.0 and 4.0" ) );
   JOptionPane.showMessageDialog( null, "Your average is "+ average );

User interface
- Provides clear prompts for input, prompts should be clear and describe data requests and any restrictions. We will discus in details all aspects of a GUI including event driven programming later.

Java Console (System.in object)
System.in and Scanner will allow multiple lines to be read. System.in:
Input streams- Reader and writer attached by stream.
- This has a producer consumer pattern with a writer that writes to a stream and a reader that reads from it. A stream generalizes input and output. Keyboard electronics different from disk input stream makes keyboard look like disk for example.

Input streams

- system.in is the default reader which reads characters from keyboard which can be used many ways, i.e. directly (low level access) read one character at a time and then connect each character.

- You use layers of abstraction to convert from char to string. System.in Object
Layers are:

- System.in(returns bytes) -> InputStreamReader (takes bytes returns unicode
char) -> BufferReader class (gets characters and returns strings) . The figure below shows these layers as well

to read from the consul using system.in use the following command:
BufferReader inStream = new BufferReader( new InputStreamReader(System.in))
and then use inStream object to invoke the read() and readline methods as follows:

// Read a line from the user as a String
  System.out.print("Enter your first name: ");
firstName = inStream.readLine();

// Read a character from the user
  System.out.print("Enter your middle initial and last name: ");
middleInitial = (char) inStream.read();

// Read a line from the user as a String
  lastName = inStream.readLine();

// Display the strings
  System.out.println("Your name is " + firstName + " "+ middleInitial + ". " + lastName);

Input Streams: Read Characters

- System.in is the default standard reader for the keyboard. This can be other devices.

- System.out does not print to a screen, it prints to a buffer so you have to
flush it to the output device (i.e. screen)

- The read method in System.in returns one integer, doesn't really return an "f" it returns a representation in bytes, so you have to typecast to char. Input Streams: Read Characters . System.in.read () returns -1 if EOF is returned so you can use this condition in a loop to continue to read.

Scanner Class
Provides methods for reading byte, short, int,long, float, double, and String data types from the Java console Scanner is in the java.util package Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.).

A Scanner Constructor
Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console. Example:
Scanner scan = new Scanner( System.in );

Scanner Class methods

DataType nextDataType( )

  returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean.

String next( )

  returns the next token in the input stream as a String

String nextLine( )

returns the remainder of the line as a String

Input Streams: Read Strings
Scanner class, Scanner class gives methods to read rather than using the mess you have to get to use the System.in.

 import java.util.Scanner;
   public class InputExample {
     public static void main( String [] args ) {
      Scanner scan = new Scanner( System.in );
      System.out.print( "Enter your first name > " );
      String firstName = scan.next( );
      System.out.println( "Your name is " + firstName );
      System.out.print( "\nEnter your age > " );
      int age = scan.nextInt( );
      System.out.println( "Your age is " + age );

- You need to import the Scanner object. This is defined to read from eyboard(System.in) but you could use a file or other input device. scan.next just returns a token which is input up until EOL - sequence of characters separated by white space. scan.nextDatatype gets types of float double and such

import java.util.Scanner;
     public class CharInputExample {
       public static void main( String [] args ) {
      Scanner scan = new Scanner( System.in );
      System.out.print( "Enter any letter:" );
      String initialS = scan.next( );
      char initial = initialS.charAt( 0 );
      System.out.println( "You entered" + initial );


Java Tutorial Home 2 3 4 5 6 7 8 9


Java Tutorial

| Home | Hosting | Domains | Support |  Contacts |
Terms & Condition | Privacy Policy |


Copyright © 2005 by HostItWise.com Read our Copyright. All rights reserved.

LasX.com | Garage Door Company | RushRash Inc