08/11/2017
Advanced topics
admin admin

Enumerations

Enumerations was added to Java language in JDK5. Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is publicstatic and final by default. Even though enumeration defines a class type and have constructors, you do not instantiate an enum using new. Enumeration variables are used and declared in much a same way as you do a primitive variable.


How to Define and Use an Enumeration

  1. An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject variable, with different subjects in the list.
    enum Subject           //Enumeration defined
    {
     Java, Cpp, C, Dbms
    }
    

  2. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public, static and final by default.
  3. Variables of Enumeration can be defined directly without any new keyword.
    Subject sub;
    

  4. Variables of Enumeration type can have only enumeration constants as value. We define an enum variable as enum_variable = enum_type.enum_constant;
    sub = Subject.Java;
    
  5. Two enumeration constants can be compared for equality by using the = = relational operator.

    Example:

    if(sub == Subject.Java) {
       ...
    }

Example of Enumeration

enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }

class Test
{
 public static void main(String args[])
 {
  WeekDays wk; //wk is an enumeration variable of type WeekDays
  wk = WeekDays.sun; //wk can be assigned only the constants defined under enum type Weekdays
  System.out.println("Today is "+wk);
 }
}

Output :

 
Today is sun

Example of Enumeration using switch statement

enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
r = Restaurants.paninos;
switch(r) { //The name of the enumertion constants are used without their enumeration
type name i.e only r, not Restaurants.r
case dominos: //only constants defined under enum Restaurants can be used
System.out.println("I AM " + r.dominos);
break;
case kfc:
System.out.println("I AM " + r.kfc);
break;
case pizzahut:
System.out.println("I AM " + r.pizzahut);
break;
case paninos:
System.out.println("I AM " + r.paninos);
break;
case burgerking:
System.out.println("I AM " + r.burgerking);
break;
}
}
}

Output:

I AM paninos

Values( ) and ValueOf( ) method

All the enumerations predefined methods values() and valueOf()values() method returns an array of enum-type containing all the enumeration constants in it. Its general form is,

public static enum-type[ ] values() 

valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as argument while calling this method. It's general form is,

public static enum-type valueOf (String str)

Example of enumeration using values() and valueOf() methods:

enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
System.out.println("All constants of enum type Restaurants are:");
Restaurants  rArray[] = Restaurants.values(); //returns an array of constants of type Restaurants
for(Restaurants  a : rArray) //using foreach loop
System.out.println(a);

r = Restaurants.valueOf("dominos");
System.out.println("I AM " + r);
}
}

Output:

All constants of enum type Restaurants are:
dominos
kfc
pizzahut
paninos
burgerking
I AM dominos

Points to remember about Enumerations

  1. Enumerations are of class type, and have all the capabilities that a Java class has.
  2. Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces.
  3. Enumerations are not instantiated using new keyword.
  4. All Enumerations by default inherit java.lang.Enum class.

Enumeration with Constructor, instance variable and Method

enum Student
{
 John(11), Bella(10), Sam(13), Viraaj(9);
 private int age;                   //variable defined in enum Student
 int getage { return age; }  //method defined in enum Student
 public Student(int age)  //constructor defined in enum Student
 {
  this.age= age;
 }
}

class EnumDemo
{
 public static void main( String args[] )
 {
  Student S;
  System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
 }
}

Output :

Age of Viraaj is 9 years

In this example as soon as we declare an enum variable(Student S), the constructor is called once, and it initializes age for every enumeration constant with values specified with them in parenthesis.

type wrapper

Java uses primitive data types such as int, double, float etc. to hold the basic data types for the sake of performance. Despite the performance benefits offered by the primitive data types, there are situations when you will need an object representation of the primitive data type. For example, many data structures in Java operate on objects. So you cannot use primitive data types with those data structures. To handle such type of situations, Java provides type Wrappers which provide classes that encapsulate a primitive type within an object.

  • Character : It encapsulates primitive type char within object.
    Character (char ch)
    
  • Boolean : It encapsulates primitive type boolean within object.
    Boolean (boolean boolValue)
    
  • Numeric type wrappers : It is the most commonly used type wrapper.
    ByteShortIntegerLongFloatDouble

    Above mentioned Classes comes under Numeric type wrapper. These classes encapsulate byte, short, int, long, float, double primitive type.


