link to intellimation

Intellimation - Your Gateway to Intelligent Information
DD3 Java Examples

Index of Examples

Art
Birds
Butterflies
Books
Cats
China
Countries
Cosmetology
Education
English Studies
Flight & Space
France
Gifts
Health

Hebrew
Historical Events
Holocaust
Iraq
Ireland

Israel

Italy
Japan
Japanese
>>>Java
Jewish, Judaism
Law
Love Lyrics
Love Poems
Musicology
Nature
New York
People
Photography
Professions
Spain
Weather

(1) The Valentine Shop:

link to Valentine Shop #1

(2) The Rainbow Valentine Shop:

Click Here for Rainbow Valenine Shop

Link to the Irish Shop

Search With Google

go shopping

Advertise on our site - learn how to
Contact us at iidesune@netvision.net.il
(ExY1)
DD1
   EM1    Y1   Y1b    EM-Phonebook  
DD2    EM2     Y2   Yv_Examples
DD3    EM3     Y3    
DD4    EM4     Y4
DD5    EM5     Y5

****  Index of Examples
****  Back to Java Cheat
ASDF
//collections - class exercise  Linked List?
//collections - class exercise
class Main
{
    public static void main(String args[]) {
        PhoneBook pb = new PhoneBook();
        Person p1 = new Person("aaaa", "aaaa", "03-0000000");
        Person p2 = new Person("aaaa", "bbbb", "03-0000000");
        Person p3 = new Person("aaaa", "bbbb", "03-1111111");
        pb.add(p1);
        pb.add(p2);
        pb.add(p3);
       
        pb.print();


        // public final static int byFirstName =1;
        // public final static int byPhone =2;
        // public final static int byLastName = 3
        pb.printSorted(SortBy.FIRST_NAME);
        pb.printSorted(SortBy.LAST_NAME);
        pb.printSorted(SortBy.PHONE);
    }
};



Comparator
//collections - class exercise
import java.util.Comparator;
class OtherPersonComparator implements Comparator
{
    private SortBy m_SortingMode;
    OtherPersonComparator(SortBy nSortedMode)
    {
        m_SortingMode = nSortedMode;
    }

    public int compare(Object o1, Object o2)
    {
        Person p1 = (Person)o1;
        Person p2 = (Person)o2;
        if (m_SortingMode == SortBy.FIRST_NAME)
            return p1.m_firstName.compareTo(p2.m_firstName);
        if (m_SortingMode == SortBy.LAST_NAME)
            return p1.m_lastName.compareTo(p2.m_lastName);
        if (m_SortingMode == SortBy.PHONE)
            return p1.m_phoneNum.compareTo(p2.m_phoneNum);
        throw new RuntimeException("Something is strange here");
    }
}


Person
//collections - class exercise

class Person
{
    String m_firstName;
    String m_lastName;
    String m_phoneNum;

    Person () {
    }

    Person(String first, String last, String phone){
        m_firstName = first;
        m_lastName = last;
        m_phoneNum = phone;
    }
    public String toString() {
        return ("First Name: " + m_firstName + " Last Name: " + m_lastName + " Phone#: " + m_phoneNum + "\n");
    }
    public boolean equals(Object o) {
        if ((!(o instanceof Person)))
            return false;

        Person p = (Person) o;
       
        return (m_firstName.equals(p.m_firstName) &&
            m_lastName.equals(p.m_lastName) &&
            m_phoneNum.equals(p.m_phoneNum) );
    }
    public int hashCode() {
        return (3*m_firstName.hashCode()) + (5 * m_lastName.hashCode()) + (7 * m_phoneNum.hashCode());
    }


};


Comparator, Comparable
//collections - class exercise
import java.util.*;   // for the collections

class PersonComperator extends Person implements Comparator , Comparable
{

    public final static int byFirstName =1;
    public final static int byPhone =2;
    public final static int byLastName = 3;

    public static int m_CompareBy = byLastName; // default
   
