Core Java Assignment

Classes and Objects
1. Create class Rectangle
a) data members
– length
– breadth
b) methods
– setDimensions
– area
– perimeter

2. Create class Cube
a) data members
– length
– breadth
– height
b) methods
– setDimensions
– volume

3. Create class Worker
a) data members
– wages
– wdays
b) methods
– setData
– payment

Method Overloading

1. Create class Box
a) data members
– length
– breadth
– height
b) methods
– setDimensions(3 args)
– setDimensions(1 arg)
– volume

Method Returning Value
1. WAP to find total payment of two employeesCreate
Create class Worker
a) data members
– wages
– wdays
b) methods
– setData
– int payment

Constructors
1. Create class Circle and initialize radius using a default constructor
2. Create class Circle and initialize radius using parameterized constructor
3. Create class Circle and define two constructor default and parameterized (Constructor overloading)

Static data members and member functions
1. Create a class Circle and find its area
a) data members
– int radius
– static double pi
b) methods
– area

2. Create a class Bank Account and find interest
a) data members
– int account_number
– int balance
– static double interest_rate
b) methods
– interest (balance * interest_rate * no_of_period / 100.0)
– changeRate (change interest_rate)

OOPS

  1. Design a class Rectangle
    data members:
    length
    breadthmember function / method:
    setDimension()
    area()
    perimeter()
    ——————————————————–
  2. Design a class Worker
    data members:
    wages
    wdaysmember function / method:
    setData()
    payment()
    ——————————————————–
  3. Design a class Box
    data members:
    length
    breadth
    heightmember functions / methods:
    setDimension()
    volume()
    ——————————————————–
  4. Design a class Rectangle
    data members:
    length
    breadth
    member functions / methods:
    setDimension()
    area()
    perimeter()It must overload setDimension() method twice:
    – by passing 1 parameter / argument
    – by passing 2 parameter / argument
    ——————————————————–
  5. Design a class Box
    data members:
    length
    breadth
    height
    member functions / methods:
    volume()It must contain 3 constructors:
    – 1 parameter / argument
    – 2 parameter / argument
    – 3 parameter / argument
    ——————————————————–
  6. Design a class Account
    data members:
    account_number
    balance
    member functions / methods:
    deposit()
    withdraw()
    showBalance()
    ——————————————————–
  7. Design a class Set
    data members:
    3 numbersmember functions / methods:
    SUM()
    MEAN()
    MAX()
    MIN()
    ——————————————————–
  8. Design a class Student
    data members:
    roll_number
    namemember functions / methods:
    setData()
    getData()
    ——————————————————–
  9. Design a class Account
    data members:
    account_number
    balance
    interest_rateinterest_rate must be shared by all objects (static modifier) and its default value 10.25member function:
    interest(no_of_years)
    ——————————————————–
  10. Design a class Student
    data members:
    roll_number
    namemember functions / methods:
    getData()roll_number must be automatically generated.It also keep track of total number of Students.
    ——————————————————–
  11. Design a package MyCircle and MyRectangle
    data members:
    radius
    length
    breadthmember functions / methods:
    area()
    circumference()
    perimeter()
    ——————————————————–
  12. Design a class Studentdata members:
    roll_number
    namemember functions / methods:
    getData()
    showData()Create 5 objects of Student using Array
    ——————————————————–
  13. Design a class Student and List ClassRoom
    add list of Students in ClassRoom
    display List
    ——————————————————–
  14. Design a class Account and List Bank
    add list of Account in Bank
    display List
    ——————————————————–
  15. Create array of Student Objects
    data members:
    roll_no
    name
    collegemember functions / methods:
    readData()
    showData()

Array to CSV in Java

 

package com.demo;

import java.io.IOException;
import com.csvreader.CsvWriter;

public class ArrayToCSVDemo {

  public static void main(String[] args) {
    
    String array[] = {"Suryanagar, Vikhroli", "Java", "SQL", "13"};
    
    try {
      
      CsvWriter writer = new CsvWriter("awesomefile.csv");
      
      writer.writeRecord(array);
      
      writer.close();
      
    } catch (IOException e) {

      e.printStackTrace();
    }
    
  }

}

