You are on page 1of 27

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.

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.

String Objects
In Java, string objects are easy to create and use. For example,
we dont need to use the new operator to create a String object.
Example:
String s = "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;
}

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
}
}

About how to create Java program


Choice 1:
1. Using NotePad to produce a .java file.
2. Invoke Commad Promt.
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.

About how to create Java programs


Choice 2:
1. Using JCreate to create Java code, compile it and then run it.
2. If your program is to run with some inputs, 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);
}
}

You might also like