    // Would have been done nicer if we knew reflection at this stage.
    PersonComperator(Person copiedObj) {
        m_firstName = copiedObj.m_firstName;
        m_lastName = copiedObj.m_lastName;
        m_phoneNum = copiedObj.m_phoneNum;
    }
   
   

    public static void setCompareBy(int by) {
        m_CompareBy = by;
    }
    public static int getCompareBy() {
        return m_CompareBy;
    }
    // Implementing the Comperator interface
    // Compare, Returns a negative integer, zero, or a positive integer:
    // as the first argument is less than,
    // equal to, or greater than the second.

    public int compare(Object element1, Object element2)
    {
        //System.out.println("In PersonComperator compare");
       
        Person p1 = (Person) element1;
        Person p2 = (Person) element2;

        switch (m_CompareBy)
        {
        case byFirstName :
            return (p1.m_firstName.compareTo(p2.m_firstName));
           
        case byLastName:
            return (p1.m_lastName.compareTo(p2.m_lastName));
           
        case byPhone:
            return (p1.m_phoneNum.compareTo(p2.m_phoneNum));
        default:
            return 0;
   
        }

    }

    // implrmrnting Comperable
    public int compareTo(Object other) {
        return compare(this, other);
    }
    public boolean equals(Object obj) {
        //System.out.println("In PersonComperator equals");
        Person p = (Person) this;
        return (p.equals(obj));
    }

    public String toString() {
        switch (m_CompareBy)
        {
        case byFirstName :
            return ("First Name: " + m_firstName + " Last Name: " + m_lastName + " Phone#: " + m_phoneNum + "\n");
           
        case byLastName:
            return ("Last Name: " + m_lastName + " First Name: " + m_firstName +  " Phone#: " + m_phoneNum + "\n");
           
        case byPhone:
            return ("Phone#: " + m_phoneNum + " First Name: " + m_firstName + " Last Name: " + m_lastName + "\n" );
        default:
            return "";
   
        }
   
    }
};


Phonebook  hashset List ArrayList
//collections - class exercise

import java.util.*;   // for the collections

class PhoneBook
{
    List m_hashset;

    PhoneBook () {
        m_hashset = new ArrayList();
    }


    // Phone book interface according to the requirements
    public boolean add(Person object) {
        //if (!( object instanceof Person))
        //    return;
//        PersonComperator personComperator = new PersonComperator((Person)object);
        return m_hashset.add(object);
    }
    public void print() {
        System.out.println("In Regular Print");

        System.out.println(m_hashset); // each set member will know how
                                        // to print itself
        /*
        Iterator iter = m_hashset.iterator();
        while(iter.hasNext())
            System.out.print(iter.next());
        */
   
    }
    public void printSorted(SortBy whichField) {

        System.out.println("In Sorted Print, sorted by" + whichField);
//        PersonComperator.setCompareBy(whatBy);
        OtherPersonComparator comparator =
                        new OtherPersonComparator(whichField);
//        TreeSet set = new TreeSet(comparator);
//        set.addAll(m_hashset);
        Collections.sort(m_hashset, comparator);
       
//        TreeSet tset = new TreeSet(m_hashset);
        System.out.println(m_hashset);
    }
};



Sortby
//collections - class exercise

class SortBy
{
    private String m_sDesc;
    public String toString() { return m_sDesc; }
    private SortBy(String sDesc) { m_sDesc = sDesc;}
    public static final SortBy FIRST_NAME = new SortBy("Sorting by first name");
    public static final SortBy LAST_NAME = new SortBy("last name");
    public static final SortBy PHONE = new SortBy("phone");
};

//dir list  Iterator Time (current.Time.Millis
// dir list

import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;


class Ex1
{
    public static void main(String args[])
    {

        List l = new ArrayList();
        for (int i = 0 ; i < 1000000 ; ++i )
        {
            l.add("This is a string");
        }
        System.out.println("Start Iteration");
        long lStart = System.currentTimeMillis();
        Iterator iter = l.iterator();
        //while(iter.hasNext())
        //    iter.next();//returns the object
        int nSize = l.size();
        for (int i = 0 ; i < nSize ; ++i)
        {
            l.get(i);
        }
        long lEnd = System.currentTimeMillis();
        System.out.println(lEnd - lStart);

    }
};