Reference Link: http://www.journaldev.com/12014/opencsv-csvreader-csvwriter-example

Jar File: http://www.java2s.com/Code/Jar/j/Downloadjavacsvjar.htm

Using FileWriter class

import java.io.FileWriter;

public class TestFileWriter {

  public static String implodeString(String[] split) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < split.length; i++) {			
        sb.append(split[i]);
        if (i != split.length - 1) {
            sb.append("\",\"");
        }
    }
    return "\"" . concat(sb.toString()) .concat("\"");
  }
  
  public static void main(String[] args) {
    
    String array[] = {"Suryanagar, Vikhroli", "Java", "SQL", "13"};
    
    try {
      
      FileWriter fw = new FileWriter("testout.csv");
      //fw.write("\"Suryanagar, Vikhroli\", Java, SQL, 13");
      fw.write(implodeString(array));
      fw.close();
    } catch (Exception e) {
      System.out.println(e);
    }

    System.out.println("Success...");

  }

}

 

 

Apache POI (Poor Obfuscation Implementation File System)

Prerequisite
Download all poi jar files
https://poi.apache.org/download.html


  1.  Terms
    • Workbook – The file contains number of sheets
    • Sheet – Matrix contains rows and cell
    • Row – Record of an entity in one row
    • Cell – A single cell which hold value
  2. JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();){
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();){
                        System.out.println(cit.next());
                    }
                    System.out.println("");
                }
            } else {
                System.out.println("Invalid output");
            }
  3. JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                FileInputStream excelFile = new FileInputStream(fileChooser.getSelectedFile());
                Workbook workbook = new XSSFWorkbook(excelFile);
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();) {
                        System.out.print(cit.next() + "\t" + cit.next());
                    }
                    System.out.println("");
                }
            }
  4.  Workbook workbook = new HSSFWorkbook();
            
            Sheet sheet1 = workbook.createSheet("movies");
    //        Sheet sheet2 = workbook.createSheet("Test Cases");
    //        Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("$*(^&?"));
            
            Row row = sheet1.createRow(0);
            
    //        Cell cell = row.createCell(4);
    //        cell.setCellValue("Hello World");
    //        Cell cell2 = row.createCell(3);
    //        cell2.setCellValue("terminator");
    //        System.out.println(cell.getRichStringCellValue().toString());
    //        System.out.println(cell2.getRichStringCellValue().toString());
    
            Cell cell1 = row.createCell(0);
            Cell cell2 = row.createCell(1);
            Cell cell3 = row.createCell(2);
            Cell cell4 = row.createCell(3);
            Cell cell5 = row.createCell(4);
            
            cell1.setCellValue(5);
            cell2.setCellValue("+");
            cell3.setCellValue(6);
            cell4.setCellValue("=");
            cell5.setCellFormula("A1+C1");
            
            try {
                FileOutputStream outputStream = new FileOutputStream("test1.xlsx");
                workbook.write(outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
  5.  Complete Program
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import javax.swing.JFileChooser;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.util.WorkbookUtil;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    /**
     *
     * @author Shailesh Sonare
     */
    public class ApachePOIDemo {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] shailesh) throws IOException {
            
            /*
            
            Workbook workbook = new HSSFWorkbook();
            
            Sheet sheet1 = workbook.createSheet("movies");
    //        Sheet sheet2 = workbook.createSheet("Test Cases");
    //        Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("$*(^&?"));
            
            Row row = sheet1.createRow(0);
            
    //        Cell cell = row.createCell(4);
    //        cell.setCellValue("Hello World");
    //        Cell cell2 = row.createCell(3);
    //        cell2.setCellValue("terminator");
    //        System.out.println(cell.getRichStringCellValue().toString());
    //        System.out.println(cell2.getRichStringCellValue().toString());
    
            Cell cell1 = row.createCell(0);
            Cell cell2 = row.createCell(1);
            Cell cell3 = row.createCell(2);
            Cell cell4 = row.createCell(3);
            Cell cell5 = row.createCell(4);
            
            cell1.setCellValue(5);
            cell2.setCellValue("+");
            cell3.setCellValue(6);
            cell4.setCellValue("=");
            cell5.setCellFormula("A1+C1");
            
            try {
                FileOutputStream outputStream = new FileOutputStream("test1.xlsx");
                workbook.write(outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            */
            /*
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();){
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();){
                        System.out.println(cit.next());
                    }
                    System.out.println("");
                }
            } else {
                System.out.println("Invalid output");
            }
            */
            
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                FileInputStream excelFile = new FileInputStream(fileChooser.getSelectedFile());
                Workbook workbook = new XSSFWorkbook(excelFile);
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();) {
                        System.out.print(cit.next() + "\t" + cit.next());
                    }
                    System.out.println("");
                }
            }
            
        }    
    }
    

     

     

