- 1 - (Java Notes 2003-4 Bar Ilan University)

Java Notes for “Programming Languages” and
“Advanced Programming”
Course URLs: http://www.cs.biu.ac.il/~hasonz
http://www.cs.biu.ac.il/~akivan/APCourse.html
old Course URLs: http://www.cs.biu.ac.il/~luryar
http://www.cs.biu.ac.il/~linraz
//FrstProg.java file
class FrstProg
{
/*This program just writes something to the console
and will stop executing*/
public static void main(String[] args)
{
System.out.println("This is the first lesson");
//println is part of API
}
}
HOW TO COMPILE AND RUN JAVA FILES:
Java Compiler:
javac FrstProg.java (creates FrstProg.class)
Java Interpreter:
java FrstProg (executes FrstProg.class)
Output:
This is the first lesson / -Comments //… or /*…*/ or /**…*/
-Blocks {…}
-Methods
-main method (always public static void)
-Identifiers (UpperCase, LowerCase, _, $, Digits) cannot start with digit
case sensitive (TOTAL, Total, total)
-Consistency in naming (Beginning Lowercase => methods and identifiers
Beginning Uppercase => classes
All Uppercase => constants
-print and println methods
-command line arguments (main method)
-object oriented programming (classes, objects, inheritance, etc.)
//Turkey.java File
class Turkey
{
public static void main(String[] args)
{
System.out.print("The international "
+ "dialing code ");
System.out.print("for Turkey is " + 90);
}
}
//NameTag.java File
class NameTag
{
public static void main(String[] args)
{
System.out.println("Hello! My name is " + args[0]);
}
}
javac NameTag.java (compile)
java NameTag XXX (run)
Hello! My name is XXX (output)
To import a package:
import package.class;
Or:
import package.*;
JAVA API (Application Programming Interface)
View: http://java.sun.com/j2se/1.3/docs/api/
Download: http://java.sun.com/j2se/1.3/docs.html
Packages
java.applet creates programs (applets) that are easily transported across
the web.
java.awt (Abstract Windowing Toolkit) Draw graphics and create
graphical user interfaces.
java.io perform a wide variety of I/O functions.
java.lang general support. It is automatically imported.
java.math for high precision calculations.
java.net communicate across a network.
java.rmi (Remote Method Invocation) create programs that can be
distributed across multiple computers.
java.sql interact with databases.
java.text format text for output.
java.util general utilities.
PRIMITIVE DATA TYPES:
byte 8 bits -128 127
short 16 bits -32768 32767
int 32 bits -2 billion 2 billion
long 64 bits -1019 1019
Floating point:
float 32 bits
double 64 bits
Others:
char 16 bits 65536 Unicode characters
boolean false true
void
WRAPPER CLASSES:
Classes declared in package java.lang:
Byte Float Character Boolean Void
Short Double
Integer
Long / OPERATORS:
Unary: + -
Binary: * / % Multiplication, division, remainder
+ - Addition, subtraction
+ String concatenation
= Assignment
+= -= *= /= %=
count++ return count and then add 1
++count add 1 and then return count
count-- return count and then subtract 1
--count subtract 1 and then return count
! Logical not ^ Bitwise xor == !=
Logical and & Bitwise and
|| Logical or | Bitwise or >= <=
CODITIONS AND LOOPS:
condition ? expression1 : expression2
example: int larger = (num1>num2) ? num1 : num2 ;
if (condition) switch (expression) {
Statement1 case value1:
else Statement-list1; break;
Statement2 case value2:
Statement-list2; break;
….
default:
Statement-list3;
}
while (condition) do Statement for (init; cond; incr)
Statement; while (condition); Statement;
continue break return
INSTANTIATION AND REFERENCES
class CarExample
{
public static void main(String[] args)
{
int total = 25;
int average;
average = 20;
//CarClass should be declared
CarClass myCar = new CarClass();
CarClass yourCar;
yourCar = new CarClass();
//To call a method use "."
myCar.speed(50);
yourCar.speed(80);
System.out.println("My car cost $" + myCar.cost());
}
}
class CarClass
{
int _speed;
int _cost;
CarClass()
{
_speed = 0;
_cost = 2500;
}
public void speed(int speed)
{
_speed = speed;
}
public int cost()
{
return _cost;
}
} / GARBAGE COLLECTION
Objects are deleted when there are no more references to them. There is a possibility
to have the System run the garbage collector upon demand using the System.gc()
method.
Calling the gc() method suggests that the Java Virtual Machine expend effort toward
recycling unused objects in order to make the memory they currently occupy available
for quick reuse. When control returns from the method call, the Java Virtual Machine
has made a best effort to reclaim space from all discarded objects.
If we add the line:
CarClass momCar = myCar;
we get the following drawing:
To reduce the number of references to an object,
We do the following:
MyCar = null;
(What would happen in C++ if we do this???)
STRINGS:
class StringExample
{
public static void main (String[] args)
{
String str1 = "Seize the day";
String str2 = new String();
String str3 = new String(str1);
String str4 = "Day of the seize";
String str5 = "Seize the day";
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println("str4: " + str4);
System.out.println("str5: " + str5);
System.out.println();
System.out.println("length of str1 is " + str1.length());
System.out.println("length of str2 is " + str2.length());
System.out.println();
System.out.println("Index of 'e' in str4: "
+ str4.indexOf('e'));
System.out.println("Char at pos 3 in str1: "
+ str1.charAt(3));
System.out.println("Substring 6 to 8 of str1: "
+ str1.substring(6,8));
if (str1==str5)
System.out.println("str1 and str5 refer to the “
+ “same object");
if (str1 != str3)
System.out.println("str1 and str3 don't refer to “
+ “the same object");
if (str1.equals(str3))
System.out.println("str1 and str3 contain the “
+ ”same chars");
System.out.println();
str2 = str1.toUpperCase();
System.out.println("str2 now is: " + str2);
str5 = str1.replace('e','X');
System.out.println("str5 is now: " + str5);
//now check again
if (str1==str5)
System.out.println("str1 and str5 refer to the “
+ “same object");
else System.out.println("str1 and str5 don't refer to “
+ “the same object");
}
} / OUTPUT:


Useful methods for string:
length() :returns the length
charAt (int index) :returns char at that positions (0..)
indexOf(char ch) :returns index (0..) of first occurrence
lastindexOf(char ch) :returns index (0..) of last occurrence
endsWith(String suffix) :returns true if has this suffix
startsWith(String prefix) :returns true if has this prefix
equals(Object obj) :returns true if two strings are the same
equalsIgnoreCase(Object obj) :returns true if two strings are equal, ignoring case
toLowerCase() :returns a new string of lower case
toUpperCase() :returns a new string of upper case
substring(int begin, int end) :returns a new string that is a substring of this string
including begin, excluding end.

java.lang.StringBuffer.
StringBuffer- implements a mutable sequence of characters.
String - implements a constant sequence of characters.
public class ReverseString{
public static void main(String[] args){
String source="abcdefg";
int strLen=source.length();
StringBuffer dest = new StringBuffer( strLen );
for( int i= strLen-1; i>=0; i--){
dest.append( source.charAt(i) );
}
System.out.println( dest );
}
}
output: gfedcba
ARRAYS:
class ArrayTest
{
public static void main(String[] args)
{
ArrayParameters test = new ArrayParameters();
//first way to initialize array with fixed size and data
int[] list = {11,22,33,44,55};
//second way to initialize array. Fixed size.
int[] list2 = new int[5]; //default for int is 0...
//fill in data
for (int i=0; i<list.length; i++)
{
list2[i]=99;
}
test.passElement(list[0]); //list: 11 22 33 44 55
test.chngElems(list); //list: 11 22 77 44 88
test.chngRef(list, list2); //list: 11 22 77 44 88
test.copyArr(list, list2); //list: 99 99 99 99 99
list=test.retRef(list2); //list: 99 66 99 99 99
}
}
class ArrayParameters
{
public void passElement(int num)
{
num = 1234; //no change in original
}
public void chngElems(int[] my1) //reference passed
{
my1[2] = 77;
my1[4] = 88;
}
public void chngRef(int[] my1, int[] my2) //reference passed
{
my1 = my2;
}
public void copyArr(int[] my1, int[] my2)
{
for (int i=0; i<my2.length; i++)
my1[i]=my2[i];
}
public int[] retRef(int[] my1)
{
my1[1] = 66;
return my1;
}
} / MULTI DIMENSIONAL ARRAYS:
class MultiArray
{
int[][] table = {{1,2,3,4},
{11,12},
{21,22,23}};
public void init1()
{
table = new int[5][];
for (int i=0; i<table.length; i++)
{
table[i] = new int[i];
}
}
public void print()
{
for (int rows=0; rows<table.length; rows++)
{
for (int col=0; col<table[rows].length; col++)
System.out.print(table[rows][col] + " ");
//move cursor to next line
System.out.println();
}
}
public static void main(String[] args)
{
MultiArray ma = new MultiArray();
ma.print();
ma.init1();
ma.print();
}
}
OUTPUT:
1 2 3 4
11 12
21 22 23
0
0 0
0 0 0
0 0 0 0
INPUT/OUTPUT:
import java.io.*;
class Greetings
{
public static void main (String[] args)
{
try
{
DataInputStream in = new DataInputStream(System.in);
System.out.println("What is your name?");
String name = in.readLine();
System.out.println("Hello " + name);
}
catch (IOException e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}
What is your name?
Bill Gates
Hello Bill Gates
import java.io.*;
class Sum
{
public static void main (String[] args)
{
try
{
DataInputStream in = new DataInputStream(System.in);
DataInputStream fin = new DataInputStream(new
FileInputStream(“numbers.dat”));
int count;
double total = 0;
System.out.print(“How many numbers? “);
System.out.flush();
count = Integer.parseInt(in.readLine());
for (int i=1; i<=count; i++)
{
Double number = Double.valueOf(fin.readLine());
total += number.doubleValue();
}
System.out.println(“The total is: “ + total);
}
catch (IOException e)
{
System.out.println(“Exception while performing “
+ e.getMessage());
}
}
}
Class java.io.File
import java.io.*;
public class BuildDir
{
public static void main(String[] args) throws IOException
{
File from = new File("source.txt");
File newDir = new File("newDir");
File to = new File("newDir/target.txt");
newDir.mkdir();
FileReader in = new FileReader( from );
FileWriter out = new FileWriter( to );
int character;
while( (character=in.read())!= -1 )
{
out.write(character);
}
in.close();
out.close();
from.delete();
}
}
Useful methods of File
getAbsoulutePath() – return string. Absoulute path of the file.
canRead(),canWrite()-return boolean .app can read/write to file.
IsFile(), isDirectory()- return boolean.
list()- return string[]. The list of the files in the directory.
mkDir() – return boolean. Creat a directory.
renameTo(File des) –return boolean. Renames the file name to the
Des pathname. / “Numbers.dat” file
1.1
2.2
3.3
4.4
10.5
javac Sum.java
java Sum
How many numbers: 5
The total is 21.5
//This program does not use deprecated methods
import java.io.*;
class MyTest
{
BufferedReader reader = null;
public void read()
{
try
{
reader = new BufferedReader (new FileReader ("numbers.dat"));
}
catch (FileNotFoundException f)//if file was not found
{
System.out.println("File was not found");
System.exit(0);
}
try
{
String line= new String();
double sum = 0.0;
while((line=reader.readLine())!=null)
{
double d = Double.parseDouble(line);
sum += d;
}
System.out.println("Sum is " + sum);
}
catch (Exception e)
{
System.out.println("Exception occurred");
}
}
public static void main(String[] args)
{
MyTest test = new MyTest();
test.read();
}
}
java.util.StringTokenizer
import java.io.*;
import java.util.StringTokenizer;
public class Tokens
{
public static void main(String[] args) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int first,second,pitaron;
int i;
char sign;
String line;
do
{
System.out.println("Enter the exercise with =.");
line = in.readLine();
StringTokenizer st=new StringTokenizer(line);
first=Integer.parseInt( st.nextToken("-+*/") );
sign = ( st.nextToken("1234567890") ).charAt(0);
second= Integer.parseInt( st.nextToken("=") );
switch(sign)
{
case '+': pitaron= first+second; break;
case '-': pitaron= first-second; break;
case '*': pitaron= first*second; break;
case '/': pitaron= first/second; break;
default : pitaron =0;
}
System.out.println(line + pitaron);
}
while( pitaron != 0);
}
}
output:
Enter the exercise with =.
12-33=
12-33=-21
StringTokenizer(st1,delim)- construct a StringTokenizer for st1. delim= the delimiters.
StringTokenizer(st1)- construct a StringTokenizer for st1. delimiters= tab,\n,space.(default)
nextToken(delim)- return the string until the delim.
CountTokens()- return the number of tokens, using the current delimiter set.
HasMoreTokens()- return boolean, test if there are more tokens available.

Class RandomAccessFile

+--java.io.RandomAccessFile
public class RandomAccessFile
extends Object
implements DataOutput, DataInput
Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended. The file pointer can be read by the getFilePointer method and set by the seek method.
It is generally true of all the reading routines in this class that if end-of-file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown. If any byte cannot be read for any reason other than end-of-file, an IOException other than EOFException is thrown. In particular, an IOException may be thrown if the stream has been closed.
Since:
JDK1.0
Constructor Summary
RandomAccessFile(Filefile, Stringmode)
Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
RandomAccessFile(Stringname, Stringmode)
Creates a random access file stream to read from, and optionally to write to, a file with the specified name.
EXCEPTION HANDLING:
import java.io.*;
import java.util.*;
class IO
{
private String line;
private StringTokenizer tokenizer;
public void newline(DataInputStream in) throws IOException
{
line = in.readLine();
if (line == null)
throw new EOFException();
tokenizer = new StringTokenizer(line);
}
public String readString(DataInputStream in) throws IOException
{
if (tokenizer == null)
newline(in);
while (true)
{
try
{
return tokenizer.nextToken();
}
catch (NoSuchElementException exception)
{
newline(in);
}
}
}
public double readDouble(DataInputStream in) throws IOException
{
if (tokenizer == null)
newline(in);
while (true)
{
try
{
String str = tokenizer.nextToken();
return Double.valueOf(str.trim()).doubleValue();
}
catch (NoSuchElementException exception)
{
newline(in);
}
}
} /
Example:
import java.io.*;
public class CopyTwoToOne
{
public static void main(String[] args) throws IOException
{
RandomAccessFile in1;
RandomAccessFile in2;
RandomAccessFile out;
in1=new RandomAccessFile("source1.txt","r");
out=new RandomAccessFile("target.txt","rw");
byte[] con = new byte[(int)in1.length()];
in1.readFully(con);
out.write(con);
in1.close();
out.close();
in2=new RandomAccessFile("source2.txt","r");
out=new RandomAccessFile("target.txt","rw");
out.seek( out.length() );
con = new byte[(int)in2.length()];
in2.readFully(con);
out.write(con);
out.writeUTF("end");
in2.close();
out.close();
}