Sunday, May 12, 2013

Access specifiers in java

Access specifiers in java :

Access specifiers in java classified into four types for the members. Access specifiers place a very important 

role in real time java applications. While developing the application we are defined the members which are 

visible outside of the class and which should not visible out side of the package. Suppose in some scenarios 

we strictly  hide some of the members which are only visible in side the class and the members which should 

not visible any of the other classes. 

  • Private
  • Default
  • Protected
  • Public
In a same class we can access all the other members of a class directly irrespective of the  access specifiers.

Private access specifier :

The visibility of the private access specifier is only with in the class. we can not access the private access 

specifiers outside of the class.

Example :

public class Test{
  private int value = 10;
}

Public access specifier :

If we declares the members of a class as public, it can be accessible any where. I mean it can be accessible

inside the class, outside the class, outside of the other packages.


Example :

public class Test{
  public int value = 10;
}

Protected access specifier :

If we declares the members of a class as protected, it can be accessible with in the same package 

and sub classes of outside the package. 

Example :

public class Test{
  protected int value = 10;
}

Default access specifier :

If we declares the members of a class as Default, it can be accessible with in the same package 

and sub classes of the same package 

We can not any access specifier for default.

Example :

public class Test{
   int value = 10;
}


Java File Output Stream Example

Java File Output Stream Example

We can write the file content by using File Output Stream .

File Output Stream  writes the stream of raw bytes to the file.

File output Stream writes the data by using the write() method.

File output Stream Example:


 import java.io.File;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
      //write the file content using File OutputStream.  
      public class FileOutputStreamExample {  
            public static void main(String[] args) {  
                 FileOutputStream fos = null;//<i>File Output Stream</i>   
                File fileName = null;  
                 try {  
                      fileName = new File("C:\\core.txt");  
                      fileName.createNewFile();  
                      fos = new FileOutputStream(fileName);  
                      fos.write("Hello Write this content".getBytes());  
                      fos.flush();                       
                } catch (IOException e) {  
                     e.printStackTrace();  
                } finally {  
                     try {  
                          if (fos != null){  
                               fos.close();  
                               fos = null;  
                          }  
                     } catch (IOException ex) {  
                          ex.printStackTrace();  
                     }  
                }  
           }  
      }  



Java File Input Stream Example

Java File Input Stream Example

We can read the files content by using File Input Stream also.

File Input Stream  reads the stream of raw bytes.

File Input Stream reads the data by using the read() method.

File input Stream Example:


 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 //Read the file content using File InputStream.  
 public class FileInputStreamExample {  
       public static void main(String[] args) {  
            FileInputStream fis = null;//<i>File Input Stream</i>   
           File fileName = null;  
            try {  
                 fileName = new File("C:\\core.txt");  
                 fis = new FileInputStream(fileName);  
                 int c;  
                 while ((c = fis.read()) != -1) {  
                     System.out.print((char) c);  
                }  
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (fis != null){  
                          fis.close();  
                          fis = null;  
                     }  
                } catch (IOException ex) {  
                     ex.printStackTrace();  
                }  
           }  
      }  
 }  


Java Constructor Example

Java Constructor Example

In java the Objects are created by using the constructor.

Once we define a class in the java application, automatically the java compiler provides the

default constructor.

We can define parameterized constructors also depends on our requirement.

Example :

 Test test = new Test();
 class Test{
 }

In class Test we haven't defined any constructor, here the java compiler provides the constructor.

//default constructor in class Test
class Test{
  Test(){
 }
}

Constructor name must be same as class name.

//parameterized constructor

class Test{
  Test(int a,int b){
  }
}

Once we write any parameterized constructors in the class, the java compiler does not provide any
default constructor, so if we want default constructor we need explicitly define the default constructor
in the class.

To create an object for a class using parameterized constructor

Example : Test test = new Test(5,6);

Constructor is also similar to java methods, but there are the below differences
  • We must specify the return type for the method definition, where as for constructor there should not be any return type specified.
  • We can give any name for a method, but coming to constructor the constructor name and class name must be same.
 public class ConstructorExample {  
      ConstructorExample(){  
           System.out.println("default constructor");  
      }  
   ConstructorExample(int a){  
        System.out.println("one parameterized constructor "+a);  
      }  
   ConstructorExample(int a ,int b){  
        System.out.println("Two parameterized constructor "+a+ " "+b);  
      }  
      public static void main(String[] args) {  
           ConstructorExample c = new ConstructorExample();  
           ConstructorExample c1 = new ConstructorExample(1);  
           ConstructorExample c2 = new ConstructorExample(1,2);  
      }  
 }  