polymorphism

class A {
    public void test(){
        System.out.println("hello");
    }
    
    public void foo(){
        System.out.println("fooo");
    }
}

class B extends A {
    @Override
    public void test(){
        System.out.println("world");
    }
    public void bar(){
        System.out.println("baar");
    }
}


public class PolymorphismDemo {

    public static void main(String[] args) {
        
        A a = new A();
        a.test(); // allowed: will print hello
        a.foo(); // allowed: will print fooo
        //a.bar(); // not allowed: compile time error
        
        B b = new B();
        b.test(); // allowed: will print world
        b.foo(); // allowed: will print fooo
        b.bar(); // allowed: will print baar
        
        A c = new B();
        c.test(); // allowed: will print world
        c.foo(); // allowed: will print fooo
        //c.bar(); // not allowed: compile time error
        
        //B d = new A(); // not allowed: compile time error
        
        A e = new B();
        A f = (A)e;
        f.test(); // allowed: will print world
        f.foo(); // allowed: will print fooo
        //f.bar(); // not allowed: compile time error
        
        B g = new B();
        A h = (A)g;
        h.test(); // allowed: will print world
        h.foo(); // allowed: will print fooo
        //h.bar(); // not allowed: compile time error
    }    
}

 

Sorting User Defined Collection Using Comparator

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", age=" + age + '}';
    }
}

 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;


/**
 *
 * @author Shailesh Sonare
 */
public class MyCollections {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(0, 5);
        list.add(1, 2);
        list.add(2, 3);
        list.add(3, 8);
        
        Collections.sort(list, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }            
        });
        
        for(Iterator i = list.iterator(); i.hasNext();) {
            System.out.println("" + i.next());
        }
        
        
        Hashtable ht = new Hashtable();
        ht.put(0, "Shailesh Sonare");
        
        HashMap hm = new HashMap();
        hm.put(0, "Mahesh Sonare");
        
        ArrayList<Student> sl = new ArrayList<Student>();
        
        sl.add(new Student("Shailesh", 28));
        sl.add(new Student("Mahesh", 20));
        sl.add(new Student("Shilpa", 22));
        
        Collections.sort(sl, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.age > o2.age) {
                    return 1;
                } else if(o1.age < o2.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        
        for(Iterator i = sl.iterator(); i.hasNext();) {
            System.out.println((Student)i.next());
        }
        
    }
    
}

 

equals and hashcode

equals() method

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

hashCode() method

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

__________________________

A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.
Imagine the following simple example:
On the table in front of you you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.
What you need is a way of instantly deciding which box you have put each object in. It works like an index; you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.
Now imagine that you don’t want to bother with the index, you want to be able to find out immediately from the object which box it lives in.
In the example, let’s use a really simple way of doing this – the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we’ll change our algorithm a little and “wrap round” so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.
Sometimes a box will have more than one object in it, but if you are looking for a rocket, it’s still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas , banjos and rhinoceroses.
That’s a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for generating its own. Lookup the “hashCode” method of Object.