Autoboxing and Unboxing

  • Autoboxing and Unboxing features was added in Java5.
  • Autoboxing is a process by which primitive type is automatically encapsulated(boxed) into its equivalent type wrapper
  • Auto-Unboxing is a process by which the value of an object is automatically extracted from a type Wrapper class.


Example of Autoboxing and Unboxing

class Test
{
 public static void main(String[] args)
 {
  Integer iob = 100; //Auto-boxing of int i.e converting primitive data type int to a Wrapper class Integer
  int i = iob;   //Auto-unboxing of Integer i.e converting Wrapper class Integer to a primitve type int
  System.out.println(i+" "+iob);

  Character cob = 'a';  //Auto-boxing of char i.e converting primitive data type char to a Wrapper class Character
  char ch = cob;  //Auto-unboxing of Character i.e converting Wrapper class Character to a primitive type char
  System.out.println(cob+" "+ch);
 }
}

Output :

100 100
a a

Autoboxing / Unboxing in Expressions

Whenever we use object of Wrapper class in an expression, automatic unboxing and boxing is done by JVM.

Integer iOb;
iOb = 100;        //Autoboxing of int
++iOb;

When we perform increment operation on Integer object, it is first unboxed, then incremented and then again reboxed into Integer type object.

This will happen always, when we will use Wrapper class objects in expressions or conditions etc.


Benefits of Autoboxing / Unboxing

  1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects interchangeably.
  2. We don't have to perform Explicit typecasting.
  3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must be used with care.
  4. Auto-unboxing also allows you to mix different types of numeric objects in an expression. When the values are unboxed, the standard type conversions can be applied.

Example:
class Test {
public static void main(String args[]) {
Integer i = 35;
Double d = 33.3;
d = d + i;
System.out.println("Value of d is " + d);
}
}

Ouput:

Value of d is 68.3

Note: When the statement d = d + i; was executed, i was auto-unboxed into int, d was auto-unboxed into double, addition was performed and then finally, auto-boxing of d was done into Double type Wrapper class.

IO Stream

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical.

Java encapsulates Stream under java.io package. Java defines two types of streams. They are,

  1. Byte Stream : It provides a convenient means for handling input and output of byte.
  2. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.

byte stream classification

These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.


Some important Byte stream classes.

Stream classDescription
BufferedInputStreamUsed for Buffered Input Stream.
BufferedOutputStreamUsed for Buffered Output Stream.
DataInputStreamContains method for reading java standard datatype
DataOutputStreamAn output stream that contain method for writing java standard data type
FileInputStreamInput stream that reads from a file
FileOutputStreamOutput stream that write to a file.
InputStreamAbstract class that describe stream input.
OutputStreamAbstract class that describe stream output.
PrintStreamOutput Stream that contain print() and println() method

These classes define several key methods. Two most important are

  1. read() : reads byte of data.
  2. write() : Writes byte of data.


Character Stream Classes

Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.

character stream classification

These two abstract classes have several concrete classes that handle unicode character.


Some important Charcter stream classes.

Stream classDescription
BufferedReaderHandles buffered input stream.
BufferedWriterHandles buffered output stream.
FileReaderInput stream that reads from file.
FileWriterOutput stream that writes to file.
InputStreamReaderInput stream that translate byte to character
OutputStreamReaderOutput stream that translate character to byte.
PrintWriterOutput Stream that contain print() and println() method.
ReaderAbstract class that define character stream input
WriterAbstract class that define character stream output


Reading Console Input

We use the object of BufferedReader class to take inputs from the keyboard.

BufferedReader class explanation


Reading Characters

read() method is used with BufferedReader object to read characters. As this function returns integer type value has we need to use typecasting to convert it into char type.

int read() throws IOException

Below is a simple example explaining character input.

class CharRead
{
 public static void main( String args[])
 {
  BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
  char c = (char)br.read();       //Reading character  
 }
}

Reading Strings

To read string we have to use readLine() function with BufferedReader class's object.

String readLine() throws IOException

Program to take String input from Keyboard in Java

import java.io.*;
class MyInput
{
 public static void main(String[] args)
 {
  String text;
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  text = br.readLine();          //Reading String  
  System.out.println(text);
 }
}

Program to read from a file using BufferedReader class

