





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
copmutercopmutercopmutercopmuter
Typology: Exercises
1 / 29
This page cannot be seen from the preview
Don't miss anything!
javac NameTag.java (compile) java NameTag XXX (run) Hello! My name is XXX (output)
To import a package:
import package.class; Or: import package.*;
If we add the line:
we get the following drawing:
To reduce the number of references to an object, We do the following:
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: "
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; } }
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
//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"));
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.
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); } }
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.
output:
Enter the exercise with =. 12-33= 12-33=-
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.
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.
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()];
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); } }
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. “
System.out.println(“Exception occurred: “
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; }
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 “
public String getName() {return m_Name; } public int getAvailableCount() {return m_Available; } public String getKind() {return "Disk";} public double getCost() {return m_Cost;} }
Event Source Listener Window WindowListener Button List MenuItem TextField ActionListener Choice Checkbox List ItemListener The keyboabrd (component) KeyListener
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.
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(); } }
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()); }