Saturday, October 8, 2016

Homework #1 - Java Basics


Homework #1

Note : Submit Emails to : sdlabuofk@gmail.com  (The Email in the printed Lab Sheet was wrong ! sorry)

Deadline is : 15 OCT 2016 11:59 PM

Part #1 Coding Exercises (7 Marks)

1.  (3 Marks) Write a program that reads in a series of first names and eliminates duplicates by storing them in a Set. Allow the user to search for a first name by implementing a proper function for that 

2.  (4 Marks) (This Exercise is almost solved with below codes given)  The code below Defines an integer stack interface: 

interface IntStack
   {
    void push(int item); // store an item 
    int pop(); // retrieve an item
    }

Create a class called FixedStack that implements IntStack above , FixedStack class has two variables ( tos (index to the current top of stack from type int , and integer array stck as in below ) , Complete the implementation of this class  so it can represent a stack with a fixed size
class FixedStack implements IntStack
{
    private int stck[];     
    private int tos;
    FixedStack(int size)
    {
    /*Add your code here to implement the constructor that   initialize                 both fixed stck array and tos */
    }

    public void push(int item)
    {
 /* Add your code here to implement Push Function that adds an integer   element to the stack (Take in consideration when user trying to add to a full stack */
    }

    public int pop()
    {
 /* Add your code here to implement Pop Function that pops item from stack
(Take in consideration the this is a fixed size stack */
    }
       Then test your class with below code in MAIN as below:

    public static void main(String args[])
    {
        FixedStack mystack1 = new FixedStack(5);
        FixedStack mystack2 = new FixedStack(8);         // push some numbers onto the stack         for(int i=0; i<5; i++) mystack1.push(i);         for(int i=0; i<8; i++) mystack2.push(i);         // pop those numbers off the stack         System.out.println("Stack in mystack1:")         for(int i=0; i<5; i++)
            System.out.println(mystack1.pop());
1


        System.out.println("Stack in mystack2:")         for(int i=0; i<8; i++)
            System.out.println(mystack2.pop());
    }

Part #2 Short Questions (3 Marks)

       What is wrong with the following interface?
public interface SomethingWrongWithThisInterface {
    void aMethod() {
        System.out.println("Hi,You’ve Just called aMethod");
    }
}

       Fix the interface above?
       Is the following interface valid?
public interface Student {
 }

Part #3 BONUS “OPTIONAL” (5 Marks)

One of most known and simple design patterns in industry is the singleton pattern. This design pattern restricts the instantiation of a class to one object , so it’s useful when exactly one object is needed to coordinate actions across the system. Knowing the concept of “static” keyword in java show how can you implement a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. (Write Code Example)
In what Applications do you think that this design pattern suits, why?

Submission Guidelines:
       Subject of Email Should be : Java_HW(No)_(Index)  E.g.  Java_HW1_104048
       Submit Java Files .java for codes and document (.doc,.docx,.pdf) for short questions (As we’re using automatic filters for downloading attachments then answers in email body will not be received so make sure that all your answers are in attachment)
       Bonus must be submitted in Separate file (either .Java or document file )


2

Lab 2 - Java Basics 6-OCT-2016

University of Khartoum
Electrical and Electronic Engineering
Java Lab – 3rd Year – Lab 2 (Java Basics)
The "static" Variables and Methods
  • A static variable/method belongs to the class, and is shared by all instances. Hence, it is also called a class variable/method.
  • On the other hand, a non-static variable/method (absence of keyword static) belongs to a specific instance of a class, also called an instance variable/method.
One usage of static variables/methods to provide a "global" variable, which is applicable to all the instances of that particular class (for purpose such as counting the number of instances, resource locking among instances, and etc.).
"Final" Class/Variable/Method
You can declare a class, a variable or a method to be final.
  • A final class cannot be sub-classed (or extended).
  • A final method cannot be overridden in the subclass.
  • A final variable cannot be re-assigned a new value.
Java interfaces
An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods.
an interface is different from a class in several ways, including:
·         You cannot instantiate an interface.
·         An interface does not contain any constructors.
·         All of the methods in an interface are abstract.
·         An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
·         An interface is not extended by a class; it is implemented by a class.
·         An interface can extend multiple interfaces.
Interfaces have the following properties:
·         An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.
·         Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
·         Methods in an interface are implicitly public.
Example 2:
interface Animal {

   public void eat();
   public void travel();
}

java Collections
A collection is a data structure—actually, an object—that can hold references to other objects. Usually, collections contain references to objects that are all of the same type.
                                                  Some collections-framework interfaces.
   Interface
               Description
Collection
The root interface in the collections hierarchy from which interfaces: Set,
Queue and List are derived.
Set
A collection that does not contain duplicates.
HashSet<String> hset = new HashSet<String>();
hset.add("Apple");

//methods
1.     boolean add(Element  e): It adds the element e to the list.
2.     void clear(): It removes all the elements from the list.
3.     Object clone(): This method returns a shallow copy of the HashSet.
4.     boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
5.     boolean isEmpty(): Returns true if there is no element present in the Set.
6.     int size(): It gives the number of elements of a Set.
7.     .toArray() :convert it to array


List
An ordered collection that can contain duplicate elements.

  (i) Array List

  ArrayList<String> obj = new ArrayList<String>();
obj.add("Ajeet");  //addition
obj.add(1, "Justin");//addition at index
for (String name : obj) ; //advanced loop
Collections.sort(obj); //sort
Collections.sort(obj, Collections.reverseOrder());
ii)iii) Try LinkedList & Vector as home practice



 

Map
A collection that associates keys to values and cannot contain duplicate keys.

  HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");


//loop through elements

    for (Map.Entry me : hmap.entrySet()) {
          System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue());
        }

Example 3:
TRY IT
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class UtilDemo3 {
   public static void main(String[] args) {
      String[] coins = { "A", "B", "C", "D", "E" };
      List l = new ArrayList();
      for (int i = 0; i < coins.length; i++)
         l.add(coins[i]);
      ListIterator liter = l.listIterator();
      System.out.println("Before reversal");
      while (liter.hasNext())
         System.out.println(liter.next());

     /*
  add your code here

     */ }}
Lab Exercises:

1)      Create class of your own with static integer variable to track the number of objects created from this class. And implement a function called printCount() to print the number of objects created.
2)      Declare interface payable that contains public abstract method getPaymentAmount
3)      create class Invoice (implementing interface above) to represent a simple invoice . The class declares private instance variables :partNumber, quantity and pricePerItem. Class Invoice also contains a three arguments  constructor ,toStringmethod that returns a String representation of an Invoice object and implement getPaymentAmount() that calculates total cost.
4)       Update example 3 to reverse the list l and print it after reversion
Homework:
Homework of This week will be uploaded to the blog: http://java-lab013.blogspot.com on           05  (Submit to: sdlabuofk@gmail.com)