java short notes for new programmer

27
- 1 - (Java Notes 2011 SSN SAN ) Java Notes for “Programming Languages” and “Advanced Programming” //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: -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]); Java Source Code (.java) Java Compiler Java Interpre ter Bytecode Compiler Java Bytecode (.class) Across the Internet using HTML Web Browser (Applet) Java Interpre ter Machine Code (.exe)

Upload: sansayana

Post on 01-Nov-2014

27 views

Category:

Documents


1 download

DESCRIPTION

for new programmer

TRANSCRIPT

Page 1: Java short notes for new programmer

- 1 - (Java Notes 2011 SSN SAN )

Java Notes for “Programming Languages” and “Advanced Programming”

//FrstProg.java fileclass 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 Fileclass Turkey{ public static void main(String[] args) { System.out.print("The international " + "dialing code "); System.out.print("for Turkey is " + 90); }}

//NameTag.java Fileclass 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 Source Code (.java)

Java Compiler

Java Interpreter

Bytecode Compiler

Java Bytecode (.class)

Across the Internet using HTML

Web Browser

(Applet)

Java Interpreter

Machine Code (.exe)

Page 2: Java short notes for new programmer

- 2 - (Java Notes 2011 SSN SAN )

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

Packagesjava.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 127short 16 bits -32768 32767int 32 bits -2 billion 2 billionlong 64 bits -1019 1019

Floating point:float 32 bits double 64 bits

Others:char 16 bits 65536 Unicode charactersboolean false truevoid

WRAPPER CLASSES:Classes declared in package java.lang:Byte Float Character Boolean VoidShort Double IntegerLong

OPERATORS:Unary: + -Binary: * / % Multiplication, division, remainder

+ - Addition, subtraction+ String concatenation = Assignment += -= *= /= %=

count++ return count and then add 1++count add 1 and then return countcount-- 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 : expression2example: 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

Page 3: Java short notes for new programmer

- 3 - (Java Notes 2011 SSN SAN )

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 towardrecycling 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???)

myCar yourCar

_speed = 50 _speed = 80

2 1

Page 4: Java short notes for new programmer

- 4 - (Java Notes 2011 SSN SAN )

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 lengthcharAt (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 occurrenceendsWith(String suffix) :returns true if has this suffixstartsWith(String prefix) :returns true if has this prefix equals(Object obj) :returns true if two strings are the sameequalsIgnoreCase(Object obj) :returns true if two strings are equal, ignoring casetoLowerCase() :returns a new string of lower casetoUpperCase() :returns a new string of upper casesubstring(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

str1: Seize the daystr2:str3: Seize the daystr4: Day of the seizestr5: Seize the day

length of str1 is 13length of str2 is 0

Index of 'e' in str4: 9Char at pos 3 in str1: zSubstring 6 to 8 of str1: thstr1 and str5 refer to the same objectstr1 and str3 don't refer to the same objectstr1 and str3 contain the same chars

str2 now is: SEIZE THE DAYstr5 is now: SXizX thX day

str1 and str5 don't refer to the same object

Page 5: Java short notes for new programmer

- 5 - (Java Notes 2011 SSN SAN )

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 411 1221 22 23

00 00 0 00 0 0 0

Page 6: Java short notes for new programmer

- 6 - (Java Notes 2011 SSN SAN )

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 GatesHello 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()); } }

}

“Numbers.dat” file1.12.23.34.410.5

javac Sum.javajava SumHow many numbers: 5The total is 21.5

//This program does not use deprecated methodsimport 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(); }}

Page 7: Java short notes for new programmer

- 7 - (Java Notes 2011 SSN SAN )

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.

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

Example:

Page 8: Java short notes for new programmer

- 8 - (Java Notes 2011 SSN SAN )

+--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(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; private StringTokenizer tokenizer;

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(); }}Useful methods

readByte() / writeByte() seek(long pos)- set the file pointer offset.readInt() / writeInt() length()- Return the length of the file.readDouble() / writeDouble() skipBytes(int n)readBoolean() /writeBoolean()

public static void main (String[] args){

Page 9: Java short notes for new programmer

- 9 - (Java Notes 2011 SSN SAN ) 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); } } }

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)); } } 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.”); } }

}

Page 10: Java short notes for new programmer

- 10 - (Java Notes 2011 SSN SAN )

INHERITANCE:

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(); }}

