Friday, 22 May 2015

Read data from file and sort

A Program to read data from file add it to Collection of object and sort.


file.txt
Ahmed 40
Ali 30

Student.java

package com.ali.fileprogram;

public class Student implements Comparable<Student>{

    private int marks;
    private String name;
   
    public int getMarks() {
        return marks;
    }
   
    public void setMarks(int marks) {
        this.marks = marks;
    }
   
    public String getName() {
        return name;
    }
   
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Student student) {
        // TODO Auto-generated method stub
        int compareMarks = student.getMarks();
       
        //ascending order
        return this.marks - compareMarks;

        //descending order
        //return compareMarks - this.marks;
    }
}



Main.java

package com.ali.fileprogram;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {
       
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>();
        try{
            File file = new File("file.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                students.add(Main.parseLine(scanner.nextLine()));
            }
            scanner.close();
            Collections.sort(students);
            for(Student student : students){
                System.out.println(student.getName() + " : " + student.getMarks());
            }
        }catch(FileNotFoundException exception){
            System.out.println("File Not Found Exception : " + exception);
        }
    }
    public static Student parseLine(String line){
        //use a second Scanner to parse the content of each line
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(" ");
        Student student = new Student();
        if (scanner.hasNext()){
          //assumes the line has a certain structure
            student.setName(scanner.next());
            student.setMarks(Integer.parseInt(scanner.next()));
        }
        scanner.close();
        return student;
    }
}




Result:
Ali : 30
Ahmed : 40

Sunday, 5 January 2014

String & String Buffer

String

         In Java, Strings are immutable objects.

                      String s = new String();

This line of code creates a new object of class String, and assigns it to the reference variable s

s = "abcdef";
This line give the String a value.


String s = new String("abcdef");
More efficient shortcut.


Because you'll use strings all the time, you can even say this
String s = "abcdef";


Now let's say that you want a second reference to the String object referred to by s:
String s2 = s; // refer s2 to the same String as s


So far so good. Now immutability?
Once you have assigned a String a value, that value can never change.


String s = ”abc”;
s = ”xyz”;
Confused!    
String object is immutable, its reference variable is not.



How String objects are immutable?
String s = ”abcde”;
s = s.concat(“ xyz”);

We have 3 String objects here
1. “abcde”
2. “ xyz”
3. “abcde xyz”



Other Example:

String x = "Java";
x.concat(" Rules!");
System.out.println("x = " + x);  


 // the output is
"x = Java"



String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2)

//Output
spring winter  spring summer

What is the output and  how many String objects and how many
reference variables were created?
8 objects and 2 reference variables



Important Facts About Strings and Memory

  • JVM sets aside a special area of memory called the "String constant pool."
  • When the compiler encounters a String literal, it checks the pool to see if an identical String already exists
  • If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created
why making String objects immutable is such a good idea?
If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String's value.


Important Methods in the String Class

  •  charAt() Returns the character located at the specified index
  •  concat() Appends one String to the end of another ( "+" also works)
  •  equalsIgnoreCase()Determines the equality of two Strings, ignoring case
  •  length()Returns the number of characters in a String
  •  replace() Replaces occurrences of a character with a new character
  •  substring()Returns a part of a String
  •  toLowerCase() Returns a String with uppercase characters converted
  •  toString()Returns the value of a String
  •  toUpperCase()Returns a String with lowercase characters converted
  •  trim()Removes whitespace from the ends of a String

 StringBuffer

The java.lang.StringBuffer and java.lang.StringBuilder classes should be used when you have to make a lot of modifications to strings of characters

StringBuffer vs. StringBuilder
  • StringBuilder has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe
  • In other words, its methods are not synchronized
  • StringBuilder will run faster
Using StringBuffer and StringBuilder

StringBuffer sb = new StringBuffer("abc");
sb.append("def");
System.out.println("sb = " + sb);    // output is "sb = abcdef"


Important Methods in the StringBuffer and StringBuilder Classes

