+ All Categories
Home > Documents > 41424702-Java-eBook

41424702-Java-eBook

Date post: 12-Oct-2015
Category:
Upload: srinivasa-helavar
View: 60 times
Download: 0 times
Share this document with a friend
Description:
cc

of 258

Transcript
  • 5/21/2018 41424702-Java-eBook

    1/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    1

    THE COMPUTER SCIENCE TUTORING CENTER

    www.cscourses.com

    JAVA PROGRAMMING COURSE E-BOOK

    Lesson 1 JAVA PROGRAMMING COMPONENTS AND VARIABLES

    Lesson 2 JAVA CLASSES AND REFERENCE VARIABLES

    Lesson 3 JAVA OPERATORS, BINARY NUMBERS AND CONDITIONS

    Lesson 4 JAVA STRING OBJECTS AND ARRAYS

    Lesson 5 JAVA METHODS

    Lesson 6 OBJECT ORIENTED PROGRAMMING

    Lesson 7 JAVA PROGRAMMING STATEMENTS

    Lesson 8 JAVA INPUT AND OUTPUT STREAM CLASSES

    Lesson 9 INHERITANCE AND ENCAPSULATION

    Lesson 10 POLYMORPHISM

    Lesson 11 JAVA CLASS COMPONENTS

    Lesson 12 ABSTRACT CLASSES AND INTERFACES

    Lesson 13 VECTORS , ENUMERATIONS AND ITERATORS

    Lesson 14 ARRAYLIST AND EXCEPTIONS

    Lesson 15 JAVA PROJECT 1

  • 5/21/2018 41424702-Java-eBook

    2/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    1

    JAVA PROGRAMMERS GUIDE LESSON 1

    File: JavaL1.doc

    Date Started: July 12,1998

    Last Update: Dec 28, 2005

    Java Version: 1.5

    INTRODUCTION

    This manual introduces the Java programming language techniques and concepts. Java is a nelanguage designed for Internet programming. When you connect to a WEB page a Java appletmabe downloaded to your browser to start a special effect on your screen. An applet is a prograwritten in Java. The Java language has built in interfaces to the Internet. The Java language has nofound it way into the University environment. It is a great teaching language, it is rich in graphicand good language constructs. Java uses the Object OrientedProgramming(OOP) approach. Thapproach uses a programming language to describe an object. What is an Object? An Object is a

    everyday thing, a car, house, table or even a person. Every object has an appearance and doesomething. A car has a shape, a color and moves. The object oriented programming approacwants to represent everyday objects in a programming language. How can it do this? programming language can store the appearance of an object as a value in the computer memory.programming language also has programming statements that are instructions telling thcomputer what the object does. When a computer stores information about an object, the storeinformation is known as data. The data is information that describes the objects and is stored in thcomputer memory. The location where the data is stored is represented by a variablehaving name. A programming statement is used to describe what an object does and is translated intcode. Code is used to run on the computer to perform some action or operation for the object. Thcode is the translated instructions telling the computer what to do. The programming languaggroups programming statements together into what is known as a method. A method is a collectioof programming statementsthat get translated into code and runs on your computer. Before yocan have an object you need a definition of the object.A classis used to define an object. The clalists all the methods and variables needed by the object. Aclassdefines the variables for the objeand the code used to access the datain the object. The same code can be used for many of thsame objects. Think that a class is the drawings or a plan to build a house. When the house is madthen it is an object. When you class runs on the computer it is an object. An object is allocatememory for the data variables defined in the class.

    CLASS (definition)

    Variables

    Methods(Programming Statements)

    OBJECT ( computer memory )

    Data

    (storage for variables

    Code to access data in object(what object does )

  • 5/21/2018 41424702-Java-eBook

    3/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    2

    Objects are created in the computer memory from the class definitions. The class definitions tewhat data and methods your object needs. Memory in the computer is allocated for the variabledefined in the class definition. It is these created objects that use computer memory for datawheyou run your Java program. The Object Oriented Programming approach will enable you to organizyour programs so that your programming tasks will be much easier to accomplish. Answer thquestion: What is the difference between a class and an object?

    This manual teaches by using the analogy approach. This approach makes it easier for you tunderstand new concepts by comparing the operation to common known principles. We also use thseeing approach, the words we use, are carefully chosen so that you get a picture of what happening. Visualizationis a very powerful concept to understanding programming. Once you gethe picture of what is happening then the programming concept is much easier to understand anaccomplish. It is very important to visualize and see things as a picture rather than trying tunderstand by reading and memorizing textbooks. Pictures are made up of words. This documendoes not cover all details of Java programming but acts as a guide so that you can get started righaway with Java programming. The main purpose of this document is to introduce, and teach yoJava and Object Oriented Programming techniques. You should have a textbook as a companion tlook up important terms for clarification or for more in depth study. Good textbooks are:

    Title Author(s) Publisher Web page

    Core Java Volume 1 Gary Cornell, Cay s. Horstmahn SunSoft Press http://www.horstmann.com/corejava.html

    PURPOSE OF PROGRAMMING LANGUAGES

    The purpose of a programming language is to direct a computer to do what you want it to do. Imost cases of beginners the computer tells the programmer what to do. Good programmers are icontrol of the computer operation. A computer program lets the user enter data from the keyboarperform some calculation to solve some problem and then displays the results on the computescreen. The user can store input and output data on a data file for future use.

    LESSONS AND ASSIGNMENTS

    You may use these lessons as a study guide or to learn java programming. There are 14 lessons ithe Java course, where the last lesson is a java project. Each lesson consists of exercises that yocan send in for marking. You should understand all the material and do all the exercises in eaclesson before proceeding to the next lesson. There is a marking charge of $15 for each lessonAdditional java tutoring is available from $15 and up. Grading is based on the assignments. (P) Pas(G) Good and (E) Excellent. Excellent is awarded to students with outstanding programs that involvcreativity and works of genius. Good is awarded to students that have exceptional workinprograms. Pass is awarded to students that have minimal working programs. Important conceptand Java keywords are introduced in bold. Keywords are the words a programming language made up of. Language definitions are in p u r p l e i t a l i cs and statements are in blueandcomments green.

    Send all solutions to assignments [email protected] ($15 marking charge)

    Java tutoring by email or telephone is also available from $15 per hour.

    Send all programming questions and the Java code you have started to [email protected] a quote (tutoring starts from $15)

  • 5/21/2018 41424702-Java-eBook

    4/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    3

    LESSON 1 JAVA PROGRAM COMPONENTS AND VARIABLES

    JAVA PROGRAM FORMAT AND COMPONENTS

    A Java program is made up programming components usually arranged in a predefined format. Bfollowing a proven format, your programs will be more organized and easier to read. A Java progra

    contains packages, import statements, classes, and methods, programming statementvariables andoperators. Packages are used to groups classestogether that have something common.Import statements are used toinclude system or user packages that contain classes thyou mayneed for your program.A class declares anddefines the variablesand methodsneedeby anobject. A classdefines an object.Variablesare used to storeand retrievedata valueMethodsare what the class object uses to perform the tasks it needs to do. Methods are made uof variables and programming statements. Programming statements are instructions used direct the flow of program execution. Statements are made up of variables and operatorOperatorsperform operations on variables like addition and subtraction. Think that a Java programhas many different layers each depending on each other: A Java program is an organized collectioof components.

    Commentsdescribe what the

    program does

    Package (optional)contain classes

    Import Statementsinclude packages

    Classescontain variables and

    methods

    Java Program

    Classvariables shared between all

    methods in class

    Variables

    collection ofMethods

    Packagecollection of classes

    group of Classes

  • 5/21/2018 41424702-Java-eBook

    5/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    4

    We will study each component individually. You do not need to understand every thing right nowThe most important thing is that you are introduced to all the terminology and the componentthat make up a Java program. Analogy to a Java program is what cities and towns are made up oTowns are made up of neighborhoods, neighborhoods are made up of streets, streets are made u

    of homes, homes are made up of people etc. A minimal Java program has only one class. A Javprogram may be written as an appletor a non-applet. Applets are Java programs that run on yoweb browser. Non-applet programs are known as standalone applicationsthat run directly on yocomputer. In the first few lessons, we will deal with non-applet programs. We will deal with applein future lessons. For a non-applet Java program a minimal class has one method called the mamethod. The mainmethodis the first method to run in a Java standalone program. When a Javprogram runsit means it is executing programming statements contained in a method. You run Java program by executing a class file that contains a main method. I call this class the "runninclass", the class that starts your Java program. The Java program that you type in is stored in a fihaving thejava extension. The file that has the class with the main program in it should have thsame name as the class name. Each class is usually kept in a separate file having the same name athe class. The file name and class name is case sensitive meaning upper and lower case character

    are considered different. Before a Java program can run it must be compiled to an intermediatexecution file made up of byte codes having the extension " *.class ".If your Java program habeen written as an applet then it is this class file that runs on your internet browser. Java programnot written as an applet are run on your computer using the Sun Microsystems JDK. The JDinterprets the byte code. The interpreter is known as a virtual machine (VM). This means Java carun on any computer machine that has the JDK.

    package

    class

    variables

    methods

    Methodscollection of statements

    TemporaryVariables

    Programming

    Statements

    Variablesand

    Operators

    Programming Statementsinstructions telling the

    computer what to do

    programming

    statements

    temporary

    variables

    andoperators

  • 5/21/2018 41424702-Java-eBook

    6/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    5

    JDK (Java Development Kit)

    The JDK is used to compile a Java source program into an execution class file so that your programcan run. The class file is run directly on your computer using the JDK. You can run applets on yocomputer without a web browser by using the JDK applet viewer. When your program is runninthe byte codes are interpreted by the JDK. An Integrated Development Environment (IDE) is

    complete Java development system. Most IDE'S have the JDK built into them. There are many JavIntegrated Development Environments on the market from IBM, Sun Microsystems, JCreater, anBorland.

    Program Translates Execution JDK (standalone)

    Java source file -->

    compiler --> class execution file Running

    *.java

    MyClass.javaJDK

    javac MyClass.java*.class

    java MyClassWeb Browser

    (applet)

    The typed in Javaprogram that contains

    all the packages,classes variables and

    methods.

    Translates the Javasource code into

    execution byte code

    Contains executioncode (Byte Code)

    and reservedmemory locations

    for data variables

    The JDK calls the mainor init method from the

    execution class file andthe program runs

    Downloading JDK

    To run java programs you should download the JDK from Sun Microsystems. They named the JDK

    J2SE 5.0 this is the newest version.. It is best to use the newest version. You can download the J2S5.0 from

    http://java.sun.com/j2se/1.5.0/download.jsp

    You have many choices here just select JDK 5.0 Update 6. To install down load the exe file thenrun. Java will be installed and automatically set up for you.

    We will write, compile and run our first java program soon. But before we do this you will need thefollowing background information.

  • 5/21/2018 41424702-Java-eBook

    7/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    6

    Compile time and run time

    Compile time is the time when the compiler is compiling your program into an execution filDuring compile time the compiler is checking your program for errors. If you have errors in yoprogram you have to fix them and then re-compile. During compile time the compiler will conveyour Java programming statements into execution code and reserve memorylocations for you

    data variables and compiled code. When the compiler reserves memory locations for your datvariables and compiled code and places them inside the class execution file.When your prograruns, the class execution file is loaded into your computer running the JDK. The JDK gives you sommemory to run your program. The size of the memory depends on the size of your class executiofile. We call this memory programor class memory and is said to be reservedmemory. It is atfixed size and never changes. Some methods are static meaning they can be used directly from thclass execution code. When your program is running it may need additional memory for objeccalled object memory. The additional memory comes from your computer memory in run time anis allocated memory. Objects are created in computer memory during run time from the clasdefinitions defined in your program. What is the difference between compile time and run time What is the difference between a class and an object ?

    additional memoryrequested

    by running program

    memory allocated

    for objects whenyour program is

    running

    memory forOBJECTS

    (always changing)

    *.javatyped

    injavaprogram

    *.class

    class file created

    in compile time

    class file loaded by JDK

    into your computermemory to run program

    (contains all class code)

    memory reserved

    for your programwhen it is loaded

    contains all class code

    and STATIC variables

    Why do we need additional memory when a program is running ? A good example is a telephonbook program. When someone writes the program they do not know how many telephones entriethe book is going to have. For every person needed in the telephone book there must be enougmemory for the persons name, address and telephone number. When the program first runs it wask the person how many entries the telephone book will have. As soon as the person enters thnumber the program must go to the computer memory and get enough memory for 100 entrieAlternatively you could just add additional memory when you add entries to your telephone booYou allocate memory in run time when you do not know how much memory you need. You reservmemory in compile time when you know how much memory you need. If you knew how manpeople you have in your telephone book then you could of reserve memory in compile time. You wsoon learn how to reserve memory in compile time and allocate memory in run time.

    JAVA PROGRAM COMPONENTS

    We will now discuss in depth all the components of a Java program. In Java you will see curbrackets like these { } all the time. They are used to group statements together in a method omethods in a class. Classes are made up of methods, methods are made up of statements, anstatements are made up of variables and operators. Operators perform operations on variables likadding or equating.

  • 5/21/2018 41424702-Java-eBook

    8/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    7

    Comments

    All programs need comments to explain to the user how the program works, what the variablerepresent and to define the purpose of classes and methods etc. You may place comments anywhein your Java program. The compiler ignores comments. They are just there for the people who reayour Java program. A comment starts with a /* and ends with a */.

    /* My first Java coment */

    A comment may also start with a "//" . The end of the comment is assumed to be the end of theline.

    // Lesson 1 Program 1

    Packages

    Packages are optional and used mostly in large programs involving many classes. Packages alloyou to group a collection of classes together that have a common purpose. A Package includes manclasses. A class may import classes from a package.

    Importing Java pre-built classes

    Import statementsare used to include Java classes contained in a package. Each package has class that performs Input/Output, math functions, language implementation etc. Each class hamany methods so that you can easily get your Java program up and running quickly. The purpose pre-defined classes is to relieve the programmer of all burdens. System source code files includinput/output classes that allows you to get data from a keyboard or file system, send information tthe computer screen, store data on an output file, make a connection to the internet etc. All of thJava system classes you useare imported from packages. You will get used to all the packages

    Java because you are always forced to use them. The compilerneeds to know what packages yowant to use when it compiles your program. You use the import statement to use packages.

    . i m p o r t p a c k a ge _ n a m e . * ;

    import java.io.*;

    program using a package

    package

    class

    class

    class

    class

    a class in a program importinga package to use

    a package

    contains many

    classes

  • 5/21/2018 41424702-Java-eBook

    9/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    8

    When you import a package you get to use all the classes in that package. In our example owe havimported thejava.io package and all of its classes. This package contains all classes needed for I/OI/O means all the input and output streams classes needed to read data from a keyboard, seninformation to a file etc. We will study all the Java I/O streams in this course. The * means import all classes in the java.iopackage. If you just want one class in this package then you caspecify it by name.

    i m p o r t p a c k a g e _ n am e .c la s s_ n am e ;

    import java.io.BufferedReader;

    Most people don't know all the names they want in a package so they use * to get all classebelonging to that package. Java automatically imports the java.lang .* package for you. Thpackage contains all the basic Java classes to compile and run your programs like the System anString classes. Don't forget the semicolon at the end of the package name in the import statement

    writing your own package

    You can also write your own Java packages, just to store you very own classes. To make yourclasses belong to a package you just put the name of the package at the beginning of your Javasource code file. All classes in this file will now belong to your package.

    p a c k a g e p a c k a g e_ n am e ;

    package student;

    You must be careful in using packages of the same name. Some Java development tools willoverwrite classes having the same name with the same named package without warning. You willloose all your original code. Always make sure all your package names are unique.

    importing your own package

    You can also import your own packages. To use your own package you must also use the importstatement.

    i m p o r t u s e r _ p a c k a g e_ n am e .* ;

    import student.*;

    The "*" means use all classes in your package. If you just want to use a specific class of a packagethen you just specify which class you want:

    i m p o r t p a c k a g e _ n am e . c l as s_ n am e ;

    import student.Calculate;

  • 5/21/2018 41424702-Java-eBook

    10/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    9

    CLASSES

    A classdefines all the variablesandmethods that your objectwill need. A class is defined bylevel of visibility, the classkeyword, the class nameand the required variablesand methodThe open curly bracket { means to begin something the closed curl bracket } means to ensomething.

    v i s i b i l i t y c l a s s c l a s s_ n am e

    {

    v a r i a b l e s

    m e t h o d s

    }

    // example classpublic class L1p1

    {

    public static void main ( Strings[ ] args )

    {

    System.out.println("hello");

    }

    }

    class visibility

    The level of visibilitystates who can use this class. Visibility for classes can be public or friendlyIf the visibility is not specified the default visibility is assumed to be friendly. The visibility of ouexample class is public. Visibility is like a protection mechanism where the programmer can chooswho can access the class.

    class visibility description

    public means all other classes can access this class

    friendly

    (default)

    means only classes in the package or file can access this class

    (classes defined in the same file are considered to be in the same package)

    There is no friendly keyword. Friendly visibility is the defaults visibility when you do not specify visibility.

    class

    method

    method

    main method

    variables

    access ublic classesfile or package

    public class

    friendly class

    friendly class

    some other class in a

    different package

    cannot access

    friendly classes

    some other class

    in same package

    can access

    friendly classes

  • 5/21/2018 41424702-Java-eBook

    11/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    10

    class name, variables and methods

    The classkeyword indicates the following block of code is to be a class definition. All classes need name so that the programmer and compiler can identify it. The name of our example class is L1PThe variables and methods belonging to a class are enclosed by curly brackets { }. The variables a class are shared between all methods in the class. This is why classes were invented so that w

    could have a collection of methods all sharing the same variables. This is a highly desirable thing tdo, it allows your programs to be highly organized and stops data corruption. Data corruption avoided because we now know which methods access the data. All classes start with a CAPITAletter where methods start with a lower case letter. You need to define a class before you can makan object of it. A class definition is like the recipe to bake a cake. You need a recipe before you cabake a cake. When a cake is baked it is ready to be eaten. Obviously you cannot eat a recipe! Wheyour program is running objects are constructed in the computer memory from your clasdefinitions defined in your program. A class contains variables and methods. Just like a cakneeds ingredientsand the needed instructionsto bake the cake. Variables are used to store anretrieve data. The variables in a class are shared between all methods in the class and retain thevalue. This is the main reason we have classes is that we want a bunch of methods to share thsame variables! A class also defines all the methods needed by the object to access the datMethods contain variables and programming statements. Variables in a method are used fotemporary storage where the programming statements are the instructions telling the computewhat to do. The variables in a methods do not retain their values and are said to be temporary. Onwhen a methods is used will the variables contain a value. After a method is finished running thvariables values disappear. We will study methods in future lessons. In this lesson we wconcentrate on variables.

    LESSON 1 PROGRAM 1

    A simple Java program only needs a class and a main method. The main method is the firmethod to be executed when the Java program first runs. Each class can have its own main methoAll class names in Java start with a CAPITAL letter, where method names start with a lower casletter. The following Java program has a class called L1p1 and is publicmeaning everybody can us

    it. Our example class just has a main method and prints out the message "Hello" to the screen.

    methods

    variables

    class visibility

    public or friendly

    Visibility is like a

    protection mechanism

    allowing only certainobjects to enter

  • 5/21/2018 41424702-Java-eBook

    12/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    11

    // example classpublic class L1p1

    {// main method

    public static void main ( String[ ] args )

    {System.out.println("hello");}

    }

    Program output:

    The L1p1 class is known as the "running class" because it is the class we call to run the program. makes sense that the running class is public. Why ? Our main method just puts the word "hello" othe screen using the following programming statement:

    System.out.println("hello"); // print "hello" on computer screen

    The System class is defined injava.langand is automatically imported for you by the Java compileWe will discuss the System class in more detail shortly.

    LESSON 1 EXERCISE 1

    Type the above program into your Java compiler and run it. You can obtain the JDK from Sun

    Microsystems at www.java.sun.com. For those people using the JDK, type the program into aneditor, the file will be called L1p1.java. From the command line of your computer type:

    javac L1p1.java

    java L1p1

    Your program should now run. The command line is case sensitive. The file name must be identicato the class name. Change the above program so that it print's out "Hello" and your name on thcomputer screen. Call your class L1ex1 and your Java file L1ex1.java. You will now need thfollowing commands to compile and run your program.

    javac L1ex1.java

    java L1ex1

    class L1P1

    main method

    hello

  • 5/21/2018 41424702-Java-eBook

    13/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    12

    Compiling and running classes defined in packages

    The next challenge is to compile and run java programs defined in packages. This always seems adifficult thing to do. Just follow the following steps and then it should work.

    Step 1: Type in the following program in a file called L1p2.java, but now define in a package

    called student.

    package student;

    // example class using packagespublic class L1p2

    {// main methodpublic static void main ( String[ ] args )

    {System.out.println("hello");}

    }

    step 2: put the file L1p2.java in a subdirectory called student

    step 3:compile the program in the parent directory

    javac student\L1p2.java

    step 4:run the file specifying the class path. The class path tells the Java loader where the studenpackage is.

    java -classpath . student/L1p2

    Notice the '.' (dot) after -classpath this means use current directory. Notice the / after student thmeans the L1p2 class file is located in the sub directory student. Notice the slash leans towards thright, this is a Unix format for specifying subdirectories and files. You must use this format.

  • 5/21/2018 41424702-Java-eBook

    14/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    13

    importing your own package

    We want to run a class defined in a another package. This is another difficult thing to do. We writeclass called L1p3 in another file called L1p3.java. In this file we the importstudent package and cathe main method from the L1p2 class.

    Step 1: Type in the following program in a file called L1p3.java that imports the student package

    import student.*

    // example classpublic class L1p3

    {// main methodpublic static void main ( String[ ] args )

    {L1p2.main(args);}

    }

    step 2:compile the class in the parent directory but specify where the student package is

    javac -classpath \student; L1p3.java

    Since the student package is in the student subdirectory the compiler can find it so you can omit th-classpath directive

    javac L1p3.java

    step 3:run the file specifying the specifying the class path. The class path tells the Java loader

    where the student package is.

    java -classpath \student; L1p3

    Since the student package is in the student subdirectory the class loader can find it so can omit th-classpath directive

    java L1p3

    The L1p3 class main method calls the main method from the L1p2 class.

    L1p3 L1p2

    main main

  • 5/21/2018 41424702-Java-eBook

    15/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    14

    MAIN METHOD

    When you run your program, the mainmethod is the first method to be called from the runninclass. Every class you want to run must have a main method.

    public class L1p1

    {// main methodpublic static void main ( String[ ] args )

    {System.out.println("hello");}

    }

    We will now discuss and analyze the main method in detail . Every method must state who canaccess it, what data type value it returns, its name what data type values it receives.

    parameter(s)

    method

    visibility

    modifier return

    data _type

    method

    name

    parameter_type parameter_name

    public static void main ( String[ ] args )

    method visibility

    Methods have visibility public, friendlyand private.

    method visibility description

    public means all other classes can access this method

    friendly(default)

    can be accessed by classes in the same package or file(classes defined in the same file areconsidered to be in the same package) (There is no keyword called friendly)

    private visibility means the method can only be accessed by the class it was defined in.

    access friendlymethod only if in

    same package

    another class in a

    different package

    access public

    methodssome public class

    public method

    friendly method

    private method

    cannot access

    rivate methods

    some method

    method

    method

    another class in

    same package

    some method

    method

    method

  • 5/21/2018 41424702-Java-eBook

    16/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    15

    All classes are placed in program memory when a Java program is loaded. Staticmeans the code the main method is directly available to be used. A static method it not associated with an objeand can be used standalone. A static variable is also not associated with any object and can also bused standalone. For non-static variables and methods, you need an object before you can usthem. Why ? Because the methods are accessing variables of an object. If you do not have an objethen the methods cannot access the variables of the object. Right ?

    The purpose of a method is to receive a value, do a calculation and return a result. A method may may not return a value. The return data typeis the type of data the method will return. The retudata type of void is used to indicatea method does not return a value. Notice the return data typof the main method is void. We will study data types very shortly. All method names end witround brackets () to distinguish the method name from an variable name. Values are sent to method through a parameters. Parameters are declared inside the round brackets of the methoname declaration to pass values to the method. The values sent to the main method are known aarguments.

    Argis an array of String objects that will let you send data values to the main method. You send thdata values to the main method through the parameter list by including extra information on th

    command line when you run your Java program. An example is you may want to specify aadditional data file name when you want to run your Java program on the computer.

    java myprogram myfile.dat

    The argument "myfile.dat" will be placed into an array of Strings referred to by the parameter args

    (String[] args)array of stringsreceive

    information

    from command line

    voiddoes not

    return

    a value

    command line arguments(optional)

    input values to main method

    java Myclass myfile.dat

    staticplaced in program

    memory ready to be

    used

    publiceveryone can

    use this method

    mainname of

    the

    method

    ar s[0]

    args[1]

    args[2]

    program memoryloaded classes

    object memoryadditional memory for objects

    Class

    static variables

    static methods

    non static methods

    Class Execution file

  • 5/21/2018 41424702-Java-eBook

    17/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    16

    Do not be too worried about arguments and parameters now, you just need to know that you casend information to the main method from the command line when you run your Java program. ThString object type will be explained in this lesson. Arrays and methods will be explained in detail future lessons. Without the main method the program can not run. Review questions: Why must thmain method be made public ? Why is the main method static ?

    LESSON 1 EXERCISE 2

    Write a program that gets a name from the keyboard and greets the user of your program with thname they entered. Call your java program and class L1Ex2. The following is an example compilinand running the program.

    javac L1Ex2

    java L1Ex2 tom

    Constants

    Numbers like (0-9) and letters like ('a'- 'Z') are known as constants. Constants are hard codevalues assigned to variables. There are many different types of constants.

    character: 'A' numeric: 9 decimal: 10.5 character string: "hello"

    Numbers represent numeric value whereas letters are assigned numeric values for identificatiofrom a chart known as the ASCII table. The letter 'A' is assigned the numeric value 65. Letteconstants have single quotes'a' around them and are known as characters. What is the differencbetween '9' and 9 ? Numbers may be grouped together to make larger numbers like 123Characters maybe grouped together to make messages and enclosed by double quotes: "helloGroups of letters are known as character strings. What is the difference between "1234" and 1234

    What is the difference between a character and a character string ?

    backslash characters

    There are special character that are called back slash codes. The backslash codes allow you tspecify new line or tab in your character strings like: "hello\n"

    code description code description

    \b backspace \0 end of string terminator

    \n new line \\ backslash

    \r carriage return \v vertical tab

    \t horizontal tab \a bell

    \" double quotation mark \o octal constant

    \' single quotation mark \x hexadecimal constant

    Hello Tom

  • 5/21/2018 41424702-Java-eBook

    18/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    17

    range of a number

    All memory is made up of bitshaving values 0 and 1. Eight bits are make up a byte.

    1 byte = 8 bits 0 1 1 0 1 0 1 0

    Data types use 1 to many bytes. Data types representing small numbers use few bytes of memowhere data types representing large numbers use many bytes of memory. All numbers in Java asignedmeaning they can represent negative and positive numbers. The first bit Most Significant B(MSB) in a signednumber is called the sign bit. It indicates a signed number if it is positive onegative.

    Signed Positivenumbers start with a 0. 0 1 1 0 1 0 0 1

    Signed Negativenumbers start with a 1 1 1 1 0 1 0 0 1

    range of a signed number

    The smallest negative value to the largest positive value a number can represent is known as thrange of a number. We need to know the range of a number before we can use it or we will geinaccurate results. We use the following formula to calculate the range of the number from thnumber of bits N the number has.

    The range of a number is calculated for an 8 bit signed number where:

    = = =

    This means a data type that has 8 bits can represent values between -128 and 127. Why is thnegative number magnitude greater than the positive number magnitude ?

    0

    127

    (N-1) (N-1)

    - 2 to (2 - 1)

    (8-1) (8-1)

    - 2 to 2 - 1

    7 7

    - 2 to 2 - 1 -128 to 127

    -1

    -128

    The positive numbers start

    at 0 and end at 127

    The negative numbers startat -1 and end at -128

    Each has 128 numbers

    N is the number of bits in the number. N=8

    sign bit

  • 5/21/2018 41424702-Java-eBook

    19/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    18

    VARIABLES AND DATA TYPES

    Variableslet you store and retrieve data in a computer memory represented by a variable namlike x. The variable namelets you identify a particular memory location. The compiler reserves thmemory address automatically for you when it complies your program. A variable is like a banaccount. You can put money in and take money out. The particular place (location) where you

    money is located is identified by the bank account number. Variables have different data types, juas a bank account would represent many different currencies. Each variable must be declared wita data type.The data type indicates what kind of data the variable is to represent. The followinchart lists the Java data types and an example of the data it is to represent.

    Java data types signed range

    type bytes N bits example - 2exp(N-1) to 2exp(N-1)-1

    byte 1 8 45 -128 to 127

    short 2 16 1234 -32,768 to 32,767

    int 4 32 123467 -2147483648 to 2147483647

    long 8 64 123456788 -2**63 to 2**63-1

    float 4 32 34.56f +/- 3.40282347E+38

    double 8 64 23.23333333 +/-1.79769313486231570E+308

    char 2 16 'A' (unicode) 16 bit character set

    boolean 1 8 true or false false true

    These are known as primitive data types and are not considered objects. .Data types are nobjects because they just store data, and cannot do any operations on the stored data. Wherobjects store data and can do operations on the stored data, using its methods. We need differendata types because we want to minimizethe amount of data memory space we use. The data typalso indicates the type of data the memory allocated for the variable is to represent

    float and double number representation

    Float and double data types are used to represent large numbers known as floating point numbestored in a small memory space. Floating point numbers have a fraction(mantissa) part and aexponent part and represented indecimal point notation 24.56f or exponent notation 3.456E04You will notice that float constants have a 'f' at the end of them. In Java you need to distinguish float constant from a double constant. It is the exponent that allows the floating point number t

    represent a large value in a small memory space. The following is a 32 bit floating point formaknown as a float, where the sign, exponent and fractional parts are stored separately.

  • 5/21/2018 41424702-Java-eBook

    20/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    19

    1 8 23 32 bit floating point number (float)

    sign bit exponent fraction(mantissa)

    (-1)**sign * 2 exp (exponent-127)*(mantissa)

    - 12 .12365 1.2365 * 10 12

    The following is a 64 bit floating point format known as a double, where the sign, exponent anfractional parts are stored separately. Double has greater precision over float because it storemore bits in their exponent and fraction.

    1 16 47 64 bit floating point number (double)

    sign bit exponent fraction

    (mantissa)

    (-1)**sign * 2 exp (exponent-127)*(mantissa)

    - 12 .12365 1.2365 * 10 12

    Declaring variables

    When you declare a variable you are telling the compiler to reservea memory space location in thcomputer memory for your data when your program runs. The variable name is used to representhe location in the computer memory where the data value is stored. Declaring a variable is likopening a bank account The name of the variable is like the bank account number. The banaccount number tells you where your money is in the bank. The bank account number identifies thlocation where your money is in the bank. It is just like the variable in your program identifying th

    locations in the computer memory where your data value is stored. To declare a variable you specithe data or object type and the variable name. A data type is like the currency of the money storein the bank account. When you declare a variable in a method the data value is uninitializedmeaning a known value has not been placed at that memory location yet. When you declare variable in a class definition it gets a default value of 0. You declare a variable by specifying thdata type and an identification name. Variable names should be short and meaningful. Evervariable must be declared with a data type and a name. The data type tells your program what kinof data the computer memory is suppose to represent. The variable name tells your program thlocation in the computer memory where your data value is stored. Data type indicated what kind data the variable represents.

    data_type variable_name; unititialized variables

    int y; // declare variable y of data type int y U 0

    char ch; // declare variable c of data type char. ch U '\0'

    double d; // declare variable d of data type double d U 0.0

    Variables store data

  • 5/21/2018 41424702-Java-eBook

    21/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    20

    You may declare more than one variable at a time if it is the same data type,by separating thvariable names by commas.

    data_type variable_name_list; unititialized variables

    int i, j, k; // declare a variable's i , j and k having data type integer

    i U 0

    j U 0

    k U 0

    declaring and initializing variables

    You may assign values to variables when they are declared. This is called initializing. It is likeopening a bank account with an initial deposit.

    data_type variable_name = value;

    int x = 5; // declare x and initialize to the value 5 x 5

    double d = 10.5; // declare d and initialize to the value 10.5 d 10.5

    A string variable s1 refers to a String object rather than contains the character string itself. Thstring object contains the character string "hello". Refers means s1 is not the String object itself bucontains the locationwhere the String object is located in the computer memory.

    You can declare many variables and initialize them all at once if they are of the same data type, bseparating the variable names and initializations by commas.

    data_type variable_name_and_initialization_list;m 1

    int m=1, n=2, p=3; n 2

    p 3

    String Objects

    Character strings are groups of letters enclosed by double quotes:

    "message"

    It is easy to use character strings in Java because Java has the built in String class located ijava.lang. Character strings in Java are represented by the String class. A String is considered aobject in Java and is not a primitive data type. String is known as a object type rather than data type. The String class lets you do operations on strings. These operations may be assignincharacter strings or joining two character strings together. A character string is made up ocharacters. A character is a single letter in the string. A character is denoted by single quotes. likthe letter 'a'. There is a big difference between 'a' and "a". 'a' is a character where as "a" is character string with only 1 character.

  • 5/21/2018 41424702-Java-eBook

    22/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    21

    You declare a String variable as follows:

    String s; // declare variable s having a object type of String s U null

    The String variable s will store the location of a String object. sis known as a reference to a strinvariable. Right now variable s does not refer to any String object and is undefined or null. A strin

    variable in a method is undefined a string variable in a class definition gets the default value nunull means no known object location. The best thing to do is to declare a String variable and assiga String object to it. The String object will store the character string.

    String s = "hello"; // declare and initialize s to "hello" s h e l l o

    The String variable sdoes not contain the character string "hello" but contains the locationwhethe string object is.

    String s = "hello";

    Assigning values to variables

    Assignment statements using the "=" assignment operator allow you to assign values to existindeclared variables. The expression on the right hand side is assigned to the variable on the left hanside of the assignment "=" operator. The variable gets the new value and the old value is ovewritten. Values are expressions. An expression may be a constant, numeric, String data values oother variable with an assigned value. Once a variable is declared it does not need to be re-declareto assign a new value to it. Its like you do not need to re-open a bank account when you want tmake deposits and withdraws. Before you can assign a value to a variable, the variable must bpreviously declared. When you assign a variable to another variable the value of the variable (nothe variable name) on the right hand side is assigned to the variable on the left hand sideAssignment statements have the form:

    variable_name = expression;

    x = 3; // variable x gets the value of 3 x 3

    y = x; // variable y gets the value of x which happens to be 3 y 3 (x)

    ch = 'A'; // variable ch gets the character constant 'A' ch 'A'

    s1 = "today"; // the String object s gets the character string "hello" s1 today

    s

    "hello"

    A String is an object that

    stores a character string.

    String Object

    The variable s contains the location of the string object.

  • 5/21/2018 41424702-Java-eBook

    23/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    22

    Printing out variable values

    The System.out.println(); statement is used to print values and messages to the computer screeThe System class is defined in java.langand is automatically imported for you when you compiyour program. The System class has a variable called outthat is a reference to a PrintStreamclaobject defined in java.io. (we will study reference's to objects shortly) println() is a method of th

    PrintStream class. The println( ) method causes your printed message to end with a new line aftethe message is printed not before. If you do not want a new line after your message use the printmethod instead.

    System out.print("hello");// print a message to the screen, with out a new lineSystem.out.println("hello"); // print a message to the screenSystem.out.println("hello"); // print a message to the screen

    To print out a variable value you just include the variable name.

    System.out.println(x);// print a variable value to the screen

    To print a message and a variable value to the screen you list the message in double quotes use th"+" catenationoperator and list the variable name. Messages are surrounded with double quoteand variables are not. The "+" catenation operator is used to join messages and variables togethe

    System.out.println("the value of x is: " + x);// print a message and value to screen

    LESSON 1 EXERCISE 3

    Write a simple Java program that has only one class and a main method. In the main methodeclare five variables of different data types. and initialize these variables with values. Use thSystem.out println() statement to print the values of the variables on the screen. Next assigvalues to your variables and print out the new values. Call your class L1ex2 and your Java fiL1ex3.java.

    hellohellohello

    3

    the value of x is: 3oin messages together

  • 5/21/2018 41424702-Java-eBook

    24/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    23

    IMPORTANT

    You should use all the material in all the lessons to do the questions and exercises. If you do noknow how to do something or have to use additional books or references to do the questions o

    exercises, please let us know immediately. We want to have all the required information in oulessons. By letting us know we can add the required information to the lessons. The lessons arupdated on a daily bases. We call our lessons the "living lessons". Please help us keep our lessonalive.

    E-Mail all typos, unclear test, and additional information required to:

    [email protected]

    E-Mail all attached files of your completed exercises to:

    [email protected]

    Order your next lesson from

    www.cscourses.com/java.htm

    This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"

    This document is not to be copied or reproduced in any form. For use of student only

  • 5/21/2018 41424702-Java-eBook

    25/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    1

    JAVA PROGRAMMERS GUIDE LESSON 2

    File: JavaL2.doc

    Date Started: July 12,1998

    Last Update: Dec 28, 2005

    Java Version: 1.5

    LESSON 2 CLASSES AND OBJECTS

    CLASSES, CONSTRUCTORS AND INSTANCES

    A classes defines all the variables and methods a object would need. When you make a object froa class definition, the object is then known as an instance of a class. An object is allocatememory for the variables defined in a class. A class may have many instances all made from thsame class definition. Just as there can be many cakes made from the same recipe. When mancake's get baked they also get names: cake1, cake2 cake3 etc. The item you are making is a cakebut each individual cake made is known separately. The class is the basic definition that instanceare created from. Each instance or object will have its own distinguishable properties.Just like eaccake can have its own distinguishable properties. Chocolate cake, vanilla cake etc. This is thhighlight of Object Oriented Programming. where a class provides a common definition that objecare created from. When you define a class you must list all the data variables and methods the claneeds. When you create an instance of a class the object will get distinguishable properties oattributes when the variables of the object are initialized. How are the properties of an objeinitialized? The variables may be initialized in the class definition or by using a constructor. constructor is a special method to initialize the variables of an object. A constructor has the sam

    name as the class. A constructor is like the baker who bakes the cake. The baker uses the recipand ingredients to bake the cake. The recipe is the class, the ingredients are the data and the bakecake is the object. Values are sent to the constructor who then initializes the variables of the objewith these values. When an object is made, memory for the variables of the object is allocated in thcomputer memory. An example of a class is a Person class. A Person may be defined with agname, height and weight. The Person class may be defined with methods to initialize age, namheight and weight and to retrieve these values. Every time you create an object from the Persoclass definition, you will get a separate Person object. Each Person object would have a differename, age, height and weight. Each Person object is distinguishable from other Person objecbecause each Person object has unique properties. How does an object get its own distinguishabproperties? When the variables of the object are initialized with different values by calling thconstructor or initializing the variables defined in class with values when they are declared.

    class

    definition

    P1P4

    many objects made from the same class definition

    P2 P3

  • 5/21/2018 41424702-Java-eBook

    26/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    2

    defining a class

    We will define a Person class. An attribute of a person can be their name. Our class will have thname of the person and a constructor to initialize the person's name when the Person object created..

    // person classpublic class Person{private String name; // name of person// constructor to initialize variable namepublic Person(String name)

    {this.name = name; // initialize name}

    }

    A reference to the executing object or the class being defined is automatically supplied by thecompiler and is called this.

    constructors

    Constructors are special methods that are used to initialize the variables of a created objecConstructors have the same name as the class. Values are passed to the constructor througparameters. Parameters are used to receive value. Parameters are enclosed by round brackets andefined by a parameter typeand identified by a parameter identifier.

    v i si b i l it y c la s s_ n am e ( p a r a m a t e r _ t y p e p a r a m a t e r _ i d e n t i f i er ) ;

    public Person(String name)

    The parameter type is Stringand the parameter identifier is name. The value represented by thparameter identifier is assigned to a specified variable defined in the class. In most situations, thparameter identifier and variable defined in the class have the same spelling. To distinguish thdifference between a parameter identifier and the variable defined in the class, a reference to thclass you are defining is used. This reference is called thisand refers to the class you are presentdefining or the object that is being executed when your program is running. The parameter identifireceives a person's name. The parameter identifier representing a persons name is assigned to thvariable namedefined in the Person class. Constructors that receive values through a parameter lito initialize the variables declared in the class are called initializing constructors.

    // initializing constructorpublic Person(String name)

    {this.name = name;}

    Person Class

    Variables

    Constructor

    Constructors are used to initialize variablesdefined in the class when the object is created

    this

    the this reference refers to the class you aredefining or the presently executing object.

  • 5/21/2018 41424702-Java-eBook

    27/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    3

    default constructor

    A default constructor initializes the variables defined in a class with default values.

    // default constructorpublic Person()

    {name = "Ed";}

    classes without constructors

    A class does not always need a constructor. The variables of a class can be initialized when they adeclared in the class definition. This is a good feature of Java. We can make a Person class that doenot have a constructor by pre-initializing the variables defined in the class with values. The compilwill initialize the variables declared in the class definition when the object is created.

    // person classpublic class Person{String name = "Ed"; // name of person}

    When we pre-initialize the name of the person in the class definition, then we will have many Persoobjects with the same name. This is totally undesirable. When do we need constructors ? The rule iwe need constructors when we want to give our object different data values when it is constructeWhen a constructor is not defined the Java compiler will supply a default constructor automaticallUnfortunately the Java compiler will not supply a default constructor if you have defined otheconstructors.

    declaring a reference to a object

    An object referencehas to be declared before an object can be made. An object reference is variable that stores the location of an object. When a object is created, memory is allocated for The object reference stores the starting location where the object is located in computer memory

    Declaring an object reference is just like declaring an integer variable.

    d a t a _ t y p e v a r i a b le _ n am e

    int x; // declare a variable

    Person Class

    Variables

    There are two ways to initialize the variables defined in a class

    1. in a constructor

    2. when the variables are declared

    A default constructor initializes the variables

    defined in a class with default values.

    this

  • 5/21/2018 41424702-Java-eBook

    28/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    4

    Instead of a data typewe now have an object type, instead of a variable namewe have aobject name. The object type is the class name. When you define a class you have automaticallcreated an object type. The object name is any name you want to identify the object. We declare reference to a Person object called p.

    o b j e c t _ t y p e o b j e c t _ n am e ;

    Person p; // declare a reference to Person object p p U null

    The object name is known as an object reference because it is a reference to an object, it is notthobject itself. The object reference will store the locationwhere the object is created in memorWhen you declare an object reference in a method it is unitialized. When you declare an objereference in a class definition it gets a default value of null.nullrefers to no known object and doenot refer to any object. An object must be created and assigned to the object reference.

    creating an instance of a class

    After you declare an object reference, you have to create an object. This is like baking a cake. cake needs to be made before it can be eaten. A object needs to be created before it can be used

    When an object is created it is known as an instanceof a class. An instance of a class is created run time (when your is running). Creating an object is much like assigning a value to a variable.

    d a t a _ t y p e v a r i ab l e _ n am e = v a lu e ;

    int x = 5;

    Except the value is the locationof an object.

    o b j e c t _ r e f e r e n ce = n e w c la s s c o n s t r u c t o r ( a r g u m e n t _ l i st ) ;

    p = new Person("Tom");// create Person object assign to p

    objectreference

    allocatememoryfor object

    callconstructor

    values passedto constructor

    When a object is created memory must be allocated for it. Memory for objects are created in rutime using the new operator. The newoperator allocates memory for the Person object, and thobject's starting memory location is assigned to the object reference. The object reference containthe locationof where the object was created in memory. The variables in the objects are initialize

    by calling the class constructor. When the constructor is called the constructor will initialize thvariables belonging to the object declared in the class.

    p

    Person object

    object reference

    x 5

    Tom

  • 5/21/2018 41424702-Java-eBook

    29/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    5

    It is always a two step process to create an object.

    (1) declare an object reference Person p; // declare reference variable p

    (2) create an instance of the class,

    assign the created Person objects

    location to the object reference p

    p = new Person("Tom"); // assign Person object to p

    When we create an object the newoperator allocates memory for the object and the constructoinitializes the variable defined in the class for the object. We have now created a Person objeinitialized with the name "Tom". The object reference variable p has the location of the Persoobject. The above two steps may be combined into 1 step.

    o b j e c t _ t y p e o b j e c t _ n am e = n e w c la ss c o n s t r u c t o r _ n am e ( a r g u m e n t _ l i st ) ;

    Person p1 = new Person("Tom");

    If we did not include a Constructor in our class definition then we can still create an object by callinthe default constructor. You call the default constructor with no arguments.

    Person p2 = new Person();

    In this situation, the object variables will have the values that they were defined with which is "EdIn programming you must make a connection between what constructors are called and whicvariables were initialized. Think that calling a constructor is creating different kinds of cake.

    // create vanilla cakeCake c1 = new Cake("vanilla");

    // create chocolate cakeCake c2 = new Cake("chocolate");

    Each cake object is made from the same recipe, the Cake class. Each cake object gets initialized wita different flavor when it is made. Summarizing we create the object from the class definition, wallocate memory for the object using the new operator, we call the constructor to initialize thvariables defined for the object by the class.

    Person p = new Person ("Tom");

    p1 Tom

    p2 Ed

    c1 vanilla

    c2 chocolate

    object

    variable andtype

    allocate memory

    for object using

    newoperator

    program

    callsconstructor

    constructor initializes

    variables belonging tothe object

  • 5/21/2018 41424702-Java-eBook

    30/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    6

    main method

    The main method is the first method to run when you run your program. The main method is statmeaning the code can be directly accessed from the loaded class. The main method is usually useto declare objects, instances of the class that the main method belongs to. This is a unique featuof Java where each class can have its own main method. By each class having its own main metho

    each class can be tested individually before they are integrated into a complete program.

    // main methodpublic static void main ( Strings[ ] args )

    {Person p1 = new Person("Tom"); // create instance of the class PersonPerson p2 = new Person(); // create instance of the class Person}

    The main method is staticand can be accessed directly from the Person class. When objects arcreated from a class definition the static variables and methods are not created again inside thobject. In an object, memory is only allocated for the non-static variables declared in a class. Th

    object may use the static variables of the class, but does not contain them. Both static and nostatic methods can access an object variables. Variables in an object are shared between amethods defined in a class. The object reference pwas declared in main and refers to a Persoobject. You must understand the difference between Person class and Person objects. The statvariables and methods belong to the Person class. There is only one person class but there can bmany person objects. The Person class is in program memory where the Person object is in objememory. There may be many Person objects but only one Person class. Note: each Person objerefers to a String object representing the Person's name.

    Tom

    Person object's String object's(declared in Person class)

    name

    name

    Person class

    main method (static)

    p1

    p2

    "Tom"

    "Ed"

    static variables and methods meanspermanent memory initialized at load time.

    What is the difference between the Person

    class and a Person object?

    Person

    object

    references

    An object is allocated memory for variables

    defined in the class definition.

  • 5/21/2018 41424702-Java-eBook

    31/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    7

    toString method

    Once we get our object created we want to do something with it. The only thing we can do with oPerson object is to print the name of the Person on the computer screen. Java lets you return string representation of an object by calling the toStringmethod. The toString method jumakes and returns a String object, but does not print out to the screen. You need to call th

    toStringmethod with the System.out.println()method to print to the computer screen.

    // return a string representation of the objectpublic String toString()

    {return "my name is: " + name; // make a String and returns it}

    The toStringmethod is also conveniently called by using the object name. The Java compiler wautomatically call the toStringmethod for this object. The System.out.println()method is calleto print out the Stringobject returned by the toStringmethod. When you want to use a methoyou call it by its name.

    System.out.println(p1); // print out string representation of this object

    or if you like typing so much then you can use the object name, the dot operator and the toStrinmethod name.

    System.out.println(p1.toString())// print out string representation of this object

    The above two methods are equivalent. Using the object name is more professional.

    If the object does not have a toString()method then the location of the object is printed out witthe class name a @ symbol and some stupid number in hexadecimal identifying the objecMyClass@7da8

    Person class

    Here is our complete Person class. The main method is used to create Person objects and calls thtoString()method from each object. We have two constructors. Having two methods with the samname is possible in Java. as long as the parameter types are different. This technique is callemethod overloadingwhich means same method name but different parameter types. The compilknows which constructor to call by matching the number of arguments when the constructor called.

    // person classpublic class Person{private String name; // name of person

    // default constructorpublic Person()

    {this.name="Ed"; // initialize variable name to "Ed"}

    a class may have more than 1

    constructor this is called overloading

  • 5/21/2018 41424702-Java-eBook

    32/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    8

    // initializing constructorpublic Person(String name)

    {this.name = name; // assign user value to variable name}

    // main method to create Person Objectspublic static void main ( String[ ] args )

    {Person p1 = new Person();System.out.println(p1);Person p2 = new Person("Tom");System.out.println(p2);}

    // return a string representation of this objectpublic String toString()

    {return "my name is: " + name;}

    In the main method we make two objects. One made using a default constructor, the other using ainitializing constructor. When you have other constructors defined you must include a defauconstructor if you create objects that need default constructors. The Java compiler will noautomatically create default constructors for you, if you already created other constructors. You wget an error message if you call a default constructor and you have not defined a default constructwith your other constructors.

    LESSON 2 EXERCISE 1

    Type in the Person class and run it on your computer. Instantiate objects with your own name. Cayour project L2ex1 call your class Person and your Java file Person.java. Remove the defauconstructor and instead initialize the name variable with a value.

    LESSON 2 EXERCISE 2

    Add more attributes to the Person class like height, age and weight. Update your constructor antoString method.

    my name is: Ed

    my name is: Tom

    ro ram out ut:

    Ed

    Tom

    p1

    p2

  • 5/21/2018 41424702-Java-eBook

    33/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    9

    LESSON 2 QUESTION 1

    1. What is the difference between a class and an object.2. What is an object ?3. What is the difference between a data type and an object type ?4. What is a Constructor and what does it do ? Give an example using a constructor.

    5. Do we always need a Constructor ?6. What is the newoperator used for ?7. What is meant by "an instance of a class " ?8. What is a main method used for ?9 Who calls the main method ?10. What does a toString method do?11. How do you call a toString method ?12. What is the difference between an object type and an object reference ?

    class components

    A class list all the variables and methods for a object. A class is defined as follows:

    visibility class name {

    variables // store and retrieve data for the class

    fi nal variables // variables once initialized the value cannot change (read only)

    stati c variables // shared variables between all instances of this class

    constructor(s) // initialize and allocate memory for variables

    methods // contains programming statements

    main method // creates i/o streams, creates classes and call's class methods

    toStri ng method // string representation of this object

    }

    A class may have many different kinds of variables. Variables that are read only, that are sharebetween all instances of a class just known to one instance of a class. Variables may be initialized the class definition or by using a constructor. When all the variables are initialized in the clasdefinition a constructor is not needed. In this case the Java compiler will supply a default constructautomatically. Methods contain programming statements and temporary variables. The variables a method do not retain their values after the method has finished running. The variables defined the class retain their values. The mainmethod is used to start your program and create an obje

    from the class it was defined in. You will learn in detail all the components of a class in futurlessons. In this lesson, we will concentrate more on variables declared inside a class.

  • 5/21/2018 41424702-Java-eBook

    34/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    10

    variable visibility

    In Java you can declare and initialize variables as you need them. You can declare variables in thclass definition, in individual methods or globally in your program. Variables declared in a class havlevel of visibility that indicate if the variables are to be known to other classes or just to be knowto the class they were declared in.

    visibility data_type variable_name

    private int x;

    Variables declared in a class definition may have visibility public, friendlyor private. If there is nvisibility specified the default visibility is friendly. There is no keyword friendly.

    public variables accessed by all classes

    friendly variables accessed by classes in same package

    levels of visibility for

    variables declared in a class

    private variables only accessed by this class

    Variables in a class should always be declared as private. By having all variables in a class privaforces all classes to exchange data through methods. By classes exchanging data through methodenables all classes to operate independently. The methods act as a protection ring to protect thdata.Objects exchange data through methods (M)

    private

    variables

    M

    MM

    M

    MM

    private

    variables

    M

    MM

    M

    M M

    Exchange datathrough

    methods

    access ublic variablespublic class

    public variable

    friendly variable

    private variable

    some other class

    differentpackage

    cannot access

    private variables

    some other class

    samepackage

    CLASS ACLASS B

  • 5/21/2018 41424702-Java-eBook

    35/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    11

    declaring variables

    Variables declared in a method are not known to other methods or classes. They are said to be locto that method and will not be recognized anywhere else. Variables declared in a method may not b

    declared as private or public. Variables declared in a class are shared by all methods of that class

    variables in a method

    (temporary)

    variables in a class

    (permanent)

    variables are temporary

    and are only known to

    method cannot be

    declared as public or

    private (local)

    variables known to all

    methods in class. Variables

    known to other classes

    depends on visibility

    (privateor public)

    Final Variables

    Thefinal keywordlet you define a variable as "read only".This means you cannot changethevalue of the variable once it is initialized. A final variable must be initialized with a constant when is declared.

    f i n a l d a t a _ t y p e v a r i a b le _ n am e = c o n s t a n t ;

    final int MaxSize = 10;// final variable initialized to constant value 10 cannot be changed

    Using final variables is a must. There should be no hard coded numeric values in your program. Thpurpose is this. If you change MaxSize to be 12 then you do not need to change all 10's to 12 i

    your program. Without using a final variable you may inadvertently change some 10's to 12's thadon't need to be changed and then your program may not operate as expected. Final variables arusually placed inside the class definition before all methods are defined. Final variables may also bdeclared in methods as well as in class definitions. Final variables declared in class definitions mabe private or public.

    Static Variables

    Static variablesare needed only when you want one variable always the same variable to baccesed by the class. Only one memory location is allocated to a static variable. Static variables aalso known as class variables. In contrast non-staticvariables are known as instancevariablebecause a new variable is made every time an instance of the class is made. Static variables shoube initialized to a default value when they are declared. Static variables can only be declared in thclass definition. Static variables cannot be declared in a method. Static variables are placed program memory where the class was loaded and can be directly used. Note: static methods caonly access static variables.

    One static variable is shared between all objects

    class

    Methods

    variables sharedby all Methods

  • 5/21/2018 41424702-Java-eBook

    36/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    12

    To declare a static variable:

    s t a t i c d a t a _ t y p e v a r i a b le _ n am e ;

    static int num=0;// declare static variable num

    Each object may have its own same name instance variablebut there is only one staric variable.

    Static variables can be accssed by all objects. When would we use static variables ? We can use thPerson class as an example. Would we want the age of a person to be shared between all instanceof Person ? Probably not. As soon as we change the value age in one object it will reflect the samvalue for all instances of the Person objects. Are all people the same age? Probably not. We woulike age to be different for each person object. What would be a good static variable for a persoclass ? The number of people objects created. We need to keep track of how many people objectwere created. This can be done by using a static variable.

    static int num=0; // declare static variable num

    There will be only 1 static variable located in program memory and shared between all objectEvery time an instance of the class is made the static variable can be incremented. When a statvariable is declared in the class definition it should be initialized to a default value like 0. Here

    the Person class with a static variable.When accessing a static variable inside the class definitioyou use the static variable name.

    num = 5; // assign 5 to static variable num declared in class Personint x = num; // assign to x the value of the static variable num.

    What is the value of x ?

    access

    inside class

    What is the difference between a staticvariable and an instancevariable ?What is another name for a static variable ?

    program memory

    class loaded into, memory:

    Code for method

    ObjectInstance Variable

    ObjectInstance Variable

    ObjectInstance Variable

  • 5/21/2018 41424702-Java-eBook

    37/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    13

    When accessing a static variable outside the class definition, you must use the class name not thinstance name or object reference name.

    c la s s_ n am e . s t a t i c_ v a r i a b le _ n am e

    Person.num = 5;// assign 5 to static variable num declared in class Person

    int x = Person.num;// assign to x the value of the static variable num.

    What is the value of x ?

    Here is the person class defined with a static variable:

    // person classpublic class Person{private static int num = 0; // declare static variable numprivate String name = "Ed"; // name of person

    // default constructorpublic Person()

    {num = num + 1;}

    // initializing constructorpublic Person(String name)

    {this.name = name;num = num + 1;}

    // main methodpublic static void main ( String[ ] args )

    {Person p1 = new Person();System.out.println(p1);Person p2 = new Person("Tom");System.out.println(p2);}

    // return a string representation of this objectpublic String toString()

    {return "my name is: " + name + " there are " + num + " persons");}} my name is: Ed there are 1 persons

    my name is: Tom there are 2 personsro ram out ut:

    Ed

    Tom

    main:

    p1

    num

    p2

    class Person(static)

    Person

    Objects

    access outside class

  • 5/21/2018 41424702-Java-eBook

    38/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    14

    LESSON 2 EXERCISE 3

    Type in the above Person class with the static variable and run it on your computer. Remove thestatic modifier on variable num and re-run the program What did you noticed ? Call your project

    L2ex2 call your class Person and your Java file Person.java.

    Reference Variables

    Reference variables are used to refer to an object. They are not the objects themselves, breference variables contain the locationof where the object is stored in the computer memory. Thonly object we have been using so far is instances of the String class and our own classes like thPerson class. Objects are stored in memory. References variables refer to the location of an objecreated in computer memory. As mentioned before, declaring a reference variable is no differenthen declaring a variable.

    int x; // declare an integer variable x

    The only difference is, instead of a primitive data type we use the class definition name. The cladefinition name is also known as an object type. When a reference variable is declared in a methoit is unitialized and does not refer to any object. When a reference variable is declared in a clasdefinition its gets default value of null meaning refers to no known object.

    o b j e c t _ t y p e o b j e ct _ n am e ;

    String s2; // declare a unutilized reference to a String object s2 U null

    If you try to access a reference variable and it does not refer to an object, then you will get aruntime unitialized variableexception. An exception is a condition that stops your program frorunning. It occurs when an error is detected while your program is running. Java is kind, most oth

    languages will crash your computer. Java keeps track of all runtime errors for you automatically bmeans of exceptions and kindly tells you about them. The reference variable refers to an objeclocationin computer memory.

    If you declare a reference variable in a method and you do not assign an object to it, then yoshould assign nullto it. null is used to represent no known object.

    String s3 = null;// reference variable refers to no object s3 null

    For Strings some people assign the empty string to it.

    String s4 = "" ;// reference variable refers to string object that is empty s4 ""

    What is the difference between s3 and s4 ?

    s3 does not refer to any object where s4 refers to a string object that is empty.

    s3 null s4 ""

  • 5/21/2018 41424702-Java-eBook

    39/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    15

    You are used to assigning string objects to references as follows:

    String s5 = "Hello"; // declare and initialize a string object s5 "Hello"

    The String object is created in compile time and placed in the class execution file. The "=assignment operator is used to assign the String object to the object reference variable s. The strin

    object is automatically constructed for you because the compiler calls the String class constructoWhen the program is loaded and running the reference variable s refers to the location of the strinobject placed in program memory.

    assigning object references to other object references

    Existing objects may be assigned to other object reference variables. Let's make another stringobject called s6.

    String s6 = "Goodbye"; // declare and initialize a string object s6 "Goodbye"

    The location of the object refereed to by s6 is assigned to s5. Now both s5 and s6 refer to the

    "goodbye" string object. Each stores the location to the String object "goodbye"

    s5

    goodbye // both s5 and s6 refer to "goodbye"

    s5 = s6;

    s6

    Now s5 and s6 refer to the String object created by s6. What happen to the object referred to by s? In Java you do not need to worry about deallocating memory, Java does this for you automaticallany memory not being used is collected for re-use. It's called garbage collection. There are 2 ru

    time methods System.gc()and Runtime.gc();

    LESSON 2 EXERCISE 4

    Write a small program by answering the following questions that just includes a class and a mainfunction If you are using a project call your project and class L2Ex3. You may want to print yourvalues on your computer screen by using the System.out class print method as follows:

    System.out.println("Lesson 2 Exercise 1"); // print a message to screenSystem.out.println("x = " + x); // print a message and a valueSystem.out.println("s1 = " + s1); // print a message and a object valu

  • 5/21/2018 41424702-Java-eBook

    40/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    16

    1. Declare an integer variable x and assign the value of 5 to it2. What is the value of x ?3. Declare an integer variable y and assign the value of x to it..4. What is the value of y ?5. Declare a String object reference s1.6. Assign the string "hello" to s1.

    7. Declare a String object reference s2 and assign the String object reference s1 to it.8. Assign the character string "world" to s1.9. What is the value of s1 ?10. What is the value of s2 ?11. Why does s1 and s2 have different character strings ?

    EXAMPLE USING DIFFERENT TYPES OF VARIABLES DEFINED IN A CLASS

    A program example consisting of a class called L2P2 with variables and a main method

    demonstrating using different types of variables is as follows. The main method is used to create ainstance of this class.

    o b j e c t _ t y p e o b j e c t _ n am e = n e w c la s s_ c o n s t r u c t o r ;

    L2p1 test = new L2p1(); // create a L1p2 object assign to test

    Once an instance of a class is created we can access the member variables of the created object busing the object name the dot operator and the variable we want to access.

    o b j e c t _ n am e . v ar i a b le _ n am e = e x p r e s si o n ;

    test.name = "Hello"; // access variable name belonging to object test "hello"

    The "." dot operator states the variable name belongs to the object referred by test.

    Here is the example class L2p1

    // public classpublic class L2p1

    {public final int Max = 5; // final variablepublic String name; // public variable referenceprivate int count; // private variable

    private static int Num=0; // static variable

  • 5/21/2018 41424702-Java-eBook

    41/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    17

    // main methodpublic static void main ( Strings[ ] args )

    {

    L2p1 test = new L2p1(); // instantiate class L1p2test.name = "Hello"; // set public variable to "hello"int x = test.Max; // variables belonging only to a methodtest.count = L2P1.Num; // assign static variable to private variableSystem.out.println("test.name " + x + test.count); // print hello}

    }

    MEMORY MODEL

    A memory model shows where all the programming components are placed in the computmemory. The memory model will let you understand the difference between static variables anmethods and objects. The class file is loaded into the program memory when you run your programIn the class file program memory is reserved for static variables and methods. Memory is allocatein the computer memory for objects created from the class definitions. Objects are only known by alocation represented by a @xxxx The methods belonging to a class are also stored in programemory or read off the class file. The methods of a class do not get stored with the object Computer data memory. Non-static methods of a class can only be accessed by objects becausvariables inside a non-static class will access variables in an object.

    Hello 5 0

    object memory

    object L2p1

    Max: 5

    name: Hello

    count: 0

    class

    memory

    class L2p1

    Num: 0

    Main

    testx: 5

    Program Output:

  • 5/21/2018 41424702-Java-eBook

    42/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    18

    location name modifier value type

    @xxxx Max final 5 int

    name public Ed Stringobjects

    Computer

    Data

    Memory count private 0 int

    main test reference @xxxx L2P1

    x variable 5 intstatic

    Computer

    Program

    Memory L2p1 Num static 0 int

    LESSON 2 EXERCISE 5

    Make a memory model for your Person class, instantiate at least 2 Person objects in your mainmethod.

  • 5/21/2018 41424702-Java-eBook

    43/258

    www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

    19

    IMPORTANT

    You should use all the material in all the lessons to do the questions exercises. If you do not knohow to do something or have to use additional books or references to do the questions or exercise

    please let us know immediately. We want


Recommended