Java Tutorial For Beginners
Java Tutorial For Beginners
http://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 ........................................................... 3 1.3 Why Java? ........................................................................................................... 3 1.4 Different Types of Java Programs ...................................................................... 3 1.5 Getting stated with Java Programming ............................................................... 4 2 Important Java Concepts ............................................................................................. 6 2.1 Object .................................................................................................................. 6 2.2 Message ............................................................................................................... 6 2.3 Class.................................................................................................................... 7 2.4 Inheritance........................................................................................................... 7 2.5 Interface .............................................................................................................. 8 2.6 Package ............................................................................................................... 8 3 Java Language Basics ............................................................................................... 10 3.1 Statements and Expressions .............................................................................. 10 3.2 Variables and Data Types ................................................................................. 10 3.3 Expressions and Operators................................................................................ 11 3.4 String Arithmetic ............................................................................................... 12 3.5 Modifiers ........................................................................................................... 12 3.6 Conditional Statement....................................................................................... 12 3.6.1 if conditional statement ............................................................................. 12 3.6.2 switch Conditional Statement ................................................................... 12 3.7 Loop statement .................................................................................................. 13 3.7.1 for Loops ................................................................................................ 13 3.7.2 while and do Loops................................................................................... 13 3.7.3 Breaking Out of Loops.............................................................................. 14 4 Working with Objects ............................................................................................... 16 4.1 Package ............................................................................................................. 16 4.1.1 Defining package ...................................................................................... 16 4.1.2 Using package ........................................................................................... 16 4.2 Class.................................................................................................................. 16 4.2.1 Defining classes ........................................................................................ 16 4.2.2 Defining variables..................................................................................... 16 4.2.3 Defining methods ...................................................................................... 16 4.2.4 Java access specifiers................................................................................ 17 4.3 Inheritance......................................................................................................... 17 4.4 Interface ............................................................................................................ 17 4.5 Creating New Objects ....................................................................................... 18 4.6 Accessing and Setting Class and Instance Variables ........................................ 19 4.7 Calling Methods ................................................................................................ 19 4.8 References to Objects........................................................................................ 20 4.9 Casting and Converting Objects and Primitive Types ...................................... 20 4.10 Comparing Objects ........................................................................................... 21 IE582 Spring-2004 1
4.11 The Java Class Library...................................................................................... 21 Array and Container Objects..................................................................................... 22 5.1 Array Objects .................................................................................................... 22 5.1.1 Arrays in Java ............................................................................................ 22 5.1.2 Declaring Array Variables ........................................................................ 22 5.1.3 Creating Array Objects ............................................................................. 22 5.1.4 Accessing Array Element s ........................................................................ 22 5.1.5 Changing Array Elements ......................................................................... 22 5.2 Container Objects.............................................................................................. 23 5.2.1 Container taxonomy.................................................................................. 23 5.2.2 Some Useful Container Objects ................................................................ 23 5.2.3 More on LinkedList .................................................................................. 23 Input and Output ....................................................................................................... 25 6.1 Stream? .............................................................................................................. 25 6.2 Character Streams and Byte Streams ................................................................ 25 6.3 Reading Console Input...................................................................................... 26 6.4 Writing Console Output .................................................................................... 27 6.5 Reading and Writing Files ................................................................................ 27 6.6 Parsing String Input using Tokenizers .............................................................. 27 Java Application........................................................................................................ 29 7.1 Creating Java Applications ............................................................................... 29 7.2 Java Applications and Command-Line Arguments .......................................... 29 What you need for (serious) Java Programming....................................................... 31 8.1 Buy a Java book (or use online tutorials).......................................................... 31 8.2 Use (hyperlinked) Java APT specification........................................................ 31 8.3 Use RAD Tools (especially for GUI programming) if possible ....................... 31 8.4 * Some (possibly) important, but not covered topics ....................................... 31
IE582 Spring-2004
Performance n Exception handling mechanism Robust n Interpreted but still high performance (using Just In Time Compiler technology) And, Network-Savvy, Secure, Multi-threaded, Dynamic, etc.
IE582 Spring-2004
Install the JDK Unzip the documentation: C:\ j2sdk1.4.2\docs Creating a Java Application n Creating the Source File: u using text editors u file name extension: .java u file name = class name (example: HelloWorld.javafor class HelloWorld ) class HelloWorld { public static void main(String[] args){ System.out.println("Hello World!"); } }
Compiling and Running the Source File u javac HelloWorld.java ( bytecode: HelloWorld .class) u java HelloWorld Creating 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); } } }
IE582 Spring-2004
Including the Applet in a Web page (Only for Netscape, IE is different) <HTML> <HEAD> <TITLE> A Simple Program </TITLE> </HEAD> <BODY> Here is the output of my program: <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML>
IE582 Spring-2004
l l
Bicycles: state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears) Software objects to model real-world objects: variables and methods Definition : An object is a software bundle of variables and related methods
Encapsulation: package an object s variable within the protective custody of its method => methods restrict and protect the variable access in an object l Benefit of Encapsulation n Modularity: write and maintain source code of other objects independently n 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
Benefits o Message parsing support all possible interactions between objects o Objects don t need to be in the same processor or even on the same machine => distributed computing is easy in Java Java Program = Objects + Message interactions
IE582 Spring-2004
2.3 Class
l Definition: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. o All the bicycles share the same characteristics and they can be defined as one class A class is an abstract of a group of objects
2.4 Inheritance
IE582 Spring-2004
Subclasses: Mountain Bike, Racing Bike, Tandem Bike Superclass: Bicycle The class variables and methods in the subclasses are the subsets of those in the superclass o Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviors: braking and changing pedaling speed o Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio Subclass can overrides some methods in the superclass o 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 times o Programmers can implement superclasses called abstract classes that define "generic" behaviors . The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses
2.5 Interface
Definition : a device that unrelated objects use to interact with each other o Analogous to a protocol (an agreed on behavior) Example: Inventory Interface o Bicycle class hierarchy defines different bicycle classes o They needs to be used in an inventory program o Inventory program only needs to know tracking numbers and retail prices o An inventory interface is defined to connect bicycles and the inventory programs o This interface can also be used by other class that needs to be used in the inventory program Benefits o 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 its class
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.*;
IE582 Spring-2004
Benefits o Easy to manage large projects o Set access barrier between different groups of classes
IE582 Spring-2004
Expressions : statements which return values Block: compound statements. They are surrounded by braces({}).
Initializing: Example:
String myName = "Yong-Han";
IE582 Spring-2004
10
int long float Real Number double char Other Types boolean
32-bit two's complement 64-bit two's complement 32-bit IEEE 754 64-bit IEEE 754 16-bit Unicode character true or false
Integer Long integer Single -precision floating point Double-precision floating point A single character A boolean (true or false) value
Class types: variables in Java can also be declared to hold an instance of a particular class. These variables can hold instances of the named class or of any of its subclasses. Example:
String myName; Object theObject;//this variable can hold any object.
Literals Example:
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.", ..
IE582 Spring-2004
3.5 Modifiers
Modifiers are special keywords that modify the definition of a class, method, or variable. Access Control: public, protected, private Making class methods, variables: static Finalizing: final Others: abstract, synchronized, volatile, native
,or
IE582 Spring-2004
12
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; else numDays = 28; break;
Example: String strArray[] = new String[10]; int i; for (i = 0; i < strArray.length; i++) strArray[i]= a ;
while (condition) { bodyOfLoop; } // check the condition before the body of loop
Example:
IE582 Spring-2004
13
do { // check the condition after the body of loop bodyOfLoop; } while (condition);
Example:
int x = 1; do { System.out.println(looping, round + x); x++; } while (x <= 10)
continue: when used in a loop, it immediately skip the current iteration, and the loop starts over at the next iteration. Example:
//Loop to copy non-zero elements from array1 into array2 // until the end of the array1. (by skipping zero-elements) int count1 = 0; int count2 = 0; while (count < array1.length) { if (array1[count] == 0) { continue; count1++; } array2[count2++] = array1[count1++]; }
Labeled loops : let the program break to specific points outside nested loops or continue a loop outside the current loop.
IE582 Spring-2004
14
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 label for (int i = 0; i < 10; I++) { while (x < 50) { if (i * x == 400) break out; ... } ... }
IE582 Spring-2004
15
The directory structure has to be the same as the package organization Example:
Bicycle.java has to be in the directory of .\ myapp\test\Bicyle.java
...
4.2 Class
4.2.1 Defining classes
Java access specifiers + class+ class name + variables + methods
IE582 Spring-2004
16
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.3 Inheritance
Use keyword extends Example:
//MountainBicycle.java class MountainBicycle extends Bicycle{ public void climbUp(); public void quickDown(); }
4.4 Interface
Use keyword interfaceto define an Interface Example:
//Inventory.java
Use keyword implementsto agree the interface //Bicycle.java will be modified in the following way
public 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
IE582 Spring-2004
17
The number and type of arguments are defined by the special method constructor. Example:
Date d1 = d2 = d3 = d1, new new new d2, d3; // class in the java.util package Date(); // current time Date(98, 8, 22, 18, 0); // 1998 Sep. 22, 6:00 pm 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 other operations 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;
IE582 Spring-2004
18
Class Variables : variables that are defined and stored in the class itself (static keyword), only one copy of the variable exists among all its instantiations.
IE582 Spring-2004
19
// the same. //
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!
pt2
150 y:
Casting Objects: (classname) object The class and the object must be related by inheritance. Apple GreenAppl Example:
Apple a = new Apple(); GreenApple aGreen = new GreenApple(); a = aGreen; // no casting needed aGreen = (GreenApple)a; // casting needed
Converting Primitive Types to Object and Vice Versa direct casting not allowed! Use constructors and special methods in the classes. Example:
Integer intObject = new Integer(35); int theInt = intObject.intValue(); // return 35
IE582 Spring-2004
20
IE582 Spring-2004
21
IE582 Spring-2004
22
import java.util.*; ... List list = new LinkedList(); Iterate the list Iterator it = list.iterator(); while(it.hasNext()){ Object o = it.next(); } Add an item list.add(o); Remove an item List.remove(o); // o is an object in the list list.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
IE582 Spring-2004
24
Writing
open a stream while more information write information close the stream
IE582 Spring-2004
25
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 and sounds
IE582 Spring-2004
26
IE582 Spring-2004
27
is a test
In the above example, the delimiters are in the string " \t\n\r\f". You can also customize the delimiters. Example:
StringTokenizer st = new StringTokenizer("kaizhi:student:2002", :\n\f); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }
The StreamTokenizer class takes an input character stream and parses it into tokens, allowing the tokens to be read one at a time.
IE582 Spring-2004
28
7 Java Application
7.1 Creating Java Applications
Applications are Java programs that run on their own, while applets are Java programs that run on the Java-enabled browser and servlets run on the Javaenabled web server. A main() method must exist in a application. 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, and as 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 be able to find them when your program runs.
(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:
IE582 Spring-2004
29
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
IE582 Spring-2004
30
IE582 Spring-2004
31