dir map
TreeMap
//dir map

import java.util.*;

class Main
{
    public static void main(String args[])
    {
        TreeMap map = new TreeMap ();
        map.put("David", new Person("david", "sdff", "1233454"));
        map.put("David1", new Person("david", "sdff", "1233454"));
        map.put("David2", new Person("david", "sdff", "1233454"));
        map.put("David", new Person("dav333id", "sdff", "1233454"));
        map.put("David4", new Person("david", "sdff", "1233454"));

        //show all keys.
        Set keySet = map.keySet();
        Iterator iter = keySet.iterator();
        print(iter);

        //Show all values
        Collection col = map.values();
        iter = col.iterator();
        print(iter);

        //Itetrate through entry set
        Set entryset = map.entrySet();
        iter = entryset.iterator();
        while(iter.hasNext())
        {
            Map.Entry entry = (Map.Entry)iter.next();
            System.out.println(entry.getKey() + " --> "
                                        + entry.getValue());
        }
    }

    private static void print(Iterator iter)
    {
        while(iter.hasNext())
            System.out.println(iter.next());
    }
}


//dir map




////dir map

class Person
{
    String m_firstName;
    String m_lastName;
    String m_phoneNum;


    Person(String first, String last, String phone){
        m_firstName = first;
        m_lastName = last;
        m_phoneNum = phone;
    }
    public String toString() {
        return ("First Name: " + m_firstName + " Last Name: " + m_lastName + " Phone#: " + m_phoneNum + "\n");
    }
    public boolean equals(Object o) {
        if ((!(o instanceof Person)))
            return false;

        Person p = (Person) o;
       
        return (m_firstName.equals(p.m_firstName) &&
            m_lastName.equals(p.m_lastName) &&
            m_phoneNum.equals(p.m_phoneNum) );
    }
    public int hashCode() {
        return (3*m_firstName.hashCode()) + (5 * m_lastName.hashCode()) + (7 * m_phoneNum.hashCode());
    }
};

dir collections/set
iterator  set
//dir collections/set

import java.util.*;
class Ex1
{
    public static void main(String args[])
    {
        Set s = new HashSet();
        for (int i = 0 ; i < args.length ;++i )
            s.add(new Person(args[i]));

        Iterator iter = s.iterator();
        while(iter.hasNext())
        {
            Object o = iter.next();
            System.out.println(o); //--> inside println --> o.toString();
        }
    }
};


//dir collections/set

class Person
{
    private String m_sName;

    Person(String sName)
    {
        m_sName = sName;
    }

    public boolean equals(Object o)
    {
        System.out.println("In Equals");
        if (!(o instanceof Person))
            return false;
        return m_sName.equals(((Person)o).m_sName);
    }

    public int hashCode()
    {
        System.out.println("In Person's Hashcode");
        return m_sName.hashCode();
    }

    public String toString()
    {
        return m_sName;
    }
};

//dir collections/set/ex2
Comparator
//dir collections/set/ex2
import java.util.*;
class Ex1
{
    public static void main(String args[])
    {
        //Set s = new TreeSet();
        Set s = new TreeSet(new PersonComparator());
        for (int i = 0 ; i < args.length ;++i )
            s.add(new Person(args[i]));

        Iterator iter = s.iterator();
        while(iter.hasNext())
        {
            Object o = iter.next();
            System.out.println(o); //--> inside println --> o.toString();
        }
    }
};


Comparable
//dir collections/set/ex2

class Person implements Comparable
{
    private String m_sName;

    Person(String sName)
    {
        m_sName = sName;
    }

    public int compareTo(Object other)
    {
        System.out.println("On CompareTo");
        Person p = (Person)other; //Can throw an exception if other is not Person
        return m_sName.compareTo(p.m_sName);
    }