class PrivateCar extends Car{ final int LEATHER = 1; final int STANDARD = 0; float engine; int seats = LEATHER; PrivateCar() { auto = false; price = 150000; } PrivateCar(float engine, int seats) { super(); //must be first command this.engine = engine; this.seats = seats; super.speed(100); } public void speed(int max) { maxSpeed = max*2; } public static void main(String[] args) { PrivateCar a = new PrivateCar(); a.speed(100); if (a instanceof PrivateCar) System.out.println("a is a PrivateCar"); }}

protected- class is accessible jast for it’s subclasses and package members.public - class is publicly accessible.abstract - class can’t be instantiated.final - class can’t be subclassed.

Page 11: Java short notes for new programmer

- 11 - (Java Notes 2011 SSN SAN )

INTERFACES:

interface ProductsInterface{ public String getName(); public int getAvailableCount(); public String getKind(); public double getCost();}

class Book implements ProductsInterface{ public String m_Name; public int m_Available; public double m_Cost; public Book(String name, int avail, double cost) { m_Name = name; m_Available = avail; m_Cost = cost; } public String getName() {return m_Name; } public int getAvailableCount() {return m_Available; } public String getKind() {return "Book";} public double getCost() {return m_Cost;} }

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 String getName() {return m_Name; } public int getAvailableCount() {return m_Available; } public String getKind() {return "Disk";} public double getCost() {return m_Cost;} }

class AmericanDisk extends IsraelDisk{ public double m_DollarRate; public AmericanDisk(String name, int avail, double cost, double rate) { super(name, avail, cost); m_DollarRate = rate; } public String getKind() {return super.getKind() +"[A]";} public double getCost() {return m_Cost * m_DollarRate;}}

class Inherit{ public static void main(String[] args) { ProductsInterface[] arr = new ProductsInterface[3]; arr[0] = new Book("My Michael - Amos Oz", 10, 56.50); arr[1] = new IsraelDisk("Moon - Shlomo Artzi", 5, 87.90); arr[2] = new AmericanDisk("Frozen - Madonna", 17, 21.23, 4.25); System.out.println("Kind \t\t Name \t\t\t Available “ + ”\t\t Cost"); for (int i=0; i<arr.length; i++) { System.out.print(arr[i].getKind() + "\t\t"); System.out.print(arr[i].getName() + "\t\t"); System.out.print(arr[i].getAvailableCount()+ "\t\t"); System.out.println(arr[i].getCost()); } }}

OUTPUT:Kind Name Available CostBook My Michael - Amos Oz 10 56.5Disk Moon - Shlomo Artzi 5 87.9Disk[A] Frozen - Madonna 17 90.2275

Page 12: Java short notes for new programmer

- 12 - (Java Notes 2011 SSN SAN )

java.awt.*

Important event sources and their listeners:

Important listener interfaces and their methods:

Awt Components:

Label -For titles, legends, etc.Button -Push buttonsTextComponent -Text input (TextField) & display (TextArea)CheckBox -On/Off or Yes/No checkboxesComboBox -Popup choice list, only one choiceList/Choice -Displayed choice list, multiple choicesScrollBar -Nu, Be’emet……Usage: < container >.add( <components>);Example: Button b=new Button(“press”); Panel.add(b);

Layouts:

BorderLayout -North/South/East/West/Center (def. for Frames)FlowLayout -Normal arrangement (def. for Panels, Applets)CardLayout -Overlapping panelsGridLayout -Frame is divided into rows and columnsGridBagLayout -you can divid one row to num’ of columns,( vice versa).null - lack of layout, the component set by coordinates.…Usage: < container >.setLayout( <Layout>);or Example: Panel p = new Panel( new GridLayout(2,2) );

Check out: http://developer.java.sun.com/developer/technicalArticles/GUI/AWTLayoutMgr/index.h tml

For an example on layouts.

Listener Interface Listener MethodsActionListener actionPerformed(ActionEvent)

FocusListenerfocusGained(FocusEvent)

focusLost(FocusEvent)ItemListener itemStateChanged(ItemEvent)

KeyListenerkeyPressed(KeyEvent)

keyReleased(KeyEvent) keyTyped(KeyEvent)

MouseListener

mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent)

MouseMotionListenermouseDragged(MouseEvent) mouseMoved(MouseEvent)

WindowListener

windowActivated(WindowEvent) windowClosed(WindowEvent) windowClosing(WindowEvent)

windowDeactivated(WindowEvent) windowDeiconified(WindowEvent)

windowIconified(WindowEvent) windowOpened(WindowEvent)

Event Source

Listener( method )

Event

Event Source ListenerWindow WindowListenerButton

ListMenuItemTextField

ActionListener

ChoiceCheckbox

ListItemListener

The keyboabrd(component) KeyListener

Page 13: Java short notes for new programmer

- 13 - (Java Notes 2011 SSN SAN )

