Java Tutorial for Beginners
January 29, 2017 | Author: sasdoc2010 | Category: N/A
Short Description
Download Java Tutorial for Beginners...
Description
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
5
6
7
8
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
2
Java Tutorial for Beginners Kaizhi Tang
1 Introduction to Java Programming 1.1 What is Java? l l
Java is a Programming Language: Full- fledged general-purpose programming language, especially object-oriented programming Java is a Platform: Java Virtual Machine (JVM) and Java API (Application Programming Interface)
1.2 Features of Java Programming Language l
Platform Independent: n n
l
Object Oriented n
l
Java program can run on any computer system for which a JVM has been installed Java bytecode / Compiler / Interpreter Java is a pure object oriented programming langauge
Easy to Learn n
Similar to C and C++, but most of more complex parts of them have been excluded
l
Performance n Exception handling mechanism
l
Robust n
l
Interpreted but still high performance (using Just In Time Compiler technology) And, Network-Savvy, Secure, Multi-threaded, Dynamic, etc.
1.3 Why Java? l l l
Shorten development time n Easy to use, Automatic garbage collection, using the third party’s APIs Shorten deployment time n Platform independent Solve complicated problem
1.4 Different Types of Java Programs l l l l
Console Application: Run in command line (*) Applet: Run in the browser (IE or Netscape) Servlet: Run in the Java Servlet container (Jakarta Tomcat) Beans: component strategy in Java, especially in J2EE
IE582 Spring-2004
3
1.5 Getting stated with Java Programming l
Getting a Java Development Environment (JDK) and documentation n n
l
Go to the JavaSoft Web site (http://java.sun.com/j2se/1.4.2/download.html) Download SDK, JRE and documentation
Install the JDK n
For example: C:\ j2sdk1.4.2
l
Unzip the documentation: C:\ j2sdk1.4.2\docs
l
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.java’for ‘class HelloWorld’) class HelloWorld { public static void main(String[] args){ System.out.println("Hello World!"); } }
n
l
Compiling and Running the Source File u javac HelloWorld.java (à bytecode: HelloWorld.class) u java HelloWorld
Creating a Java Applet n
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); } } }
n
Compiling and Running the Source File
IE582 Spring-2004
4
n
Including the Applet in a Web page (Only for Netscape, IE is different) A Simple Program Here is the output of my program:
n
Execution à Web browser or appletviewer
IE582 Spring-2004
5
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, and wagging tail)
§ 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
l
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
6
2.3 Class l
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
7
• • •
•
•
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
8
•
Benefits o Easy to manage large projects o Set access barrier between different groups of classes
IE582 Spring-2004
9
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 variable static String lastName; // class variable
§
Initializing: Example: String myName = "Yong-Han";
§
Finalizing: (constant) Example: final String myName = "Kumara";
•
Variable Names Example: int _number, $money, 5five // à O.K button theButton; // By convention, Java variables long reallyBigNumber; // have meaningful names, often boolean currentWeatherState; // are made up of several // words combined.
•
Variable Types §
Primitive types: Category
Type
Integer
byte
8-bit two's complement
Byte-length integer
short
16-bit two's complement
Short integer
IE582 Spring-2004
Size / Format
Description
10
Real Number
int
32-bit two's complement
Integer
long
64-bit two's complement
Long integer
float
32-bit IEEE 754
Single -precision floating point
double
64-bit IEEE 754
Double-precision floating point
16-bit Unicode character
A single character
true or false
A boolean (true or false)
char Other Types
§
boolean
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.
• Assigning Values to Variables: using operator ‘=’. Example: myName = "Mahima" ; x = y = z = 0; x += y; // x = x + y x -= y; // x = x - y x *= y; // x = x * y x /= y; // x = x / y
•
Comments: • /* and */ • // • /** and */
•
ß used by the javadoc system to generate API documents
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.", ..
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 : ==, !=, , =
IE582 Spring-2004
11
•
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, or variable. •
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) statement
•
,or
if (expression) statement-1 else statement-2
The conditional expression returns boolean value (true or false) 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, or int. Example: int month; int numDays; . . .
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;
} // 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 is true.
while (condition) { bodyOfLoop; } // check the condition before the body of loop
Example:
IE582 Spring-2004
13
int x = 1; while (x
View more...
Comments