Output :

default constructor
one parameterized constructor 1
Two parameterized constructor 1 2

Html5 Examples

Html5 Video Example

Html5 Video Example

Html5 Video is very simple to embed video in the web page.

It is very simple, to embed the video in our browser we just use the video tag as shown in

below example.

The controls attribute which adds video controls like volume, play and pause....etc

source tag which will give the link to the video files.

for src attribute , we should give the path of the media files and for type attribute  will give

the media type.

you can change the width and height based on webpage look and feel.

Below you can find very simple Html5 Video example.


 <html>  
 <body>  
 <video width="111" height="111" controls>  
  Video tag does not support yoiur browser.  
  <source src="http://javademos.blogspot.com/java.mp4" type="video/mp4">  
  <source src="http://javademos.blogspot.com/java.mpeg" type="video/mpeg">  
 </video>  
 </body>  
 </html>  

Saturday, May 11, 2013

Java BufferedWriter

Java BufferedWriter 

BufferedWriter is the class which is under the package java.io.

BufferedWriter  Write text to a character-output stream.

We can write characters to the file  by using the  write methods .

Below i am giving the very simple example, which writes the some text content

to the file. if file is there it overwrites the content, if file is not there, it creates one file


Java BufferedWriter  Example


 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileWriter;  
 import java.io.IOException;  
      //Write the content into the file  
      public class Java_BufferedWriterExample {  
            public static void main(String[] args) {  
                 BufferedWriter br = null;  
                FileWriter fr = null;  
                File file = null;  
                try {  
                      file = new File("C:\\core1.txt");  
                      file.createNewFile();  
                      fr = new FileWriter(file);  
                      br = new BufferedWriter(fr);  
                      fr.write("hello");  
                      fr.write("how are you");  
                } catch (IOException e) {  
                     e.printStackTrace();  
                } finally {  
                     try {  
                          if (fr != null){  
                               fr.close();  
                               fr = null;  
                          }  
                          if (br != null){  
                               br.close();  
                               br = null;  
                          }  
                     } catch (IOException ex) {  
                          ex.printStackTrace();  
                     }  
                }  
           }  
      }  


Java BufferedReader

Java BufferedReader Example

BufferedReader is the class which is there in java.io package.

Buffered Reader reads the text from a character-input stream. We will pass the FileReader

as constructor argument to the  Buffered Reader.

BufferedReader reads the file line by line, character, group of characters.

Create one .txt file under C directory.

I am giving below very straight forward example which reads the file content line by line and print

in the console.

While iterating to the file, if the pointer reaches to the end of the file, the readLine() method

which return the null value.

BufferedReader Example



 import java.io.BufferedReader;  
 import java.io.File;  
 import java.io.FileReader;  
 import java.io.IOException;  
 //Read the file using Buffered reader.  
 public class Java_Bufferedreader {  
       public static void main(String[] args) {  
            BufferedReader br = null;  
           FileReader fr = null;  
           File file = null;  
           String line = null;  
            try {  
                 file = new File("C:\\core.txt");  
                 fr = new FileReader(file);  
                 br = new BufferedReader(fr);  
                 while ((line = br.readLine()) != null) {  
                     System.out.println(line);  
                }   
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (fr != null){  
                          fr.close();  
                          fr = null;  
                     }  
                     if (br != null){  
                          br.close();  
                          br = null;  
                     }  
                } catch (IOException ex) {  
                     ex.printStackTrace();  
                }  
           }  
      }  
 }  


Java String

Java String

String class is available under the package java.lang.String.

String class is very important class, we almost use most of the places while developing the applications.

We no need to import this class in our code, automatically this class is available.

String is final class, so the string object can not be modify.

String class is immutable object, that means its contents can not be editable.

There are lot of methods are there to perform string operations like indexOf, concat,charAt...etc

We can create string objects in number of ways.

String str = "Javademos.blogspot";

It is a string constant, it will store in string constant pool.

The other way to create string object is by using new operator.

String str = new String("Javademos.blogspot");

char[] cArray = {'J','A','V','A'};

String str = new String(cArray);

There are many ways we can create string object like passing the byte[] constructor...etc.

We have  number of methods in string class to perform operations on strings.