ActivatorAWT.java (AWT version)

import java.awt.*;import java.awt.event.*;

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 System.out.println(s + " selected"); } }

other method:

getSource()–return a reference (pointer) to the component that was activated.

Activator.java (Swing version)

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Activator{ public static void main(String[] args) { try { UIManager.setLookAndFeel

("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } JButton b; ActionListener al = new MyActionListener(); JFrame f = new JFrame("Hello Java"); //always add contents to content pane. Never to Frame!!! Container c = f.getContentPane(); c.add(b = new JButton("Hola"), BorderLayout.NORTH); b.setActionCommand("Hello"); b.addActionListener(al); c.add(b=new JButton("Aloha"), BorderLayout.CENTER); b.addActionListener(al); c.add(b = new JButton("Adios"), BorderLayout.SOUTH); b.setActionCommand("Quit"); b.addActionListener(al); f.pack(); f.show(); }}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()

Page 14: Java short notes for new programmer

- 14 - (Java Notes 2011 SSN SAN )

ItemListener

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

for( int i=0; i<4; i++) { c[i]=new Checkbox(labels[i]); add(c[i]); c[i].addItemListener(this); } label=new Label(" chose a checkbox. "); add(label); } public void itemStateChanged(ItemEvent e) { if(e.getSource() == c[3]) label.setText("I am the fourth check box"); else label.setText(e.getItem()+" was changed to "+e.getStateChange()); } public static void main(String[] args) { ItemEvApp app = new ItemEvApp(); app.pack(); app.show(); }}

setVisible(boolean bool)

Focus Listener 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++) { tf[i]=new TextField(); tf[i].addFocusListener(this); add(tf[i]); } } public void focusGained(FocusEvent e) { Object source = e.getSource(); if( source == tf[0] ) tf[0].setText(" I am in focus "); else if( source == tf[1] ) tf[1].setText(" I am in focus "); } public void focusLost(FocusEvent e) { Object source = e.getSource(); if( source == tf[0] ) tf[0].setText(" I lost focus "); 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(); }}

Page 15: Java short notes for new programmer

- 15 - (Java Notes 2011 SSN SAN )

More on Listeners:

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 classpublic class MyClass extends JApplet{ ... someObject.addMouseListener(new MyAdapter()); ... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { ... //Event Handler implementation goes here... } }}

Anonymous inner classes:public class MyClass extends JApplet{ ... someObject.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { ... //Event Handler implementation goes here... } }); ...}

Looks and feels supported by Swing: javax.swing.plaf.metal.MetalLookAndFeel com.sun.java.MotifLookAndFeel com.sun.java.WindowsLookAndFeel

Page 16: Java short notes for new programmer

- 16 - (Java Notes 2011 SSN SAN )

APPLETS

Converting an application to an applet:

1. Change all I/O relevant to the user to awt interface(System.out.println(…) g.drawstring(…))

2. Ensure applet can be stopped by closing the window.3. Import applet package: “import java.applet.*;”4. Extend Applet class instead of Frame class:

class MyApplet extends Applet {…5. main() method is no longer needed (can remain, but should call init())6. Remove “setTitle(-) “ calls.7. Replace the constructor with init()8. New default layout manager is “FlowLayout()”. Change it if needed.9. Replace Frame calls with Applet ones

(dispose becomes destroy, createImage becomes getImage, etc.)10. Replace file I/O with URL I/O or getParameter from HTML base document.11. Create an HTML file that refers to this applet12. Run HTML file through appletviewer or Internet browser.

Applet Methods:

public void init() initialization functionality to the applet prior to the first time the applet is started.

public void start() called after the applet has been initialized (init method), and every time the applet is reloaded in the browser.

public void stop() called by the browser when the containing web page is replaced.

public void destroy() destroys the applet and releases all its resources.

public void paint( Graphics g )

Important notes:1. Make main applet class public!2. Create WWW directory under home directory and move all relevant files into

it. > mkdir WWW

3. Make WWW directory viewable to others.> chmod 755 WWW

4. Make all files under WWW directory viewable to others.> chmod 755 *.class *.gif

5. Make home directory viewable to others and passable.> chmod 755 <login>

Example of an HTML file and Applet

H ello.java

import java.awt.*;import java.applet.*;

public class Hello extends Applet{ Font f; public void init() { String myFont= getParameter("font"); int mySize= Integer.parseInt(getParameter("size")); f=new Font(myFont, Font.BOLD,mySize); } public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); g.drawString("Hello",5,40); } }

Hello.html

<HTML><HEAD><TITLE> Hello world </TITLE></HEAD><BODY><H1> my first applet </H1><APPLET CODE="Hello.class" CODEBASE="c:\myclasses" WIDTH=600 HEIGHT=100><PARAM NAME=font VALUE="TimesRoman"><PARAM NAME=size VALUE="40"> No Java support for APPLET !</APPLET><BODY></HTML>

short: without parameters etc<APPLET CODE="Hello.class" WIDTH=600 HEIGHT=100></APPLET>

archive: reduce time of download.<APPLET code="Hello.class" archive="Hello.jar" width=600 height=100 ></APPLET>

new:<OBJECT CLASSID="java:Hello.class" HEIGHT=600 WIDTH=100></OBJECT>

Page 17: Java short notes for new programmer

- 17 - (Java Notes 2011 SSN SAN )

SoundAndImageApplet

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(); }

public void paint(Graphics g) { g.drawImage(image,0,0,getSize().width,getSize().height,this); } }

SoundAndImageAppletCanvas

import java.applet.*;import java.awt.*;import java.net.*;

public class SoundAndImageAppletCanvas extends Applet{ AudioClip clip; Image image;

public void init() { setLayout( new GridLayout(1,1) );

URL soundURL=null; URL imageURL=null;

try { soundURL = new URL( getCodeBase(),"sound.au" ); imageURL = new URL(getCodeBase(),"img.jpg"); } catch(MalformedURLException e){}

clip = getAudioClip( soundURL); clip.loop(); image = getImage(imageURL); add( new ImageDrawer(image) ); }}

class ImageDrawer extends Canvas{ Image image; public ImageDrawer(Image image) {

this.image = image; }

public void paint(Graphics g) { g.drawImage(image,0,0,getSize().width,getSize().height,this); }}

Page 18: Java short notes for new programmer

- 18 - (Java Notes 2011 SSN SAN )

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: PrimeThread p = new PrimeThread(143); p.start(); The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following:

class PrimeRun implements Runnable { long minPrime; PrimeRun(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: PrimeRun p = new PrimeRun(143); new Thread(p).start();

Example1 :

class SimpleThread extends Thread{ public SimpleThread(String str) { super(str); } public void run() { for (int i=0; i<10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random()*1000)); } catch (InterruptedException e) {} } System.out.println("Done! " + getName()); }}