    public boolean equals(Object o)
    {
        System.out.println("In Equals");
        if (!(o instanceof Person))
            return false;
        return m_sName.equals(((Person)o).m_sName);
    }

    public int hashCode()
    {
        System.out.println("In Person's Hashcode");
        return m_sName.hashCode();
    }

    public String toString()
    {
        return m_sName;
    }
};


Comparator2
//dir collections/set/ex2

import java.util.Comparator;

class PersonComparator implements Comparator
{
    public int compare(Object o1, Object o2)
    {
        Person p1 = (Person)o1;
        Person p2 = (Person)o2;
        return p2.compareTo(p1); //return age differecnes etc.
    }
};

dir ... root (day 3 didi)
a
//dir ... root (day 3 didi)
class Person
{
    String m_sName;
    String m_sPhone;
    void setPhoneNumber(String phone)
    {
        m_sPhone = phone;
    }

    void setName(String name)
    {
        m_sName = name;
    }

    void print()
    {
        System.out.println("Name = " + m_sName +
                            " Phone = " + m_sPhone);
    }
};

a
a
//dir ... root (day 3 didi)
class PhoneBook
{
    Person arr[] = new Person[100];
    //Dim arr as Person(100)
    int nNumOfPersons = 0;

    void addPerson(Person p) //param0 -> this (PhoneBook), Person p
    {
        if (nNumOfPersons < arr.length)
        {
            arr[nNumOfPersons++] = p;
        }
    }

    void print()
    {
        System.out.println("Num of persons in book = "
            + nNumOfPersons);
        for (int i = 0 ; i < nNumOfPersons ; ++i )
        {
            Person personToPrint = arr[i];
            personToPrint.print();
            //arr[i].print();
        }
    }
};

a
a
//dir ... root (day 3 didi)

class PhoneBook
{
    Person arr[] = new Person[100];
    //Dim arr as Person(100)
    int nNumOfPersons = 0;

    void addPerson(Person p) //param0 -> this (PhoneBook), Person p
    {
        if (nNumOfPersons < arr.length)
        {
            arr[nNumOfPersons++] = p;
        }
    }

    void print()
    {
        System.out.println("Num of persons in book = "
            + nNumOfPersons);
        for (int i = 0 ; i < nNumOfPersons ; ++i )
        {
            Person personToPrint = arr[i];
            personToPrint.print();
            //arr[i].print();
        }
    }
};
a
a
//dir ... root (day 3 didi)
class Test
{
    public static void main(String args[])
    {
        int arr[] = new int[Integer.MAX_VALUE / 1000];
    }
};

a
a
//dir ... root (day 3 didi)
class Ex2
{
    public static void main(String args[])
    {
        /*
        int i = 0;
        int j = 33;
        boolean b = true;
        long l = 3l;
        double d = 2.3;
        float f = 2.3f;
        System.out.println(j);
        */
        int nUserVal = Integer.parseInt(args[0]);
        nUserVal += 10;
        System.out.println("will print 10 times");
    for (int i = 0 ; i < 9 ; i = i + 1)
        System.out.println(nUserVal);
    }
};


String methods
//dir ... root (day 3 didi)
class Ex3
{
    public static void main(String args[])
    {
        String s1 = "Hello";
        String s2 = " World".toUpperCase();
        String s3 = s1 + s2;
        //String s4 = s1;
        //s4 += s2;
        String s4 = s3;
        s4 += s4;
        s4 = s4.toUpperCase();
        s4 = s4.trim();
        s4 = s4.subString(2);
        System.out.println(s4);
    }
};

a
a
//dir ... root (day 3 didi)

class Ex4
{
    public static void main(String args[])
    {
        String s = "";
        for (int i = 0 ; i < 100000 ; ++i)
        {
            s += i;
        }
    }
};

