Download Java Programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Programming
(Chapter 1)
Java Programming
In this course, we will study different kinds of data structures
and some methods for designing algorithms. For practice
purpose, all the discussed algorithms are implemented in Java
language.
Algorithm readDVDFile()
read the title of the first DVD
while there are more DVDs
read the rest of the DVD data
store the DVD data in the vector
read the title of next DVD
close the input file
Classes, Types, and Objects
A class is a data structure that binds together the data and
operations on the data.
Therefore, a class can have two kinds of members in it:
 data fields
 methods (operation)
Here is an example of a simple class:
public class NameInStars {
// data fields
private String name;
// methods
public NameInStars(String nam) {
name = nam;
}
public String surroundNameInStars() {
return "*****" + name + "*****\n" +
"*****" + name + "*****\n" +
"*****" + name + "*****";
}
}
public class Factorial3 {
Static long[] table = new long[21];
Static {table[0] = 1;}
//factorial of 0 is 1
static int last = 0;
public static long factorial(int x) {
while (last < x) {
table [last + 1] = table[last]*(last + 1);
last++;}
}
}
The syntax for a Java class definition is as follows:
[<class_modifiers>] class <class_name>
[extends <superclass_name>]
[implements <interface_1>, <interface_2>, ...] {
// data fields
// methods
}
An object of a given class is an instance of the class. Objects
have the memory storage for the data fields and methods.
Class Modifiers
abstract: Indicate that the class has abstract methods. Abstract
methods are declared with the abstract keyword and do not
have the body of code.
final: Indicate that the class can have no subclasses.
public: Indicate that the class can be instantiated or extended
by any class.
Without the public class modifier, the class can be used and
instantiated by all classes in the same package.
Package
A package is a group of classes and interfaces. You can assign the classes and interfaces
in a source file to a particular package by using a package statement with the following
syntax:
package <packageName>
Example:
package engineering;
package engineering.electrical.signals;
• If a package statement is used, it must appear as the first statement in that source file.
• If a source file does not contain a package statement, its classes and interface are
placed in a default package – normally, the current fold.
Base Types
Classes are treated as data types. However, there are data types
that are not classes. They are called base types.
boolean
char
byte
short
int
long
float
double
Boolean value: true or false
16-bit Unicode character
8-bit signed integer
16-bit signed integer
32-bit signed integer
64-bit signed integer
32-bit floating-point number
64-bit floating-point number
Objects
A new object in Java is created by using the new operator.
<variable_name> = new <class_type>([param1, param2, …]);
Example:
myPoint = new Point(3, 6);
Three things happen when the above code is executed.
 A memory block is dynamically allocated to store the
object. All data fields are initialized to standard default
values.
 The constructor for the new object is called with the
parameter specified.
 The new operator returns a reference (a memory address)