public StringBuffer append(String s)
public StringBuffer reverse()
public delete(int start, int end)
public insert(int offset, int i)
replace(int start, int end, String str)

Tuesday, 31 December 2013

Map in Java

Map

public interface Map<KEY,VALUE>


  • A Map is an object that maps keys to values
  • A map cannot contain duplicate keys: Each key can map to at most one value
  • Maps are not collections because they do not implement the Collection interface

 


Map interface includes methods
  • void clear()
  • boolean containsKey(Object k)    
  • boolean containsValue(Object v)
  • Set entrySet()
  • boolean equals(Object obj)
  • Object get(Object k)
  • int hashCode()
  • boolean isEmpty()
  • Set keySet() 
  • Object put(Object k, Object v)
  • void putAll(Map m)
  • Object remove(Object k)
  • int size()
  • Collection values()

SortedMap Interface
  •  Extends Map.
  • It ensures that entries are maintained in ascending key order.

Methods Declared are:
  • Comparator comparetor()
  • Object firstKey()
  • SortedMap headMap(Object end)
  • Object lastKey()
  • SortedMap subMap(Object start, Object end)
  • SortedMap tailMap(Object start) 

The Map.Entry Interface
  • Used to Obtain Collection view of map.
  • EntrySet() of Map interface return a set containing the map entries
 Methods declared in Map.Entry interface
  • Boolean equals(Object obj)
  • Object getKey()
  • Object getValue()
  • Int hashCode()
  • Object setValue(Object v)

The Map Classes

The following are the classes that can be used for Maps
  • AbstractMap           implements Map interface
  • HashMap                extends AbstractMap
  • TreeMap                 extends AbstractMap
  • LinkedHashMap      extends HashMap
  • WeakHashMap        extends AbstractMap
  • IdentityHashMap     extends AbstractMap

AbstractMap class

public abstract class AbstractMap<K,V>
extends Object
implements Map<K,V>
Super class of all concrete map implementatoin

Methods 

void    clear()Removes all of the mappings from this map (optional operation)

protected Object    clone()
Returns a shallow copy of this AbstractMap instance: the keys and values themselves are not cloned.

boolean    containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

boolean    containsValue(Object value)Returns true if this map maps one or more keys to the specified value.

abstract Set<Map.Entry<K,V>>    entrySet()
Returns a Set view of the mappings contained in this map.

boolean    equals(Object o)
Compares the specified object with this map for equality.

V    get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

int    hashCode()
Returns the hash code value for this map.

boolean    isEmpty()
Returns true if this map contains no key-value mappings.

Set<K>    keySet()
Returns a Set view of the keys contained in this map.

V    put(K key, V value)
Associates the specified value with the specified key in this map (optional operation).

void    putAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).

V    remove(Object key)
Removes the mapping for a key from this map if it is present (optional operation).

int    size()
Returns the number of key-value mappings in this map.

String    toString()
Returns a string representation of this map.

Collection<V>    values()
Returns a Collection view of the values contained in this map.



HashMap Class

Constructors
 

HashMap()
 

HashMap(Map m)
 

HashMap(int capacity)
 

HashMap(int capacity, float fillRatio)


  • HashMap extends AbstractMap
  • HashMap does not add any methods of its own
  • HashMap does not guarantee the order of its element


TreeMap Class
  • TreeMap provides efficient means of storing key/value pairs in sorted order.
  • TreeMap guarantees that its elements will be stored in ascending key order
  •  TreeMap implements SortedMap and extends AbstractMap
  • TreeMap does not define any methods of its own

Constructors
 

TreeMap()
 

TreeMap(Comparator comp)
 

TreeMap(Map m)
 

TreeMap(SortedMap sm)



LinkedHashMap Class

Allows insertion order iteration

Constructors
 
LinkedHashMap()


LinkedHashMap(Map m)
 

LinkedHashMap(int capacity)
 

LinkedHashMap(int capacity, float fillRatio)
 

LinkedHashMap(int capacity, float fillRatio, boolean order)



LinkedHashMap adds one method

