Professional Documents
Culture Documents
Java Notes For Programming Languages and Advanced Programming
Java Notes For Programming Languages and Advanced Programming
(Java Notes 2003-4 Bar Ilan University) -Comments // or /**/ or /***/ Java Notes for Programming Languages and -Blocks {} Advanced Programming
Course URLs: old Course URLs:
Java Source Code (.java)
-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]); } }
Java Compiler
Java Interpreter
Bytecode Compiler
//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 Java Interpreter: java FrstProg Output: This is the first lesson (creates FrstProg.class) (executes FrstProg.class)
javac NameTag.java java NameTag XXX Hello! My name is XXX To import a package: import package.class; Or: import package.*;
-2-
View: http://java.sun.com/j2se/1.3/docs/api/ Download: http://java.sun.com/j2se/1.3/docs.html Packages java.applet java.awt java.io java.lang java.math java.net java.rmi java.sql java.text java.util
creates programs (applets) that are easily transported across the web. (Abstract Windowing Toolkit) Draw graphics and create graphical user interfaces. perform a wide variety of I/O functions. general support. It is automatically imported. for high precision calculations. communicate across a network. (Remote Method Invocation) create programs that can be distributed across multiple computers. interact with databases. format text for output. general utilities.
return count and then add 1 add 1 and then return count return count and then subtract 1 subtract 1 and then return count ^ Bitwise xor & Bitwise and | Bitwise or == > >= != < <=
CODITIONS AND LOOPS: condition ? expression1 : expression2 example: int larger = (num1>num2) ? num1 : num2 ; if (condition) Statement1 else Statement2 switch (expression) { case value1: Statement-list1; break; case value2: Statement-list2; break; . default: Statement-list3; } do Statement while (condition); break for (init; cond; incr) Statement; return
PRIMITIVE DATA TYPES: byte 8 bits -128 short 16 bits -32768 int 32 bits -2 billion long 64 bits -1019 Floating point: float 32 bits double 64 bits Others: char boolean void 16 bits
WRAPPER CLASSES: Classes declared in package java.lang: Byte Float Character Short Double Integer Long
Boolean
Void
-3-
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; } }
_speed = 50
_speed = 80
myCar
2
yourCar
1
-4-
OUTPUT: str1: Seize the day str2: str3: Seize the day str4: Day of the seize str5: Seize the day length of str1 is 13 length of str2 is 0 Index of 'e' in str4: 9 Char at pos 3 in str1: z Substring 6 to 8 of str1: th str1 and str5 refer to the same object str1 and str3 don't refer to the same object str1 and str3 contain the same chars str2 now is: SEIZE THE DAY str5 is now: SXizX thX day str1 and str5 don't refer to the same object
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
-5-
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: 1234 11 12 21 22 23 0 00 000 0000
-6import 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()); } } }
public static void main(String[] args) { MyTest test = new MyTest(); test.read(); } }
-7-
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.
-8-
Since: JDK1.0 Constructor Summary RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) 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;
seek(long pos)- set the file pointer offset. length()- Return the length of the file. skipBytes(int n)
if (tokenizer == null) newline(in); while (true) { try { return tokenizer.nextToken(); } catch (NoSuchElementException exception) { newline(in); } }
public static void main (String[] args) { System.out.println("This is the Java IO Example"); IO test = new IO(); DataInputStream file = null; try { file = new DataInputStream(new FileInputStream(books.txt)); } catch (FileNotFoundException fnfe) { System.out.println(Could not find file. + Please place books.txt in main directory); } try { while (true)
{ System.out.println(Type: + test.readString(file)); System.out.println(Name: + test.readString(file)); System.out.println(Cost1: + test.readDouble(file)); System.out.println(Cost2: + test.readDouble(file));
} }
if (tokenizer == null) newline(in); while (true) { try { String str = tokenizer.nextToken(); return Double.valueOf(str.trim()).doubleValue(); } catch (NoSuchElementException exception) { newline(in); } }
catch (EOFException exception) { //just exit the program } catch (IOException exception) { System.out.println(Exception occurred: + exception.getMessage()); } finally { System.out.println(This Line is printed anyhow.); } } }
- 10 -
class Car { boolean auto; int price; int maxSpeed = 120; Car() { auto = true; price = 100000; } Car (boolean auto, int price) { this.auto = auto; this.price = price; } Car (int speed) { this(); //must be first command maxSpeed = speed; } public void speed (int max) { maxSpeed = max; } public int cost() { return price; } public static void main(String[] args) { Car a = new Car(); Car b = new Car(true, 120000); b.speed(80); int c = b.cost(); } }
protected- class is accessible jast for its subclasses and package members. public - class is publicly accessible. abstract - class cant be instantiated. final - class cant be subclassed.
- 11 interface ProductsInterface { public String getName(); public int getAvailableCount(); public String getKind(); public double getCost(); } class Book { public public public implements ProductsInterface String m_Name; int m_Available; double m_Cost;
public Book(String name, int avail, double cost) { m_Name = name; m_Available = avail; m_Cost = cost; } public public public public } class IsraelDisk implements ProductsInterface { public String m_Name; public int m_Available; public double m_Cost; public IsraelDisk(String name, int avail, double cost) { m_Name = name; m_Available = avail; m_Cost = cost; } public public public public } String getName() {return m_Name; } int getAvailableCount() {return m_Available; } String getKind() {return "Disk";} double getCost() {return m_Cost;} String getName() {return m_Name; } int getAvailableCount() {return m_Available; } String getKind() {return "Book";} double getCost() {return m_Cost;}
OUTPUT: Kind Name Book My Michael - Amos Oz Disk Moon - Shlomo Artzi Disk[A] Frozen - Madonna
Available 10 5 17
Event Source
ItemListener
KeyListener
Listener( method )
MouseListener
MouseMotionListener
WindowListener
public class ActivatorAWT { public static void main(String[] args) { Button b; ActionListener al = new MyActionListener(); Frame f = new Frame("Hello Java"); f.add(b = new Button("Hola"), BorderLayout.NORTH); b.setActionCommand("Hello"); b.addActionListener(al); f.add(b=new Button("Aloha"), BorderLayout.CENTER); b.addActionListener(al); f.add(b = new Button("Adios"), BorderLayout.SOUTH); b.setActionCommand("Quit"); b.addActionListener(al); f.pack(); f.show(); } } class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { //Action Command is not necessarily label String s = e.getActionCommand(); if (s.equals("Quit")) System.exit(0); else if (s.equals("Hello")) System.out.println("Bon Jour"); else } other method: getSource()return a reference (pointer) to the component that was activated.
class MyActionListener looks exactly the same as before Other methods on frames: setTitle(String title) setBackground(Color col) resize(int x, int y) setLayout(LayoutManager manager) hide()
- 14 -
import java.awt.*; import java.awt.event.*; public class ItemEvApp extends Frame implements ItemListener { Checkbox[] c; Label label; GridLayout gl; ItemEvApp() { gl= new GridLayout(3,2); setLayout(gl); c =new Checkbox[4]; String[] labels = { "first","second","third","fourth" };
FocusListener
import java.awt.*; import java.awt.event.*; public class FocusEvApp extends Frame implements FocusListener { TextField[] tf;
public FocusEvApp() { setLayout( new GridLayout(2,1) ); tf = new TextField[2]; for(int i=0; i<2; i++) { for( int i=0; i<4; i++) tf[i]=new TextField(); { tf[i].addFocusListener(this); c[i]=new Checkbox(labels[i]); add(tf[i]); add(c[i]); } c[i].addItemListener(this); } } public void focusGained(FocusEvent e) label=new Label(" chose a checkbox. "); add(label); { } Object source = e.getSource(); public void itemStateChanged(ItemEvent e) if( source == tf[0] ) { tf[0].setText(" I am in focus "); if(e.getSource() == c[3]) else if( source == tf[1] ) label.setText("I am the fourth check box"); tf[1].setText(" I am in focus "); else } label.setText(e.getItem()+" was changed to "+e.getStateChange()); } public void focusLost(FocusEvent e) public static void main(String[] args) { { Object source = e.getSource(); ItemEvApp app = new ItemEvApp(); if( source == tf[0] ) app.pack(); tf[0].setText(" I lost focus "); app.show(); else if( source == tf[1] ) } tf[1].setText(" I lost focus "); } } public static void main(String[] args) { FocusEvApp app = new FocusEvApp(); app.pack(); app.show(); } }
- 15 Implementing an interface:
public class MyClass implements ActionListener { ... someObject.addActionListener(this); ... public void actionPerformed(ActionEvent e) { ... //Event Handler implementation goes here... } }
Using Event Adapters: To use an adapter, you create a subclass of it, instead of directly implementing a listener interface.
/* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class MyClass extends MouseAdapter { ... someObject.addMouseListener(this); ... public void mouseClicked(MouseEvent e) { ... //Event Handler implementation goes here... } }
Inner classes:
//An example of using an inner class public class MyClass extends JApplet { ... someObject.addMouseListener(new MyAdapter()); ... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { ... //Event Handler implementation goes here... } } }
- 17 -
import java.applet.*; import java.awt.*; import java.net.*; public class SoundAndImageApplet extends Applet { AudioClip clip; Image image; public void init() { setLayout( new GridLayout(1,1) ); URL imageURL=null; URL soundURL=null; try { imageURL = new URL( getCodeBase(),"img.jpg" ); soundURL = new URL( getCodeBase(),"sound.au" ); } catch( MalformedURLException e ){} image = getImage(imageURL); clip = getAudioClip( soundURL); clip.loop(); }
class ImageDrawer extends Canvas public void paint(Graphics g) { { Image image; g.drawImage(image,0,0,getSize().width,getSize().height,this); public ImageDrawer(Image image) }
{ }
- 18 THREADS
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows:
class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } }
The following code would then create a thread and start it running:
The following code would then create a thread and start it running:
- 19 Example2:
import java.awt.*; import java.util.*;
public class Clock extends Frame implements Runnable { int sec; Label time; Thread runner; public Clock(int sec) { this.sec=sec; time = new Label(sec+":"); add(time); start(); pack(); show(); } public void start() { if( runner == null ) { runner=new Thread(this); runner.start(); } } public void stop() { runner = null; } public void run() { while( runner != null ) { sec++; repaint(); try { Thread.sleep(1000); } catch(InterruptedException e){} } } public void paint( Graphics g ) { time.setText(sec+":"); } public static void main( String[] args ) { Clock c=new Clock(0); } }
- 20 SERVER
import java.io.*; import java.net.*; import java.util.*; public class PrimeServer { private ServerSocket sSoc; public static final int PORT = 1301;
public static void main(String args[]) throws IOException { PrimeServer server = new PrimeServer(); server.go(); } public void go() throws IOException { Socket soc = null; sSoc = new ServerSocket(PORT); while(true) { soc = sSoc.accept(); // blocks until a connectio occurs PrintWriter pw = new PrintWriter( //creating an OutputStream object new OutputStreamWriter( soc.getOutputStream()),true); BufferedReader br = new BufferedReader( new InputStreamReader( soc.getInputStream())); int num = Integer.parseInt( br.readLine() ); pw.println( prime(num) ); pw.close(); br.close(); soc.close(); } } String prime( int num ) { for(int i=2; i*i<= num; i++) if( num%i==0 ) return(num +" is not a primary number."); return(num +" is a primary number."); } }
} }
- 21 -