to the newly created object. This reference is assigned to
the object variable.
myPoint
object of Point
For simplicity, we
call the variable
myPoint an object
variable. But
understanding this
picture is very
important.
Java also provides wrapper classes for the base types.
Base Type
boolean
char
byte
short
int
long
float
double
Class Name
Boolean
Character
Byte
Short
Integer
Long
Float
Double
Creation Example
n = new Boolean(true)
n = new Character(‘c’)
n = new Byte((byte)34)
n = new Short((short)100)
n = new Integer(1045)
n = new Long(10849L)
n = new Float(3.934F)
n = new Double(3.934)
Wrapper classes stores numbers in objects. They are useful
because some data structures cannot handle base types.
String Objects
In Java, string objects are easy to create and use. For example,
we don’t need to use the new operator to create a String object.
Example:
String s = "kilo" + "meters";
String s = new String("kilo" + "meters");
char a = s[0];
char b = s.charAt[1];
String substring = s.substring(0, 10);
int index = s.indexOf('m');
Instance Variables
Data fields in a class declaration are called instance variables.
Example:
class Gnome {
protected String name;
protected int age;
private boolean magical;
public double height = 2.6;
public static final int MAX_HEIGHT = 3;
. . .
}
Variable Modifiers
public: Anyone can access the variables.
protected: Only methods of the same package or of
subclassess can access the variables.
private: Only methods of the same class can access private
instance variable.
If none of above modifiers are used, the variables can be
accessed by any class in the same package.
Class variables and constants
static: A variable that is associated with the class, not with
individial instances of the class.
final: A variable that must have an initial value. And the value
cannot be changed. Used to define constant.
Methods
Methods are members in some class. They are the functions
that can be invoked to update and access data fields in the
class.
[<method_modifiers>] <return_type> <method_name> (parameter_list) {
// method body . . .
}
Example:
public void rename( String s ) {
name = s;
}
Method Modifiers
public: Anyone can call the method.
protected: Only methods of the same package or of subclass
can call the method.
private: Only methods of the same class can call the method.
abstract: The method is to be overridden in subclasses.
Abstract methods are declared without method body.
Example:
public abstract void setHeight( double newHeight );
Note the difference between the above and the following:
public void setHeight( double newHeight ){ };
final: The method cannot be overridden by a subclass.
static: The method is a class method that is not associated with
any instance of the class.
Constructor Methods
A constructor is a special method that is executed when an
object of the class is being created. Its method name is exactly
the same as the class name, within which it is defined.
[constructor_modifiers] <class_name> (parameter_list) {
// constructor body
}
Example:
public Fish( int w, String n ) {
weight = w;
name = n;
}
The main Method
The main method in a class funtions as the starting point for a
stand-alone Java program. When the program is executed, the
Java virtual machine executes the main method.
public static void main( String[] args ) {
// main method body . . .
}
The Dot Operator
Recall that a class can have data fields and methods. They can
be referenced by means of the dot operator.
Examples:
oven.cookDinner();
oven.cookDinner( food );
oven.setTemporature( t );
Control Structures
In Java, we can use the if and switch statements to control the
execution flow.
We can also use loops including for, while and do loops. Here,
we are interested in a special kind of loops called sentinelcontrolled loops.
sentinel: A special data value used to terminate the loop
Example: 0 or -1 for integer type, or a null string “ ” for String
type, or a null Object value.
Java provides a keyword null to represent a null object.
JoptionPane.showMessageDialog( null, "num is " + num1 );
Example:
public void findSumAndCount() {
int score;
int SENTINEL = -1;
// sentinel value
score = readInt("Enter next score or " + SENTINEL +
" to stop");
// initialize lcv
while (score != SENTINEL) {
// test lcv
sum += score;
// add current score to sum
count++;
// increase count by 1
System.out.println("score: " + score);
score = readInt("Enter next score or " + SENTINEL +
" to stop");
// update lcv
}
}
Arrays
An array is a collection of values of the same type. Arrays are
important in this course because we can use them to implement
data types that contain multiple objects.
Each element in an array is accessed through an integer called
index.
int[] a = new int[ 10 ];
float[][] x = new float[ 8 ][ 10 ];
i = 5;
a[ i ] = 138;
x[ i ][ i + 1 ] = 2.189 + x[ i ][ i ];
double nums[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
About how to create Java program
Choice 1:
1. Using NotePad to produce a .java file.
2. Invoke ‘Commad Prompt’.
3. Using ‘cd’ command to go to the fold where you put your
program.
4. Using ‘javac <file name>’ to compile your program.
5. Using ‘java <file name without .java>’ to run your program.
public class a1q2 {
/**
* main method
*
* prompts input and calls the recursive method
*/
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
System.out.println("result of fn(" + m + ") is " + computeFN(m));
}
/**
* computeFN - the definition of the function
*
* input: int
* output: int
* calculate f(N) = 3*f(N-3) + 4*f(N-2) - 5*f(N-1) where f(0) = 1, f(1) = 1, f(2) = 3.
*/
public static int computeFN(int n)
{
if(n<=0) return 1;
else if(n==1) return 1;
else if(n==2) return 3;
else
return 3 * computeFN(n-3) + 4 * computeFN(n-2) - 5 * computeFN(n-1);
}
}
About how to create Java programs
Choice 2:
1. Using ‘JCreator’ to create Java code, compile it and then run it.
2. If your program is to run with an input of integers, you need
arrange a statement in the main method, before any other
statements as below:
int m = (int)new Integer(JOptionPane.showInputDialog("Enter an integer"));
(see the following example.)
import javax.swing.JOptionPane;
public class a1q2 {
/**
Not forget these two statements.
* main method
*
* prompts input and calls the recursive method
*/
public static void main(String[] args) {
//input dialog
int m = (int)new Integer(JOptionPane.showInputDialog("Enter an integer"));
//calculate f(N) = 3*f(N-3) + 4*f(N-2) - 5*f(N-1) where f(0) = 1, f(1) = 1, f(2) = 3.
System.out.println("result of fn(" + m + ") is " + computeFN(m));
}
/**
* computeFN - the definition of the function
*
* input: int
* output: int
*/
public static int computeFN(int n)
{
if(n<=0) return 1;
else if(n==1) return 1;
else if(n==2) return 3;
else
return 3 * computeFN(n-3) + 4 * computeFN(n-2) - 5 * computeFN(n-1);
}
}