Saturday, October 8, 2016

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)

No comments:

Post a Comment