Protected boolean removeEldestEntry(Map.Entry e)

  • This method is called by put() and putAll()
  • The oldest entry is passed in e
  • By default it retrun false and does nothing
  • If override, then you can have LinkedHashMap remove the oldest entry in the map
  • To remove retrun true
  • To keep return false

WeakHashMap Class

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys

Storing only weak references allows a key-value pair to be garbagecollected when its key is no longer referenced outside of the WeakHashMap


IdentityHashMap Class

This class implements AbstractMap. It is similar to HashMap except that it uses reference equality when comparing elements

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys

Monday, 30 December 2013

Java Calendar Demo

/**
 *
 */
package com;

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * @author Ali
 *
 */
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String months[] = {
                "Jan", "Feb", "Mar", "Apr",
                "May", "Jun", "Jul", "Aug",
                "Sep", "Oct", "Nov", "Dec"};
        Calendar calendar = Calendar.getInstance();
        System.out.println("Calendar Object is as follows:");
        System.out.println(calendar);
        System.out.println("Month : "+calendar.get(Calendar.MONTH));
        System.out.print("Date: ");
        System.out.print(months[calendar.get(Calendar.MONTH)]);
        System.out.print(" " + calendar.get(Calendar.DATE) + " ");
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.print("Time: ");
        System.out.print(calendar.get(Calendar.HOUR) + ":");
        System.out.print(calendar.get(Calendar.MINUTE) + ":");
        System.out.println(calendar.get(Calendar.SECOND));
        // Set the time and date information and display it.
        calendar.set(Calendar.HOUR, 10);
        calendar.set(Calendar.MINUTE, 29);
        calendar.set(Calendar.SECOND, 22);
        System.out.print("Updated time: ");
        System.out.print(calendar.get(Calendar.HOUR) + ":");
        System.out.print(calendar.get(Calendar.MINUTE) + ":");
        System.out.println(calendar.get(Calendar.SECOND));
       
       
        int year;
        System.out.println("Gregorian Calendar");
        GregorianCalendar gcalendar = new GregorianCalendar();
        // Display current time and date information.
        System.out.print("Date: ");
        System.out.print(months[gcalendar.get(Calendar.MONTH)]);
        System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
        System.out.println(year = gcalendar.get(Calendar.YEAR));
        System.out.print("Time: ");
        System.out.print(gcalendar.get(Calendar.HOUR) + ":");
        System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
        System.out.println(gcalendar.get(Calendar.SECOND));
        // Test if the current year is a leap year
        if(gcalendar.isLeapYear(year))
        {
            System.out.println("The current year is a leap year");
        }
        else
        {
            System.out.println("The current year is not a leap year");
        }
    }
}


/*
Output:
Calendar Object is as follows:
java.util.GregorianCalendar[time=1382378159963,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=9,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=21,DAY_OF_YEAR=294,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=11,HOUR_OF_DAY=23,MINUTE=25,SECOND=59,MILLISECOND=963,ZONE_OFFSET=19800000,DST_OFFSET=0]
Month : 9
Date: Oct 21 2013
Time: 11:25:59
Updated time: 10:29:22
Gregorian Calendar
Date: Oct 21 2013
Time: 11:25:59
The current year is not a leap year

*/

Monday, 2 September 2013

Few Known and Unknown Things about Java

Java

Most of the people say Java is an Object Oriented Programming Language.
The fact is Java is an Object Oriented Programming Language but not Completely.

Why?

Because Java Support Primitive types.

We also have Wrapper classes, which are used to represent primitive values when an Object is required.

Something about Abstraction:

In general abstraction means Something that exists only as an idea.

In Computer Science abstraction is the process by which data and programs are defined with a representation similar in form to its meaning (semantics), while hiding away the implementation details

In one word abstraction is nothing but hiding the implementation details.

All Programming Language Provides Abstraction even C language

How and What is it that you are abstracting?

Assembly language is a small abstraction of the underlying machine. Many languages such as FORTRAN, BASIC, and C were abstractions of assembly language.