Sie sind auf Seite 1von 11

-1- (Java Notes 2011 SSN )

Java Notes for “Programming Languages” and -Comments //… or /*…*/ or /**…*/
“Advanced Programming” -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
Java Source All Uppercase => constants
Across the
Code (.java)
Internet -print and println methods
using
HTML
-command line arguments (main method)
-object oriented programming (classes, objects, inheritance, etc.)
Java
Java Bytecode
Compiler
(.class)
Web Browser //Turkey.java File
class Turkey
{
Java Bytecode Java
Interpreter Compiler
public static void main(String[] args)
Interpreter
{
System.out.print("The international "
(Applet) + "dialing code ");
Machine System.out.print("for Turkey is " + 90);
Code (.exe) }
}
//FrstProg.java file
//NameTag.java File
class FrstProg
class NameTag
{
{
/*This program just writes something to the console
public static void main(String[] args)
and will stop executing*/
{
public static void main(String[] args)
System.out.println("Hello! My name is " +
{
args[0]);
System.out.println("This is the first lesson");
}
//println is part of API
}
}
}
javac NameTag.java (compile)
HOW TO COMPILE AND RUN JAVA FILES: java NameTag XXX (run)
Hello! My name is XXX (output)
Java Compiler:
javac FrstProg.java (creates FrstProg.class) To import a package:
Java Interpreter:
java FrstProg (executes FrstProg.class) import package.class;
Or:
Output: import package.*;
This is the first lesson
-2- (Java Notes 2011 SSN )
JAVA API (Application Programming Interface) OPERATORS:
Unary: + -
View: http://java.sun.com/j2se/1.3/docs/api/ Binary: * / % Multiplication, division, remainder
Download: http://java.sun.com/j2se/1.3/docs.html + - Addition, subtraction
+ String concatenation
= Assignment
Packages += -= *= /= %=
java.applet creates programs (applets) that are easily transported across
the web. count++ return count and then add 1
java.awt (Abstract Windowing Toolkit) Draw graphics and create ++count add 1 and then return count
graphical user interfaces. count-- return count and then subtract 1
java.io perform a wide variety of I/O functions. --count subtract 1 and then return count
java.lang general support. It is automatically imported.
java.math for high precision calculations. ! Logical not ^ Bitwise xor == !=
java.net communicate across a network. && Logical and & Bitwise and > <
java.rmi (Remote Method Invocation) create programs that can be || Logical or | Bitwise or >= <=
distributed across multiple computers.
java.sql interact with databases.
java.text format text for output. CODITIONS AND LOOPS:
java.util general utilities. condition ? expression1 : expression2
example: int larger = (num1>num2) ? num1 : num2 ;

PRIMITIVE DATA TYPES:


byte 8 bits -128 127 if (condition) switch (expression) {
short 16 bits -32768 32767 Statement1 case value1:
int 32 bits -2 billion 2 billion else Statement-list1; break;
long 64 bits -1019 1019 Statement2 case value2:
Statement-list2; break;
Floating point: ….
float 32 bits default:
double 64 bits Statement-list3;
}
Others:
char 16 bits 65536 Unicode characters while (condition) do Statement for (init; cond; incr)
boolean false true Statement; while (condition); Statement;
void
continue break return

WRAPPER CLASSES:
Classes declared in package java.lang:
Byte Float Character Boolean Void
Short Double
Integer
Long
-3- (Java Notes 2011 SSN )
INSTANTIATION AND REFERENCES GARBAGE COLLECTION

class CarExample 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()
public static void main(String[] args) method.
{ Calling the gc() method suggests that the Java Virtual Machine expend effort toward
int total = 25; recycling unused objects in order to make the memory they currently occupy
int average; available
average = 20; 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.
//CarClass should be declared
CarClass myCar = new CarClass();
CarClass yourCar;
yourCar = new CarClass(); If we add the line:
//To call a method use "." CarClass momCar = myCar;
myCar.speed(50);
yourCar.speed(80);
we get the following drawing:
System.out.println("My car cost $" + myCar.cost());
}
}

