Java Tutorial for Beginners

Embed Size (px)

Citation preview

  • 7/29/2019 Java Tutorial for Beginners

    1/31

    IE582 Spring-2004 1

    Java Tutorial for Beginnershttp://www.personal.psu.edu/kxt179/teaching/index.html

    1 Introduction to Java Programming.............................................................................. 3

    1.1 What is Java? ...................................................................................................... 3

    1.2 Features of Java Programming Language ........................................................... 31.3 Why Java?........................................................................................................... 31.4 Different Types of Java Programs ...................................................................... 31.5 Getting stated with Java Programming ............................................................... 4

    2 Important Java Concepts ............................................................................................. 62.1 Object .................................................................................................................. 6

    2.2 Message............................................................................................................... 62.3 Class.................................................................................................................... 72.4 Inheritance........................................................................................................... 7

    2.5 Interface .............................................................................................................. 82.6 Package ............................................................................................................... 8

    3 Java Language Basics ............................................................................................... 103.1 Statements and Expressions.............................................................................. 103.2 Variables and Data Types ................................................................................. 10

    3.3 Expressions and Operators................................................................................ 113.4 String Arithmetic ............................................................................................... 12

    3.5 Modifiers ........................................................................................................... 123.6 Conditional Statement....................................................................................... 12

    3.6.1 if conditional statement ............................................................................. 12

    3.6.2 switch Conditional Statement ................................................................... 123.7 Loop statement .................................................................................................. 13

    3.7.1 for Loops ................................................................................................ 13

    3.7.2 while and do Loops................................................................................... 133.7.3 Breaking Out of Loops.............................................................................. 14

    4 Working with Objects ............................................................................................... 16

    4.1 Package ............................................................................................................. 164.1.1 Defining package ...................................................................................... 164.1.2 Using package ........................................................................................... 16

    4.2 Class.................................................................................................................. 164.2.1 Defining classes ........................................................................................ 16

    4.2.2 Defining variables..................................................................................... 164.2.3 Defining methods...................................................................................... 164.2.4 Java access specifiers................................................................................ 17

    4.3 Inheritance......................................................................................................... 174.4 Interface ............................................................................................................ 17

    4.5 Creating New Objects ....................................................................................... 184.6 Accessing and Setting Class and Instance Variables........................................ 194.7 Calling Methods................................................................................................ 19

    4.8 References to Objects........................................................................................ 204.9 Casting and Converting Objects and Primitive Types ...................................... 20

    4.10 Comparing Objects ........................................................................................... 21

  • 7/29/2019 Java Tutorial for Beginners

    2/31

    IE582 Spring-2004 2

    4.11 The Java Class Library...................................................................................... 215 Array and Container Objects..................................................................................... 22

    5.1 Array Objects .................................................................................................... 225.1.1 Arrays in Java............................................................................................ 22

    5.1.2 Declaring Array Variables ........................................................................ 22

    5.1.3 Creating Array Objects ............................................................................. 225.1.4 Accessing Array Elements ........................................................................ 22

    5.1.5 Changing Array Elements......................................................................... 225.2 Container Objects.............................................................................................. 23

    5.2.1 Container taxonomy.................................................................................. 235.2.2 Some Useful Container Objects................................................................ 235.2.3 More on LinkedList .................................................................................. 23

    6 Input and Output ....................................................................................................... 256.1 Stream?.............................................................................................................. 25

    6.2 Character Streams and Byte Streams................................................................ 256.3 Reading Console Input...................................................................................... 266.4 Writing Console Output .................................................................................... 27

    6.5 Reading and Writing Files ................................................................................ 276.6 Parsing String Input using Tokenizers.............................................................. 27

    7 Java Application........................................................................................................ 297.1 Creating Java Applications ............................................................................... 297.2 Java Applications and Command-Line Arguments .......................................... 29

    8 What you need for (serious) Java Programming....................................................... 318.1 Buy a Java book (or use online tutorials).......................................................... 31

    8.2 Use (hyperlinked) Java APT specification........................................................ 318.3 Use RAD Tools (especially for GUI programming) if possible ....................... 318.4 * Some (possibly) important, but not covered topics ....................................... 31

  • 7/29/2019 Java Tutorial for Beginners

    3/31

    IE582 Spring-2004 3

    Java Tutorial for BeginnersKaizhi Tang

    1 Introduction to Java Programming

    1.1 What is J ava?

    l Java is a Programming Language: Full-fledged general-purpose programminglanguage, especially object-oriented programming

    l Java is a Platform: Java Virtual Machine (JVM) and Java API (ApplicationProgramming Interface)

    1.2 Features of J ava Programming Language

    l Platform Independent:n Java program can run on any computer system for which a JVM has been

    installedn Java bytecode / Compiler / Interpreter

    l Object Orientedn Java is a pure object oriented programming langauge

    l Easy to Learnn Similar to C and C++, but most of more complex parts of them have been

    excluded

    l Performancen Exception handling mechanism

    l Robustn Interpreted but still high performance (usingJust In Time Compiler

    technology)

    l And, Network-Savvy, Secure, Multi-threaded, Dynamic, etc.1.3 Why J ava?

    l Shorten development timen Easy to use, Automatic garbage collection, using the third partys APIs

    l Shorten deployment timen Platform independent

    l Solve complicated problem1.4 Different Types of J ava Programs

    l Console Application: Run in command line (*)l Applet: Run in the browser (IE or Netscape)l Servlet: Run in the Java Servlet container (Jakarta Tomcat)l Beans: component strategy in Java, especially in J2EE

  • 7/29/2019 Java Tutorial for Beginners

    4/31

    IE582 Spring-2004 4

    1.5 Getting stated with J ava Programming

    l Getting a Java Development Environment (JDK) and documentationn Go to the JavaSoft Web site

    (http://java.sun.com/j2se/1.4.2/download.html )

    n Download SDK, JRE and documentationl Install the JDK

    n For example: C:\ j2sdk1.4.2l Unzip the documentation: C:\ j2sdk1.4.2\docsl Creating a Java Application

    n Creating the Source File:u using text editorsu file name extension: .javau file name = class name (example: HelloWorld.java for class

    HelloWorld)

    n Compiling and Running the Source Fileu

    javac HelloWorld.java (

    bytecode: HelloWorld.class)u java HelloWorldl Creating a Java Applet

    n Creating the Source File

    n Compiling and Running the Source File

    import java.applet.Applet;import java.awt.Graphics;

    public class HelloWorld extends Applet {public void paint(Graphics g) {

    g.drawString("Hello world!", 50, 25);}

    }}

    class HelloWorld {public static void main(String[] args){

    System.out.println("Hello World!");}

    }

  • 7/29/2019 Java Tutorial for Beginners

    5/31

    IE582 Spring-2004 5

    n Including the Applet in a Web page (Only for Netscape, IE is different)

    n ExecutionWeb browser orappletviewer

    A Simple Program

    Here is the output of my program:

  • 7/29/2019 Java Tutorial for Beginners

    6/31

    IE582 Spring-2004 6

    2 Important Java Concepts

    2.1 Object

    l Two characteristics of real-world objects: states and behaviors Dogs: state (name, color, breed, hungry) and behavior (barking, fetching, andwagging tail) Bicycles: state (current gear, current pedal cadence, two wheels, number of

    gears) and behavior (braking, accelerating, slowing down, changing gears)l Software objects to model real-world objects: variables and methods l Definition: An object is a software bundle ofvariables and related methods

    l Encapsulation: package an objects variable within the protective custody of itsmethod => methods restrict and protect the variable access in an object

    l Benefit of Encapsulationn Modularity: write and maintain source code of other objects independentlyn Information hiding: only public method can communicate with other objects

    2.2 Message Software objects interact and communicate with each other by sending messages

    to each other

    Objects will update states or send messages to other objects in the system

    Benefitso Message parsing support all possible interactions between objectso Objects dont need to be in the same processor or even on the same

    machine => distributed computing is easy in Java

    Java Program = Objects + Message interactions

  • 7/29/2019 Java Tutorial for Beginners

    7/31

    IE582 Spring-2004 7

    2.3 Class

    l Definition: A class is a blueprint, or prototype, that defines the variables and themethods common to all objects of a certain kind.

    o All the bicycles share the same characteristics and they can be defined asone class

    l A class is an abstract of a group of objects

    2.4 Inheritance

  • 7/29/2019 Java Tutorial for Beginners

    8/31

    IE582 Spring-2004 8

    Subclasses: Mountain Bike, Racing Bike, Tandem Bike Superclass: Bicycle The class variables and methods in the subclasses are the subsets of those in the

    superclasso Mountain bikes, racing bikes, and tandems share some states: cadence,

    speed, and the like. Also, each subclass inherits methods from thesuperclass. Mountain bikes, racing bikes, and tandems share somebehaviors: braking and changing pedaling speed

    o Tandem bicycles have two seats and two sets of handle bars; somemountain bikes have an extra set of gears with a lower gear ratio

    Subclass can overrides some methods in the superclasso For example, if you had a mountain bike with an extra set of gears, you

    would override the "change gears" method so that the rider could use those

    new gears.

    Benefits:o Reuse the code in the superclass many timeso Programmers can implement superclasses called abstract classes thatdefine "generic" behaviors . The abstract superclass defines and may

    partially implement the behavior, but much of the class is undefined andunimplemented. Other programmers fill in the details with specialized

    subclasses

    2.5 Interface

    Definition: a device that unrelated objects use to interact with each othero Analogous to a protocol (an agreed on behavior)

    Example: Inventory Interfaceo Bicycle class hierarchy defines different bicycle classeso They needs to be used in an inventory programo Inventory program only needs to know tracking numbers and retail priceso An inventory interface is defined to connect bicycles and the inventory

    programso This interface can also be used by other class that needs to be used in the

    inventory program

    Benefitso Capturing similarities among unrelated classes without artificially

    forcing a class relationship (inheritance)o Declaring methods that one or more classes are expected to

    implement

    o Revealing an object's programming interface without revealing itsclass

    2.6 Package

    Definitions: a collection of classes Without explicit declaration, access to the classes in a package is not allowed

    o import java.io.*;

  • 7/29/2019 Java Tutorial for Beginners

    9/31

    IE582 Spring-2004 9

    Benefitso Easy to manage large projectso Set access barrier between different groups of classes

  • 7/29/2019 Java Tutorial for Beginners

    10/31

    IE582 Spring-2004 10

    3 Java Language Basics

    3.1 Statements and Expressions

    Statement: forms a single Java operation. They must end with semi-colons(;).Example:

    int i = 1;import java.awt.Font;System.out.println("This car is a "+ color + " " + make);

    m.engineState = true;

    Expressions : statements which return values Block: compound statements. They are surrounded by braces({}).

    3.2 Variables and Data Types

    Declaring Variables Variable definition can go anywhere in a method definition Instance variables vs. Class variables

    Example:

    String firstName; // instance variablestatic String lastName; // class variable

    Initializing:Example:

    String myName = "Yong-Han";

    Finalizing: (constant)Example:

    final String myName = "Kumara";

    Variable NamesExample:

    int _number, $money, 5five // O.K

    button theButton; // By convention, Java variables longreallyBigNumber; // have meaningful names, oftenboolean currentWeatherState; // are made up of several

    // words combined.

    Variable Types Primitive types:

    Category Type Size / Format Description

    byte 8-bit two's complement Byte-length integerInteger

    short 16-bit two's complement Short integer

  • 7/29/2019 Java Tutorial for Beginners

    11/31

    IE582 Spring-2004 11

    int 32-bit two's complement Integer

    long 64-bit two's complement Long integer

    float 32-bit IEEE 754 Single -precisionfloating point

    Real Numberdouble 64-bit IEEE 754 Double-precision

    floating pointchar 16-bit Unicode character A single character

    Other Types boolean true or false A boolean value(true or false)

    Class types: variables in Java can also be declared to hold an instance of aparticular class. These variables can hold instances of the named class orof anyof its subclasses.

    Example:

    String myName;Object theObject;//this variable can hold any object.

    Assigning Values to Variables: using operator =.Example:

    myName = "Mahima" ;x = y = z = 0;x += y; // x = x + yx -= y; // x = x - yx *= y; // x = x * yx /= y; // x = x / y

    Comments: /* and */ // /** and */ used by the javadoc system to generate API documents

    LiteralsExample:

    Number Literals: -45, 4L, 0777, 0XFF, 2.56F, 10e45, .36E-2, ..

    Boolean Literals: true, false

    Character Literals: 'a', '#', '3', \n, \\, \", ..

    String Literals: "A string with a \t tab in it.", ..

    3.3 Expressions and Operators Arithmetic: +, -, *, /, % (modulus operator) Incrementing and Decrementing

    Example:y = x++; // y = x; x = x + 1;y = ++x; // x = x + 1; y = x;

    Comparisons: ==, !=, , =

  • 7/29/2019 Java Tutorial for Beginners

    12/31

    IE582 Spring-2004 12

    Logical operators: &, &&, |, ||, ^, !3.4 String Arithmetic

    Additional operator (+) to create and concatenate strings.Example:System.out.println(name + " is a " + color + " beetle");myName += " Jr."; // myName = myName + " Jr.";

    3.5 Modifiers

    Modifiers are special keywords that modify the definition of a class, method, orvariable.

    Access Control: public, protected, private Making class methods, variables: static Finalizing: final Others: abstract, synchronized, volatile, native

    3.6 Conditional Statement

    3.6.1 if conditional statement

    if (expression) if (expression)statement ,or statement-1

    else

    statement-2

    The conditional expression returns boolean value (true orfalse)Example:

    if (engineState == true)System.out.println("The engine is already on.");

    else {engineState = true;System.out.println("The engine is now on.");

    }

    3.6.2 switch Conditional Statement

    When the result of a test can be represented by byte, char, short, orint.

    Example:

    int month;int numDays;. . .

  • 7/29/2019 Java Tutorial for Beginners

    13/31

    IE582 Spring-2004 13

    switch (month) {case 1:case 3:case 5:case 7:

    case 8:case 10:case 12:

    numDays = 31;break;

    case 4:case 6:case 9:case 11:

    numDays = 30;

    break;case 2:

    if (((year%4 == 0) && !(year%100 == 0)) || (year%400== 0))

    numDays = 29;

    elsenumDays = 28;

    break;

    } // end of switch (month)

    3.7 Loop statement

    3.7.1 for Loops

    for (initialization; test; increment)

    statement;

    Example:String strArray[] = new String[10];int i;for (i = 0; i < strArray.length; i++)

    strArray[i]= a;

    3.7.2 while and do Loops

    To repeat a statement or block of statements as long as particular condition istrue.

    Example:

    while (condition) {bodyOfLoop;

    } // check the condition before the body of loop

  • 7/29/2019 Java Tutorial for Beginners

    14/31

    IE582 Spring-2004 14

    int x = 1;while (x

  • 7/29/2019 Java Tutorial for Beginners

    15/31

    IE582 Spring-2004 15

    Example:

    // When the condition (i * x == 400), the break causes// the execution to break out of both loops (for and// while) and continue executing any code after both loops.

    out: // a labelfor (int i = 0; i < 10; I++) {

    while (x < 50) {

    if (i * x == 400)break out;

    ...}...

    }

  • 7/29/2019 Java Tutorial for Beginners

    16/31

    IE582 Spring-2004 16

    4 Working with Objects

    4.1 Package

    4.1.1 Defining package Put package name at the beginning of a java file

    Example://Bicycle.java

    package myapp.test;

    The directory structure has to be the same as the package organizationExample:

    Bicycle.java has to be in the directory of .\ myapp\test\Bicyle.java

    If no explicit package, default package uses the current directory4.1.2 Using package

    Classes from packages other than java.lang must be explicitly imported orrefereed to by full package name. (* Packages do not limit the inheritance, i.e. aclass can be inherited from a class in other packages)

    Example:

    import java.awt.Graphics;import java.awt.Font;import java.awt.*;

    import myapp.util.*;// The directory .\myapp\util needs to be set in the// classpath of the system variable

    public class .. {Font f; // java.awt.Font f;

    ...

    4.2 Class

    4.2.1 Defining classes

    Java access specifiers + class + class name + variables + methods4.2.2 Defining variables

    Java access specifiers + Type (Class) + variable name4.2.3 Defining methods

    Java access specifiers + return type(class) + method name + parameterlist

    Example:

    //Bicycle.java

  • 7/29/2019 Java Tutorial for Beginners

    17/31

    IE582 Spring-2004 17

    public class Bicycle{

    double currentSpeed;

    int currentCadence;

    int numberOfGears;

    int currentGear;

    public void brake();

    public void changeCadence(int cadence);

    public void changeGear(int gear);

    }

    4.2.4 Java access specifiers

    Friendly (no specifier): public to the same package and private to otherpackages

    public: everybody, everywhere can access it protected: only inheriting classes can access it private: only the class itself can access it

    4.3 Inheritance

    Use keyword extendsExample://MountainBicycle.java

    class MountainBicycle extends Bicycle{

    public void climbUp();

    public void quickDown();

    }

    The friendly members in the same package can be accessed by subclasses4.4 Interface

    Use keyword interface to define an InterfaceExample://Inventory.java

    Use keyword implements to agree the interface//Bicycle.java will be modified in the following waypublic class Bicycle implements Intentory{

    double currentSpeed;

    int currentCadence;

    int numberOfGears;

    int currentGear;

    public void brake();public void changeCadence(int cadence);

    public void changeGear(int gear);

    //implements the following methods

  • 7/29/2019 Java Tutorial for Beginners

    18/31

    IE582 Spring-2004 18

    void setRetailPrice(int price);}

    All the methods defined in the interface needs to be implemented

    4.5 Creating New Objects

    Using new To create a new object, use the new operator with the name of the class

    (exception for String object creation using string literal).

    Example:

    String str = new String();

    Random r = new Random();Tree t = new Tree();

    The number and type of arguments are defined by the special method constructor.

    Example:

    Date d1, d2, d3; // class in the java.util packaged1 = new Date(); // current time

    d2 = new Date(98, 8, 22, 18, 0); // 1998 Sep. 22, 6:00 pmd3 = new Date(September 22 1998 6:00 PM);

    constructors: special methods that initialize a new object, set its variables,create any other objects that object needs, and generally perform any otheroperations the object needs to initialize itself.

    What new Does New instance of the given class is created. Memory is allocated. The constructor method is called.

    Example:

    public class Car {String make = Nissan;String color = red;

    boolean engineState = false;

    Car() {System.out.println(a Car object created);

    }

    Car(String mk, String cl) {this();make = mk;color = cl;

  • 7/29/2019 Java Tutorial for Beginners

    19/31

    IE582 Spring-2004 19

    }

    Car(String mk, String cl, boolean es) {this(mk,cl);engineState = es;

    }}

    4.6 Accessing and Setting Class and Instance Variables

    use dot notation.Eexample:

    myCar.make, myCar.color

    Changing valuesExample:

    myCar.engineState = true;

    Class Variables: variables that are defined and stored in the class itself (statickeyword), only one copy of the variable exists among all its instantiations.

    4.7 Calling Methods

    use dot notationExample:

    myCar.startEngine();myCar.changeColor(blue);theMake = myCar.getColor();

    More complicated example:

    public class Car {Engine engine;...Engine GetEngine(){

    Return engine;}

    ...}

    public class Engine {long CC;

    ...void getCC(){

    Return CC;}...

    }

    long theCC = myCar.GetEngine().getCC(); //long theCC = myCar.GetEngine().CC; // They are all

  • 7/29/2019 Java Tutorial for Beginners

    20/31

    IE582 Spring-2004 20

    long theCC = myCar.engine.getCC(); // the same.long theCC = myCar.engine.CC; //

    Class methods: method that can be called without any instantiation of its class.Example:

    int biggerOne = Math.max(x, y);

    // We dont need to create an object of class Math at all!

    4.8 References to Objects

    Assigning objects to variables and passing objects as arguments to methods passing references to those objects, not the objects themselves or copies of those

    objects.

    Example:

    Point pt1, pt2; // create two variables for class Point

    pt1 = new Point(100,100);pt2 = pt1;pt1.x = pt1.y =150;

    4.9 Casting and Converting Objects and Primitive Types

    Casting: converts the value of an object or primitive type into another type. Casting Primitive Types: (typename) value

    Example:

    i = (int) (x / y); // x and y are floats, i is an integer.

    Casting Objects: (classname) object The class and the object must be related by inheritance.Example:

    Apple a = new Apple();GreenApple aGreen = new GreenApple();a = aGreen; // no casting neededaGreen = (GreenApple)a; // casting needed

    Converting Primitive Types to Object and Vice Versa direct casting notallowed! Use constructors and special methods in the classes.Example:

    Integer intObject = new Integer(35);int theInt = intObject.intValue(); // return 35

    x:150

    pt1

    pt2

    Point

    Apple

    GreenAppl

  • 7/29/2019 Java Tutorial for Beginners

    21/31

    IE582 Spring-2004 21

    4.10 Comparing Objects

    Cannot use the comparison operators except == and !=, which just test whetherthe two operands refer to exactly the same object in memory.

    Instead, in order to compare the contents of objects, you have to implementspecial methods in your class, and use them.Example:

    boolean equalOrNot = myString.equals(yourString);// equals() method was implemented in String class.

    4.11 The J ava Class Library

    Standard Java packages support a huge set of classes that are guaranteed to beavailable in any commercial Java environment.

    Those classes are in the java and javax package including: java.lang.* Classes that apply to the language itself, including theObject class, the String class, and the System class. It also contains the

    special classes for the primitive types (Integer, Character,Float, andso on).

    java.util.* Utility classes, such as Data, as well as simple collectionclasses, such as Vector and Hashtable.

    java.io.* Input and output classes for writing to and reading fromstreams (such as standard input and output) and for handling files.

    java.net.* Classes for networking support, including Socket and URL(a class to represent references to documents on the WWW).

    java.awt.* This is the Abstract Windowing Toolkit. It contains classesto implement graphical user interface features, including classes forWindow, menu, Button, Font, CheckBox, and so on. It alsoincludes mechanisms for managing system events and for processing images

    (in the java.awt.Image package).

    java.applet.* Classes to implement Java applets. And a lot more: javax.swing.*, java.bean.*, java.math.*,

    java.rmi.*, java.security.*, java.sql.*,java.text.*, ...

    Reference URL: http://javasoft.com/products

  • 7/29/2019 Java Tutorial for Beginners

    22/31

    IE582 Spring-2004 22

    5 Array and Container Objects

    5.1 Array Objects

    5.1.1 Arrays in Java Each slot in the array can hold an object or a primitive value. Arrays in Java are objects. Steps to create an array in Java:

    Declare a variable to hold the array. Create a new array object and assign it to the array variable. Store things in that array.

    An array of objects in Java is an array of references to those objects!5.1.2 Declaring Array Variables

    Use empty brackets ([]).Example:String studentNames[];String[] studentNames;Point centerPts[];Point[] centerPts;int temps[];int[] temps;

    5.1.3 Creating Array Objects

    Use new, or directly initialize the contents of that array.Example:

    String[] names = new String[10];int[] theNumbers = new int[100];Car[] theCars = new Car[100];

    String[] names = {Yong-Han, Goutam, Shreesh};boolean[] isGoodGuy = {true, true, true};

    5.1.4 Accessing Array Elements

    Use the array subscription expression ([]). Use the instance variable length to test the length of an array.

    Example:currentString = theStrings[i++];

    int theFirst = theNumbers[0];int theLast = theNumbers[theNumbers.length-1];

    5.1.5 Changing Array Elements

    Just use assignment statements.Example:theStrings[10] = Hello!;theNumbers[0] = 15;

    theNumbers[i] = theNumber[i+1]; // Primitives type

  • 7/29/2019 Java Tutorial for Beginners

    23/31

    IE582 Spring-2004 23

    Car[2] = Car[3]; // Object type// what is the difference between them?

    5.2 Container Objects

    5.2.1 Container taxonomy

    5.2.2 Some Useful Container Objects

    Vector: a growable array of objects. ArrayList: resizable-array implementation of the List interface. Hashtable: This class implements a hashtable, which maps keys to values Stack: a growable array implementing first in last out mechanism HashSet: implements a set in a hash table TreeSet: implements a set in a tree structure, it can be sorted HashMap: implements a map in a hash table TreeMap: implements a map in a tree structure LinkedList: implements a linked list

    5.2.3 More on LinkedList

    Linked list is a simple but powerful data structure for the dynamic memory allocation.

    Java has fully implemented it.

    Define a Linked List

  • 7/29/2019 Java Tutorial for Beginners

    24/31

    IE582 Spring-2004 24

    import java.util.*;...List list = new LinkedList();

    Iterate the listIterator it = list.iterator();while(it.hasNext()){

    Object o = it.next();

    }

    Add an itemlist.add(o);

    Remove an itemList.remove(o); // o is an object in the listlist.remove(i); // i is the index of an object in the list

    Update an item(1)use iterator to locate the object(2)update the object using the reference

  • 7/29/2019 Java Tutorial for Beginners

    25/31

    IE582 Spring-2004 25

    6 Input and Output

    6.1 Stream?

    Astream is a path of communication between the source of some information andits destination.

    Procedure for reading and writing dataReading Writing

    open a streamwhile more information

    read informationclose the stream

    open a streamwhile more information

    write informationclose the stream

    6.2 Character Streams and Byte Streams

    Character Streams: read and write a stream of characters (16 bits)o Reader and Writer are the abstract super classes for all character streams.

  • 7/29/2019 Java Tutorial for Beginners

    26/31

    IE582 Spring-2004 26

    Byte Streams: read and write a stream of bytes (8 bits).o InputStream and OutputStream are the abstract super classes for all byte

    streams.

    o These streams are typically used to read and write binary data such as images andsounds

    6.3 Reading Console Input

    Use predefined stream variable System.in and BufferedReader object.Example:char ch;

    String str;BufferedReader br = new BufferedReader(new

    InputStreamReader(System.in));

    try { // read a character.c = (char) br.read();

    } catch (IOException e) {

    System.out.println(e.getMessage());}

    try { // read a String.str = br.readLine();

    } catch (IOException e) {System.out.println(e.getMessage());

    }

  • 7/29/2019 Java Tutorial for Beginners

    27/31

    IE582 Spring-2004 27

    6.4 Writing Console Output

    Use predefined print and printlnmethods ofSystem.out object.Example:String str = a string line;System.out.println(str);System.out.print(str + \n);

    6.5 Reading and Writing Files

    Use two stream classes, FileInputStream andFileOutputStream.Example:try { // read String lines from the file input.txt

    FileInputStream fis = new FileInputStream(input.txt);BufferedReader buff = new BufferedReader(new

    InputStreamReader(fis));String line = new String();while((line = buff.readLine()) != null)

    System.out.println(line);} catch (FileNotFoundException e){

    System.out.println(e.getMessage());} catch (IOException e){

    System.out.println(e.getMessage());}

    try { // write a String array to the file output.txtFileOutputStream fos = new FileOutputStream(output.txt);BufferedWriter buff = new BufferedWriter(new

    OutputStreamWriter(fos));

    String[] line = {line 1, line 2, line 3, line 4};for (int i=0; i

  • 7/29/2019 Java Tutorial for Beginners

    28/31

    IE582 Spring-2004 28

    isatest

    In the above example, the delimiters are in the string " \t\n\r\f". You can

    also customize the delimiters.

    Example:StringTokenizer st = newStringTokenizer("kaizhi:student:2002", :\n\f);while (st.hasMoreTokens()) {

    System.out.println(st.nextToken());}

    The output result is:kaizhistudent2002

    The StreamTokenizer class takes an input character stream and parses it intotokens, allowing the tokens to be read one at a time.

  • 7/29/2019 Java Tutorial for Beginners

    29/31

    IE582 Spring-2004 29

    7 Java Application

    7.1 Creating J ava Applications

    Applications are Java programs that run on their own, while applets are Javaprograms that run on the Java-enabled browser and servlets run on the Java-

    enabled web server. A main() method must exist in aapplication.

    A typical example of the main() method:Public static void main(String args[]) {

    ...

    }

    Helper Classes: you can create as many classes as you want for your program, andas long as (1) they are in the same directory, (2) listed in your CLASSPATH, or(3) explicitly declare using java command option classpath, Java will beable to find them when your program runs.

    7.2 J ava Applications and Command-Line Arguments

    Passing Arguments to Java Programs: append them to the command line! They are separated by spaces.(example)

    java Myprogram argumentOne 2 three fourth argument

    Handling Arguments in Your Java program The arguments are stored in an array of strings.Example:

    class EchoArgs {public static void main(String args[]) {

    for (int i = 0; i < args.length; i++) {System.out.println(Argument + i + : +

    args[i]);}

    } // end of main()} // end of EchoArgs

    Example:

  • 7/29/2019 Java Tutorial for Beginners

    30/31

    IE582 Spring-2004 30

    class SumAverage {public static void main(String args[]) {

    int sum = 0;

    for (int i = 0; i < args.length; i++) {

    sum += Integer.parseInt(args[i]);// convert string arguments to integer values

    }System.out.println(Sum = + sum);System.out.println(Average = +

    (float)sum / args.length);} // end of main()

    } // end of SumAverage

  • 7/29/2019 Java Tutorial for Beginners

    31/31

    8 What you need for (serious) Java Programming

    8.1 Buy a J ava book (or use online tutorials)

    Java Tutorial from Sun: http://java.sun.com/docs/books/tutorial/8.2 Use (hyperlinked) J ava APT specification

    Java 2 (v1.4) API Specification: http://java.sun.com/j2se/1.4/docs/api/8.3 Use RAD Tools (especially for GUI programming) if possible

    Full fledged RAD tools: Visual Caf, JBuilder, etc. Or, Java editor for writing, compiling, executing, and locating syntax errors: JPad,

    Editplus, etc.

    8.4 * Some (possibly) important, but not covered topics Graphic / Window User Interface : JFC/Swing (javax.swing.*), 2D

    Graphics (java.awt.Graphics2D, java.awt.geom.*), etc.

    Multiple tasks at once: Multithreading (java.lang.thread) Database Access: JDBC Database Access (java.sql.*) Integrating Native Codes: Java Native Interface (JNI) And, Networking, Remote Method Invoking, Security, etc