Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

copmuter copmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmuter, Exercises of Computer Science

copmutercopmutercopmutercopmuter

Typology: Exercises

2018/2019

Uploaded on 11/26/2019

mdv-prasad
mdv-prasad 🇮🇳

2 documents

1 / 29

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
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)
{
-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)
{
- 1 - (Java Notes 2003-4 Bar Ilan University)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download copmuter copmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmutercopmuter and more Exercises Computer Science in PDF only on Docsity!

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)

-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("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

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.

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 >= <=

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)

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:

_speed = speed;

public int cost()

return _cost;

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

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

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) {

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:

for (int i=0; i<my2.length; i++) my1[i]=my2[i]; } public int[] retRef(int[] my1) { my1[1] = 66; return my1; } }

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

“Numbers.dat” file

javac Sum.java

java Sum

How many numbers: 5

The total is 21.

//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.

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.

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

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. “

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

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)

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)

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 “

  • ”\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 Cost

public String getName() {return m_Name; } public int getAvailableCount() {return m_Available; } public String getKind() {return "Disk";} public double getCost() {return m_Cost;} }

Book My Michael - Amos Oz 10 56.

Disk Moon - Shlomo Artzi 5 87.

Disk[A] Frozen - Madonna 17 90.

java.awt.*

Important event sources and their listeners:

Event Source Listener Window WindowListener Button List MenuItem TextField ActionListener Choice Checkbox List ItemListener The keyboabrd (component) KeyListener

Awt Components:

Label -For titles, legends, etc.

Button -Push buttons

TextComponent -Text input (TextField) & display (TextArea)

CheckBox -On/Off or Yes/No checkboxes

ComboBox -Popup choice list, only one choice

List/Choice -Displayed choice list, multiple choices

ScrollBar -Nu, Be’emet…

Usage: < container >.add( );

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 panels

GridLayout -Frame is divided into rows and columns

GridBagLayout -you can divid one row to num’ of columns,( vice versa).

null - lack of layout, the component set by coordinates.

Usage: < container >.setLayout( );

or Example: Panel p = new Panel( new GridLayout(2,2) );

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.

ItemListener

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

setVisible(boolean bool)

FocusListener

import java.awt.*;

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

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] )