import java. Io *;
class ReadTest
{
 public static void main(String[] args)
 {
  try 
  {
   File fl = new File("d:/myfile.txt");
   BufferedReader br = new BufferedReader(new FileReader(fl)) ;
   String str;
   while ((str=br.readLine())!=null)
   {
    System.out.println(str);
   }
   br.close();
   fl.close();
  }
  catch (IOException  e)
  { e.printStackTrace(); }
 }
}

Program to write to a File using FileWriter class

import java. Io *;
class WriteTest
{
 public static void main(String[] args)
 {
  try 
  {
   File fl = new File("d:/myfile.txt");
   String str="Write this string to my file";
   FileWriter fw = new FileWriter(fl) ;
   fw.write(str);
   fw.close();
   fl.close();
  }
  catch (IOException  e)
  { e.printStackTrace(); }
 }
}

Serialization and Deserialization in Java

Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization.

A class must implement Serializable interface present in java.io package in order to serialize its object successfully. Serializable is a marker interface that adds serializable behaviour to the class implementing it.

Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects which include,

  • java.io.serializable
  • java.io.Externalizable
  • ObjectInputStream
  • and ObjectOutputStream etc.


Marker interface

Marker Interface is a special interface in Java without any field and method. Marker interface is used to inform compiler that the class implementing it has some special behaviour or meaning. Some example of Marker interface are,

  • java.io.Serializable
  • java.lang.Cloneable
  • java.rmi.Remote
  • java.util.RandomAccess

All these interfaces does not have any method and field. They only add special behavior to the classes implementing them. However marker interfaces have been deprecated since Java 5, they were replaced by Annotations. Annotations are used in place of Marker Interface that play the exact same role as marker interfaces did before.


Signature of writeObject() and readObject()

writeObject() method of ObjectOutputStream class serializes an object and send it to the output stream.

public final void writeObject(object x) throws IOException

readObject() method of ObjectInputStream class references object out of stream and deserialize it.

public final Object readObject() throws IOException,ClassNotFoundException

while serializing if you do not want any field to be part of object state then declare it either static or transient based on your need and it will not be included during java serialization process.

serialization and deserialization of objects


Serializing an Object

import java.io.*;
class studentinfo implements Serializable 
{
 String name;
 int rid;
 static String contact;
 studentinfo(string n, int r, string c)
 {
  this.name = n;
  this.rid = r;
  this.contact = c;
 }
}