class CarClass _speed = 50 _speed = 80


{ myCar yourCar
int _speed;
int _cost;

CarClass() 2 1
{
_speed = 0;
_cost = 2500;
}

public void speed(int speed)


{ To reduce the number of references to an object,
_speed = speed; We do the following:
}
MyCar = null;
public int cost()
{ (What would happen in C++ if we do this???)
return _cost;
}
}
-4- (Java Notes 2011 SSN )
STRINGS: OUTPUT:

class StringExample str1: Seize the day Index of 'e' in str4: 9


{ str2: Char at pos 3 in str1: z
public static void main (String[] args) str3: Seize the day Substring 6 to 8 of str1: th
{ str4: Day of the str1 and str5 refer to the same object
String str1 = "Seize the day";
seize str1 and str3 don't refer to the same
String str2 = new String();
String str3 = new String(str1); str5: Seize the day object
String str4 = "Day of the seize"; str1 and str3 contain the same chars
String str5 = "Seize the day"; length of str1 is 13
System.out.println("str1: " + str1); length of str2 is 0 str2 now is: SEIZE THE DAY
System.out.println("str2: " + str2); str5 is now: SXizX thX day
System.out.println("str3: " + str3); str1 and str5 don't refer to the same object
System.out.println("str4: " + str4);
System.out.println("str5: " + str5);
System.out.println();
System.out.println("length of str1 is " + str1.length()); Useful methods for string:
System.out.println("length of str2 is " + str2.length()); length() :returns the length
System.out.println(); charAt (int index) :returns char at that positions (0..)
System.out.println("Index of 'e' in str4: " indexOf(char ch) :returns index (0..) of first occurrence
+ str4.indexOf('e')); lastindexOf(char ch) :returns index (0..) of last occurrence
System.out.println("Char at pos 3 in str1: "
+ str1.charAt(3));
endsWith(String suffix) :returns true if has this suffix
System.out.println("Substring 6 to 8 of str1: " startsWith(String prefix) :returns true if has this prefix
+ str1.substring(6,8)); equals(Object obj) :returns true if two strings are the same
if (str1==str5) equalsIgnoreCase(Object obj) :returns true if two strings are equal, ignoring case
System.out.println("str1 and str5 refer to the “ toLowerCase() :returns a new string of lower case
+ “same object"); toUpperCase() :returns a new string of upper case
if (str1 != str3) substring(int begin, int end) :returns a new string that is a substring of this string
System.out.println("str1 and str3 don't refer to “ including begin, excluding end.
+ “the same object");
if (str1.equals(str3))
System.out.println("str1 and str3 contain the “ java.lang.StringBuffer.
+ ”same chars");
System.out.println(); StringBuffer- implements a mutable sequence of characters.
str2 = str1.toUpperCase(); String - implements a constant sequence of characters.
System.out.println("str2 now is: " + str2);
str5 = str1.replace('e','X');
System.out.println("str5 is now: " + str5); public class ReverseString{
public static void main(String[] args){
//now check again String source="abcdefg";
if (str1==str5) int strLen=source.length();
System.out.println("str1 and str5 refer to the “ StringBuffer dest = new StringBuffer( strLen );
+ “same object"); for( int i= strLen-1; i>=0; i--){
else System.out.println("str1 and str5 don't refer to “ dest.append( source.charAt(i) );
+ “the same object"); }
} System.out.println( dest );
} }
}

output: gfedcba
-5- (Java Notes 2011 SSN )
ARRAYS: MULTI DIMENSIONAL ARRAYS:

class ArrayTest class MultiArray


{ {
public static void main(String[] args) int[][] table = {{1,2,3,4},
{ {11,12},
ArrayParameters test = new ArrayParameters();
//first way to initialize array with fixed size and data
{21,22,23}};
int[] list = {11,22,33,44,55};
//second way to initialize array. Fixed size. public void init1()
int[] list2 = new int[5]; //default for int is 0... {
//fill in data table = new int[5][];
for (int i=0; i<list.length; i++) for (int i=0; i<table.length; i++)
{ {
list2[i]=99; table[i] = new int[i];
} }
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 public void print()
list=test.retRef(list2); //list: 99 66 99 99 99 {
} for (int rows=0; rows<table.length; rows++)
} {
for (int col=0; col<table[rows].length;
class ArrayParameters col++)
{ System.out.print(table[rows][col] + " ");
public void passElement(int num)
{
//move cursor to next line
num = 1234; //no change in original System.out.println();
} }
public void chngElems(int[] my1) //reference passed }
{
my1[2] = 77; public static void main(String[] args)
my1[4] = 88; {
} MultiArray ma = new MultiArray();
public void chngRef(int[] my1, int[] my2) //reference passed ma.print();
{
my1 = my2;
ma.init1();
} ma.print();
public void copyArr(int[] my1, int[] my2) }
{ }
for (int i=0; i<my2.length; i++)
my1[i]=my2[i]; OUTPUT:
} 1234
public int[] retRef(int[] my1) 11 12
{
21 22 23
my1[1] = 66;
return my1;
} 0
} 00
000
0000
-6- (Java Notes 2011 SSN )
INPUT/OUTPUT: “Numbers.dat” file
1.1
import java.io.*; 2.2
class Greetings
3.3
{ 4.4
public static void main (String[] args) 10.5
{
try
{ javac Sum.java
DataInputStream in = new DataInputStream(System.in); java Sum
System.out.println("What is your name?"); How many numbers: 5
String name = in.readLine(); The total is 21.5
System.out.println("Hello " + name);
}
catch (IOException e) //This program does not use deprecated methods
{ import java.io.*;
System.out.println("Exception: " + e.getMessage());
} class MyTest
} {
} BufferedReader reader = null;

public void read()


What is your name? {
Bill Gates try
Hello Bill Gates {
reader = new BufferedReader (new FileReader
import java.io.*; ("numbers.dat"));
}
class Sum catch (FileNotFoundException f)//if file was not found
{ {
public static void main (String[] args) System.out.println("File was not found");
{ System.exit(0);
try }
{
DataInputStream in = new DataInputStream(System.in); try
DataInputStream fin = new DataInputStream(new {
FileInputStream(“numbers.dat”)); String line= new String();
int count; double sum = 0.0;
double total = 0; while((line=reader.readLine())!=null)
System.out.print(“How many numbers? “); {
System.out.flush(); double d = Double.parseDouble(line);
count = Integer.parseInt(in.readLine()); sum += d;
for (int i=1; i<=count; i++) }
{ System.out.println("Sum is " + sum);
Double number = Double.valueOf(fin.readLine()); }
total += number.doubleValue(); catch (Exception e)
} {
System.out.println(“The total is: “ + total); System.out.println("Exception occurred");
} }
catch (IOException e) }
{
System.out.println(“Exception while performing “ public static void main(String[] args)
+ e.getMessage()); {
} MyTest test = new MyTest();
} test.read();
} }
}
-7- (Java Notes 2011 SSN )

Class java.io.File java.util.StringTokenizer

import java.io.*; import java.io.*;


import java.util.StringTokenizer;
public class BuildDir
{ public class Tokens
public static void main(String[] args) throws IOException {
{ public static void main(String[] args) throws IOException
File from = new File("source.txt"); {
File newDir = new File("newDir"); BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
File to = new File("newDir/target.txt"); int first,second,pitaron;
int i;
newDir.mkdir(); char sign;
String line;
FileReader in = new FileReader( from ); do
FileWriter out = new FileWriter( to ); {
System.out.println("Enter the exercise with =.");
int character; line = in.readLine();
while( (character=in.read())!= -1 ) StringTokenizer st=new StringTokenizer(line);
{ first=Integer.parseInt( st.nextToken("-+*/") );
out.write(character); sign = ( st.nextToken("1234567890") ).charAt(0);
} second= Integer.parseInt( st.nextToken("=") );
switch(sign)
in.close(); {
out.close(); case '+': pitaron= first+second; break;
case '-': pitaron= first-second; break;
from.delete(); case '*': pitaron= first*second; break;
} case '/': pitaron= first/second; break;
} default : pitaron =0;
}
Useful methods of File System.out.println(line + pitaron);
}
getAbsoulutePath() – return string. Absoulute path of the file. while( pitaron != 0);
}
canRead(),canWrite()-return boolean .app can read/write to file. }
IsFile(), isDirectory()- return boolean.
output:
list()- return string[]. The list of the files in the directory.
Enter the exercise with =.
12-33=
mkDir() – return boolean. Creat a directory.
12-33=-21
renameTo(File des) –return boolean. Renames the file name to the
StringTokenizer(st1,delim)- construct a StringTokenizer for st1. delim= the delimiters.
Des pathname.
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.
-8- (Java Notes 2011 SSN )

Class RandomAccessFile
Example:

+--java.io.RandomAccessFile
java.io.RandomAccessFile import java.io.*;

public class RandomAccessFile public class CopyTwoToOne


extends Object {
public static void main(String[] args) throws IOException
implements DataOutput, DataInput {
Instances of this class support both reading and writing to a random access file. A random RandomAccessFile in1;
RandomAccessFile in2;
access file behaves like a large array of bytes stored in the file system. There is a kind of RandomAccessFile out;
cursor, or index into the implied array, called the file pointer; input operations read bytes
in1=new RandomAccessFile("source1.txt","r");
starting at the file pointer and advance the file pointer past the bytes read. If the random out=new RandomAccessFile("target.txt","rw");
access file is created in read/write mode, then output operations are also available; output
byte[] con = new byte[(int)in1.length()];
operations write bytes starting at the file pointer and advance the file pointer past the bytes in1.readFully(con);
out.write(con);
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 in1.close();
out.close();
method.
in2=new RandomAccessFile("source2.txt","r");
It is generally true of all the reading routines in this class that if end-of-file is reached before out=new RandomAccessFile("target.txt","rw");
the desired number of bytes has been read, an EOFException (which is a kind of out.seek( out.length() );
IOException) is thrown. If any byte cannot be read for any reason other than end-of-file, an
con = new byte[(int)in2.length()];
IOException other than EOFException is thrown. In particular, an IOException may be thrown in2.readFully(con);
if the stream has been closed. out.write(con);

Since: out.writeUTF("end");
JDK1.0
in2.close();
out.close();
Constructor Summary }
}
RandomAccessFile(File file, String mode) Useful methods
Creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
readByte() / writeByte() seek(long pos)- set the file pointer offset.
readInt() / writeInt() length()- Return the length of the file.
RandomAccessFile(String name, String mode)
readDouble() / writeDouble() skipBytes(int n)
Creates a random access file stream to read from, and optionally to write to, a file readBoolean() /writeBoolean()
with the specified name.
-9- (Java Notes 2011 SSN )
EXCEPTION HANDLING:
public static void main (String[] args)
import java.io.*; {
import java.util.*; System.out.println("This is the Java IO Example");
IO test = new IO();
class IO DataInputStream file = null;
{ try
private String line; {
private StringTokenizer tokenizer; file = new DataInputStream(new
FileInputStream(“books.txt”));
public void newline(DataInputStream in) throws IOException }
{ catch (FileNotFoundException fnfe)
line = in.readLine(); {
if (line == null) System.out.println(“Could not find file. “
throw new EOFException(); + “Please place books.txt in main directory”);
tokenizer = new StringTokenizer(line); }
} try
{
public String readString(DataInputStream in) throws IOException while (true)
{ {
if (tokenizer == null) System.out.println(“Type: “ + test.readString(file));
newline(in); System.out.println(“Name: “ + test.readString(file));
while (true) System.out.println(“Cost1: “ + test.readDouble(file));
System.out.println(“Cost2: “ + test.readDouble(file));
{ }
try }
{ catch (EOFException exception)
return tokenizer.nextToken(); {
} //just exit the program
catch (NoSuchElementException exception) }
{ catch (IOException exception)
newline(in); {
} System.out.println(“Exception occurred: “
} + exception.getMessage());
}
}
public double readDouble(DataInputStream in) throws IOException finally
{ {
if (tokenizer == null) System.out.println(“This Line is printed anyhow.”);
newline(in); }
while (true) }
{ }
try
{
String str = tokenizer.nextToken();
return Double.valueOf(str.trim()).doubleValue();
}
catch (NoSuchElementException exception)
{
newline(in);
}
}
}
- 10 - (Java Notes 2011 SSN )
class PrivateCar extends Car
INHERITANCE: {
final int LEATHER = 1;
class Car final int STANDARD = 0;
{ float engine;
boolean auto; int seats = LEATHER;
int price;
int maxSpeed = 120; PrivateCar()
{
Car() auto = false;
{ price = 150000;
auto = true; }
price = 100000;
} PrivateCar(float engine, int seats)
{
Car (boolean auto, int price) super(); //must be first command
{ this.engine = engine;
this.auto = auto; this.seats = seats;
this.price = price; super.speed(100);
} }

Car (int speed) public void speed(int max)


{ {
this(); //must be first command maxSpeed = max*2;
maxSpeed = speed; }
}
public static void main(String[] args)
public void speed (int max) {
{ PrivateCar a = new PrivateCar();
maxSpeed = max; a.speed(100);
} if (a instanceof PrivateCar)
System.out.println("a is a PrivateCar");
public int cost() }
{ }
return price;
}

public static void main(String[] args) protected- class is accessible jast for it’s subclasses and package members.
{ public - class is publicly accessible.
Car a = new Car(); abstract - class can’t be instantiated.
Car b = new Car(true, 120000); final - class can’t be subclassed.
b.speed(80);
int c = b.cost();
}
}
- 11 - (Java Notes 2011 SSN )
INTERFACES:
class AmericanDisk extends IsraelDisk
interface ProductsInterface {
{ public double m_DollarRate;
public String getName();
public int getAvailableCount(); public AmericanDisk(String name,
public String getKind(); int avail, double cost, double rate)
public double getCost(); {
} super(name, avail, cost);
m_DollarRate = rate;
class Book implements ProductsInterface }
{
public String m_Name; public String getKind() {return super.getKind() +"[A]";}
public int m_Available; public double getCost() {return m_Cost * m_DollarRate;}
public double m_Cost; }

public Book(String name, int avail, double cost) class Inherit


{ {
m_Name = name; public static void main(String[] args)
m_Available = avail; {
m_Cost = cost; ProductsInterface[] arr = new ProductsInterface[3];
} arr[0] = new Book("My Michael - Amos Oz", 10, 56.50);
arr[1] = new IsraelDisk("Moon - Shlomo Artzi", 5,
public String getName() {return m_Name; } 87.90);
public int getAvailableCount() {return m_Available; } arr[2] = new AmericanDisk("Frozen - Madonna",
public String getKind() {return "Book";} 17, 21.23, 4.25);
public double getCost() {return m_Cost;}
} System.out.println("Kind \t\t Name \t\t\t Available “
+ ”\t\t Cost");
class IsraelDisk implements ProductsInterface for (int i=0; i<arr.length; i++)
{ {
public String m_Name; System.out.print(arr[i].getKind() + "\t\t");
public int m_Available; System.out.print(arr[i].getName() + "\t\t");
public double m_Cost; System.out.print(arr[i].getAvailableCount()+
"\t\t");
public IsraelDisk(String name, int avail, double cost) System.out.println(arr[i].getCost());
{ }
m_Name = name; }
m_Available = avail; }
m_Cost = cost;
}
OUTPUT:
public String getName() {return m_Name; } Kind Name Available Cost
public int getAvailableCount() {return m_Available; } Book My Michael - Amos Oz 10 56.5
public String getKind() {return "Disk";}
Disk Moon - Shlomo Artzi 5 87.9
public double getCost() {return m_Cost;}
} Disk[A] Frozen - Madonna 17 90.2275