public class TwoThreadsTest{ public static void main(String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); }}

OUTPUT:0 Jamaica0 Fiji1 Jamaica1 Fiji2 Fiji2 Jamaica3 Jamaica4 Jamaica3 Fiji4 Fiji…8 Fiji8 Jamaica9 FijiDone! Fiji9 JamaicaDone! Jamaica

Page 19: Java short notes for new programmer

- 19 - (Java Notes 2011 SSN SAN )

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

Example3:

import java.awt.*;import java.util.*;

public class ThreadApp extends Frame { int sec=0; Label time; ClockThread runner;

public ThreadApp() { time = new Label(sec+":"); add(time); runner = new ClockThread( time ); runner.start(); pack(); show(); } public static void main( String[] args ) { ThreadApp app=new ThreadApp(); } }

class ClockThread extends Thread{ Label time; int sec;

public ClockThread(Label t) { time = t; }

public void run() { while( true ) { sec++; time.setText(sec+":"); try { Thread.sleep(1000); } catch(InterruptedException e){} } } }

Page 20: Java short notes for new programmer

- 20 - (Java Notes 2011 SSN SAN )

NETWORKING IN JAVASERVER

import java.io.*;import java.net.*;import java.util.*;

public class PrimeServer{ private ServerSocket sSoc; public static final int PORT = 1301; // port out of the range of 1-1024

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."); }}

CLIENT

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

public class PrimeClient { public static final int PORT = 1301;// port out of the range of 1-1024 String hostName; Socket soc; public static void main(String args[]) throws IOException { //replace localhost =>args[0] or with url PrimeClient client = new PrimeClient("localhost"); client.go(); }

public PrimeClient(String hostString) { this.hostName = hostString; }

String readInput() throws IOException { BufferedReader in =new BufferedReader( new InputStreamReader(System.in)); return( in.readLine() ); }

public void go() throws IOException { soc = new Socket(hostName, PORT); BufferedReader ibr = new BufferedReader( new InputStreamReader(

soc.getInputStream()));

PrintWriter pw = new PrintWriter( new OutputStreamWriter(

soc.getOutputStream()),true);

System.out.println("************** Check Prime *************"); System.out.println("Enter a number."); pw.println( readInput() ); System.out.println(ibr.readLine());

ibr.close(); pw.close(); soc.close(); }}

Page 21: Java short notes for new programmer

- 21 - (Java Notes 2011 SSN SAN )