class Test
{
 public static void main(String[] args)
 {
 try
 {
  Studentinfo si = new studentinfo("Abhi", 104, "110044");
  FileOutputStream fos = new FileOutputStream("student.ser");
  Objectoutputstream oos = new ObjectOutputStream(fos);
  oos.writeObject(si);
  oos.close();
  fos.close();
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}

Object of Studentinfo class is serialized using writeObject() method and written to student.ser file.


Deserialization of Object

import java.io * ;
class DeserializationTest
{
 public static void main(String[] args)
 {
  studentinfo si=null ;
  try  
  {
   FileInputStream fis = new FileInputStream("student.ser");
   ObjectOutputStream ois = new ObjectOutputStream(fis);
   si = (studentinfo)ois.readObject();
  } 
  catch (Exception e)
   { e.printStackTrace(); }
  System.out.println(si.name);
  System.out. println(si.rid);
  System.out.println(si.contact);
 }
}

Output :

Abhi
104
null

Contact field is null because,it was marked as static and as we have discussed earlier static fields does not get serialized.

NOTE : Static members are never serialized because they are connected to class not object of class.


transient Keyword

While serializing an object, if we don't want certain data member of the object to be serialized we can mention it transient. transient keyword will prevent that data member from being serialized.

class studentinfo implements Serializable 
{
 String name;
 transient int rid;
 static String contact;
}
  • Making a data member transient will prevent its serialization.
  • In this example rid will not be serialized because it is transient, and contact will also remain unserialized because it is static.
  • Networking in Java

    Java is a premier language for network programming. java.net package encapsulate large number of classes and interface that provides an easy-to use means to access network resources. Here are some important classes and interfaces of java.net package.


    Some Important Classes

    CLASSES
    CacheRequestCookieHandler
    CookieManagerDatagrampacket
    Inet AddressServerSocket
    SocketDatagramSocket
    ProxyURL
    URLConnection

    Some Important Interfaces

    INTERFACES
    CookiePolicyCookieStore
    FileNameMapSocketOption
    InetAddressServerSocket
    SocketImplFactoryProtocolFamily

    InetAddress

    Inet Address encapsulates both numerical IP address and the domain name for that address. Inet address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor. To create an inet Address object, you have to use Factory methods.

    Three commonly used Inet Address factory methods are.

    1. static InetAddress getLocalHost() throws UnknownHostException
    2. static InetAddress getByName (String hostname) throws UnknownHostException
    3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException

    InetAddress subclasses


    Example using InetAddress class

    import java.net.*;
    class Test
    {
     public static void main(String[] args)
     {
      InetAddress address = InetAddress.getLocalHost(); 
      System.out.println(address);
      address = InetAddress.getByName("www.studytonight.com");
      System.out.println(address);
      InetAddress sw[] = InetAddress.getAllByName("www.google.com");
      for(int i=0; i< sw.length; i++)
      {
       System.out.println(sw[i]);
      }
     }
    }
    

    Output:

    Welcome-PC/59.161.87.227
    www.studytonight.com/208.91.198.55
    www.google.com/74.125.236.115
    www.google.com/74.125.236.116
    www.google.com/74.125.236.112
    www.google.com/74.125.236.113
    www.google.com/74.125.236.114
    www.google.com/2404:6800:4009:802:0:0:0:1014
    

    Socket and ServerSocket Class

    Socket is foundation of modern networking, a socket allows single computer to serve many different clients at once. Socket establishes connection through the use of port, which is a numbered socket on a particular machine. Socket communication takes place via a protocol. Socket provides communication mechanism between two computers using TCP. There are two kind of TCP sockets in Java. One is for server and other is for client.

    • ServerSocket is for servers.
    • Socket class is for client.


    URL class

    Java URL Class present in java.net package, deals with URL (Uniform Resource Locator) which uniquely identify or locate resources on internet.

    url defination


    Important Methods of URL class

    • getProtocol() : Returns protocol of URL
    • getHost() : Returns hostname(domain name) of URL
    • getPort() : Returns port number of URL
    • getFile() : Returns filename of URL

    Program using URL class

    import java.net.*;
    class Test
    {
     public static void main(String[] arg) throws MalFormedURLException 
     {
      URL hp = New URL("http://www.studytonight.com/index");
      system.out.println(hp.getProtocol[]); 
      System.out.println(hp.getFile[]);
     }
    }
    

    Ouput:

    http
    -1
    www.studytonight.com 
    /index
    

    Generics

    Generics was first introduced in Java5. Now it is one of the most profound feature of java programming language. Generic programming enables the programmer to create classes,interfaces and methods in which type of data is specified as a parameter. It provides a facility to write an algorithm independent of any specific type of data. Generics also provide type safety. Type safety means ensuring that an operation is being performed on the right type of data before executing that operation.

    Using Generics, it has become possible to create a single class ,interface or method that automatically works with all types of data(Integer, String, Float etc). It has expanded the ability to reuse the code safely and easily.

    Before Generics was introduced, generalized classes,interfaces or methods were created using references of type Object because Object is the super class of all classes in Java, but this way of programming did not ensure type safety.

    Syntax for creating an object of a generic type

    Class_name <data type> reference_name = new Class_name<data type> ();
    OR
    Class_name <data type> reference_name = new Class_name<>();
    

    This is also known as Diamond Notation of creating an object of Generic type.Generic type.


    Example of Generic class

    class Gen <T> //<> brackets indicates that the class is of generic type
    {
    T ob;     //an object of type T is declared
    Gen(T o)  //constructor
    {
      ob = o;
    }
    public T getOb()
    {
      return ob;
    }
    }
    
    class Test
    {
    public static void main (String[] args)
    {
      Gen < Integer> iob = new Gen<>(100);     //instance of Integer type Gen Class.
      int  x = iob.getOb();
      System.out.println(x);
      Gen < String> sob = new Gen<>("Hello");   //instance of String type Gen Class.
      String str = sob.getOb();
      System.out.println(str);
    }
    }   
    

    Output :

    100
    Hello
    

    In the above program, we first passed an Integer type parameter to the Generic class. Then, we passed a String type parameter to the same Generic class. Hence, we reused the same class for two different data types. Thus, Generics helps in code reusability with ease.


    Generics Work Only with Objects

    Generics work only with objects i.e the type argument must be a class type.You cannot use primitive datatypes such as int, char etc. with Generics type. It should always be an object. We can use all the Wrapper Class objects and String class objects as Generic type.datatypes such as int, char etc. with Generics type. It should always be an object. We can use all the Wrapper Class objects and String class objects as Generic type.

    Gen< int> iOb = new Gen< int>(07);    //Error, can't use primitive type
    

    Generics Types of different Type Arguments are never same

    Reference of one generic type is never compatible with other generic type unless their type argument is same. In the example above we created two objects of class Gen, one of type Integer, and other of type String, hence,

    iob = sob;    //Absolutely Wrong
    

    An array of Generic type cannot be created

    Creation of a generic type array is not allowed in Generic programming. We can make a reference of an array, but we cannot instantiate it.

    For example, In the above program, in class Gen,

    T a[]; //this is allowed

    T a[] = new T[10]; //this is not allowed


    Generic Type with more than one parameter

    In Generic parameterized types, we can pass more than 1 data type as parameter. It works the same as with one parameter Generic type.

    class Gen <T1,T2>
    {
    T1 name;
    T2 value;
    
    Gen(T1 o1,T2 o2) 
    {
      name = o1;
      value = o2;
    }
    public T1 getName()
    {
      return name;
    }
    
    public T2 getValue()
    {
      return value;
    }
    
    }
    
    class Test
    {
    public static void main (String[] args)
    {
      Gen < String,Integer> obj = new Gen<>("StudyTonight",1); 
     
      String  s = obj.getName();
      System.out.println(s);
     
      Integer i = obj.getValue();
      System.out.println(i);
    }
    }   
    

    Output:

    StudyTonight
    1
    

    Note: Since there are two parameters in Generic class - T1 and T2, therefore, while creating an instance of this Generic class, we need to mention two data types that needs to be passed as parameter to this class.

    Generic Methods

    You can also create generic methods that can be called with different types of arguments. Based on the type of arguments passed to generic method, the compiler handles each method.

    The syntax for a generic method includes a type-parameter inside angle brackets, and should appear before the method's return type.

    <type-parameter> return_type method_name (parameters) {...}

    Example of Generic method

    class GenTest
    {
     static <b>< V, T></b> void display (V v, T t)
     {
      System.out.println(v.getClass().getName()+" = " +v);
      System.out.println(t.getClass().getName()+" = " +t);
     }
     public static void main(String[] args)
     {
      display(88,"This is string");
     }
    }
    

    Output :

    java lang.Integer = 88
    Java lang.String = This is string 
    

    Generic Constructors

    It is possible to create a generic constructor even if the class is not generic.

    Example of Generic Constructor

    class Gen
    {
     private double val;
     < T extends Number> Gen(T ob)
     {
      val=ob.doubleValue();
     }
     void show()
     {
      System.out.println(val);
     }
    }
    
    class Test
    {
     public static void main(String[] args)
     {
      Gen g = new Gen(100); 
      Gen g1 = new Gen(121.5f);
      g.show();
      g1.show(); 
     }
    }
    

    Output :

    100.0
    121.5 
    

    Generic Interface

    Like classes and methods, you can also create generic interfaces.

    interface MyInterface< T >
    { .. }
    

    Generic Bounded type Parameter

    You can also set restriction on the type that will be allowed to pass to a type-parameter. This is done with the help of extends keyword when specifying the type parameter.

     < T extends Number >

    Here we have taken Number class, it can be any wrapper class name. This specifies that T can be only be replaced by Number class data itself or any of its subclass.


    Generic Method with bounded type Parameters.

    class Gen
    {
     static < T, V extends number> void display(T t, V v)  
     {
      System.out.println(v.getClass().getName()+" = " +v);
      System.out.println(t.getClass().getName()+" = " +t);
     }
     public static void main(String[] args)
     {
     // display(88,"This is string");
      display ("this is string",99); 
     }
    }
    

    Output :

      java.lang.String = This is string 
      java.lang.Double = 99.O
    
    
    • Type V is bounded to Number type and its subclass only.
    • If display(88,"This is string") is uncommented, it will give an error of type incompatibility, as String is not a subclass of Number class.



  • VIA
  • admin
  • TAGS



LEAVE A COMMENT

Facebook Conversations

FOLLOW US