/***

Method void main(java.lang.String[])
   0 ldc #2 <String "">
   2 astore_1
   3 iconst_0
   4 istore_2
   5 goto 30
   8 new #3 <Class java.lang.StringBuffer>
  11 dup
  12 invokespecial #4 <Method java.lang.StringBuffer()>
  15 aload_1
  16 invokevirtual #5 <Method java.lang.StringBuffer append(java.
  19 iload_2
  20 invokevirtual #6 <Method java.lang.StringBuffer append(int)>
  23 invokevirtual #7 <Method java.lang.String toString()>
  26 astore_1
  27 iinc 2 1
  30 iload_2
  31 ldc #8 <Integer 100000>
  33 if_icmplt 8
  36 return
*/

StringBuffer
//dir ... root (day 3 didi)

class Ex4Improved
{
    public static void main(String args[])
    {
        StringBuffer s = new StringBuffer();
        for (int i = 0 ; i < 100000 ; ++i)
        {
            s.append(i);
        }
        String s2 = s.toString();
    }
}
/***
Method void main(java.lang.String[])
   0 new #2 <Class java.lang.StringBuffer>
   3 dup
   4 invokespecial #3 <Method java.lang.StringBuffer()>
   7 astore_1
   8 iconst_0
   9 istore_2
  10 goto 22
  13 aload_1
  14 iload_2
  15 invokevirtual #4 <Method java.lang.StringBuffer append(int)>
  18 pop
  19 iinc 2 1
  22 iload_2
  23 ldc #5 <Integer 100000>
  25 if_icmplt 13
  28 aload_1
  29 invokevirtual #6 <Method java.lang.String toString()>
  32 astore_3
  33 return
 */
a
a
//dir ... root (day 3 didi)
class Ex5
{
    public static void main(String args[])
    {
        int arr[];
        arr = new int[3];
        int temp[] = new int[6];
        for (int i = 0 ; i < 3  ;  ++i)
        {
            temp[i] = arr[i];
        }
        arr = temp;
        byte b[] = new byte[1024];

    }
};

a
Getting Arguments from Command Line  or  Command Line Arguments
//dir ... root (day 3 didi)
class Ex6
{
    public static void main(String args[])
    {
        for (int i = 0 ; i < args.length ; ++i )
        {
            System.out.println(args[i]);
        }
    }
};


If Statement
//dir ... root (day 3 didi)
class IfStatement
{
    public static void main(String args[])
    {
        int i = args.length;
        if (i > 0)
        {
            System.out.println(args[0]);
        }
    }
};


Thread.sleep
//dir ... root (day 3 didi)
class Main
{
    public static void main(String args[]) throws InterruptedException
    {
        System.out.println("Hello Java");
        Thread.sleep(10000);
        System.out.println("Done");
    }
};



Add any number of numbers from commandline
//dir ... root (day 3 didi)

class AddFourNumbers {
/*

int[]  sArray = { 1,2,3,4};
int total = 0;
total = sArray[1]+ sArray[2] + sArray[3] + sArray[4];
System.out.println(total);
*/
/////////////////////////
    public static void main(String[] args)
    {
        int Sum = 0;
        for (int i = 0 ; i < args.length ; i = i + 1)
        {
            int NextVal = Integer.parseInt(args[i]);
            Sum = Sum + NextVal; //Sum += NextVal;
        }
        System.out.println(Sum);
    }
}




a
a
//dir ... root (day 3 didi)


aa
//dir ... root (day 3 didi)


a
a
//dir ... root (day 3 didi)


a


























Warning and Disclaimer

We try here to provide simple, non-professional advice and links to sites that seem to be trustworthy for more details.
This is no substitute for qualified medical advice.

Always consult a qualified medical practioner to confirm any self diagnosis and rule out other causes. Always consult a qualified medical practioner regarding medical problems or questions.

This site takes no responsibility for any loss or claim arising from the use or misuse of information/"advice"  on the site or information or advice on linked sites, nor from the failure of any reader to seek or take medical, psychological, legal or any other professionally qualified advice. This warning/disclaimer applies to every page of this website, whether it appears there or not.