I am giving the most useful methods which are frequently using in java real time applications.

 public class StringExample {  
      public static void main(String[] args) {  
                String str1 = new String("java");  
                String str2 = new String("j2ee");  
                //equals method Compares string to the specified object.  
                boolean flag = str1.equals(str2);  
                System.out.println("equals .. "+flag);  
                //equalsIgnoreCase method Compares String to another String, ignoring case considerations.  
                flag = str1.equalsIgnoreCase(str2);  
                System.out.println("equalsIgnoreCase .. "+flag);  
                //charAt method gives the character position.  
                int position = str1.charAt(3);  
                System.out.println("charAt .. "+position);  
                //concat the strings  
                String str = str1.concat(str2);  
                System.out.println("concat .. "+str);  
                //replace the characters  
                str = str1.replace('a','b');  
                System.out.println("replace .. "+str);  
                //return the substring  
                str = str1.substring(2);  
                System.out.println("substring .. "+str);  
                //convert all the chars to lower case  
                str = str1.toLowerCase();  
                System.out.println("toLowerCase .. "+str);  
                //convert all the chars to upper case  
                str = str1.toUpperCase();  
                System.out.println("toUpperCase .. "+str);  
                String str4 = " abc ";  
                //with leading and trailing whitespace omitted  
                str = str4.trim();  
                System.out.println("trim .. "+str);  
                //Tests if this string starts with the specified prefix  
                flag = str1.startsWith("j");  
                System.out.println("startsWith .. "+flag);  
                //Tests if this string ends with the specified prefix  
                flag = str1.endsWith("j");  
                System.out.println("endsWith .. "+flag);  
                //length of the string  
                System.out.println("endsWith .. "+str1.length());  
      }  
 }  


OutPut : equals .. false
equalsIgnoreCase .. false
charAt .. 97
concat .. javaj2ee
replace .. jbvb
substring .. va
toLowerCase .. java
toUpperCase .. JAVA
trim .. abc
startsWith .. true
endsWith .. false
endsWith .. 4

There are lot of methods are available you can refer the java string api.

Java static import

java import static

Static import in java is the feature which is available in Java 1.5.

This is the best feature if we want to use in some real time scenarios.

Before java 1.5 if we want to use the static members in another classes/packages

we are using the Classname.MemberName, For Example ClassA.Method();

But With this static import feature, we just define the classname/members starting with

import static pkg.class;
import static pkg.class.memberNames;

In the code we can directly use the static members, if we write static import.
But at the same time we cann't use more static members. in long run the new developer
may gets confused which member is for which class.

static imports in java Example:


 package javademos;  
 public class AppConstants {  
  public static int maxTimeLimit = 1 ;//in hours  
  public static int minTimeLimit = 1 ;//in hours  
 }  


 package javademos;  
 import static javademos.AppConstants.*;  
 // Importing all static members and using directly as shown below.
 public class StaticImport {  
      public static void main(String[] args) {  
           System.out.println("maxTimeLimit "+maxTimeLimit);  
           System.out.println("minTimeLimit "+minTimeLimit);  
      }  
 }  


Linked HashSet Example

LinkedHashSet Example :

LinkedHashSet is the class which is available in java.util package.

The main advantage of LinkedHashSet is, it preserves the order of the elements. I mean while iterating the
LinkedHashSet  the elements are retrieve in the same order how we insert into it.

LinkedHashSet implements the Set interface, it allows the Null values and allows unique elements.

LinkedHashSet  has lot of methods which are very much useful.

LinkedHashSet which extends the java.util.HashSet Class and all the methods which are available in HashSet class are available in the LinkedHashSet class.



 import java.util.Iterator;  
 import java.util.LinkedHashSet;  
      //LinkeHashSetExample Example Java  
      public class LinkeHashSetExample {  
        public static void main(String[] args) {  
          //LinkeHashSetExample, it preserves order of the elements.  
             LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();  
             linkedHashSet.add("Item1");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item4");  
             linkedHashSet.add("Item3");  
             linkedHashSet.add(null);  
             linkedHashSet.add(null);  
          Iterator<String> iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          linkedHashSet.remove("Item2");  
          System.out.println("After removing Item2...");  
          // after removing jsp  
          iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          if (linkedHashSet.contains("Item3")) {  
            System.out.println("Item3 available");  
          }  
        }  
      }  

Output : Item1
Item2
Item4
Item3
null
After removing Item2...
Item1
Item4
Item3
null
Item3 available

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.