Friday, February 12, 2016

Final Keyword In Java

The final is a modifier in Java, which can be applied to a variable, a method or a class.When a final modifier is used with a class then the class cannot be extended further. This is one way to protect your class from being subclassed and often sensitive classes are made final due to security reason.
When the final keyword is used with a method that it cannot be overridden in Java, which means you cannot override the logic of the method in the subclass. This is also done to protect the original logic of method.

When the final keyword is used with a variable then its value cannot be changed once assigned. Though this is a little bit tricky to understand especially when you make a reference variable final pointing to array or collection.

For the Static and instance variables no need to perform initialization, JVM Will Provide default initialization.For the local variables compulsory we should perform initialization before using.

Along with lambda expression, streams and a couple of other changes, Java 8 has introduced a new concept called effectively final variable, which allows a non-final variable to be accessed inside an inner class or lambda expression.

Earlier, you cannot access a non-final local variable inside an inner or anonymous class but from Java 8 onwards you can provide it's effectively final i.e. it's value has not changed after assignment.


When you make a class final than all its method effectively become final because a final class cannot be extended and without inheritance, you cannot override them. Some programmers argue that how about overriding final methods in the inner class, well that's not true because even an inner class cannot extend a final class.

Final Instance Variables
For the final instance variables JVM won’t provide any default values, compulsory we should
perform initialization before completion of constructor.

The following are the places to perform this

1) At the time of declaration:.
  
final int i = 0;

2) Inside instance initialization class

Visibility public protected <default> private With in the same classWith in the same package but from out side class.
Outside package but from child class
Outside package but from non-child

class Test
final int i;
{
i = 0;
}

3) Inside constructor

final int i;
test()
{
i = 0;
}
If u r performing initialization any where else we will get compile time error.

Ex:

class Test
{
final int i;
}

Output:- Generates Compile time error, variable “i” might not have been initialized.


Class Test
{
final int i;
public void m1()
{
i=20;
}
}
Output:- Generates Compile time error, can’t assign a value to final variable.

Class Test
{
final int i;
{
i=20;
}
}

Output- Won’t generate compile time error.


Final static Variables

For the final static variables compulsory we should perform initialization.

Ex:

class Test
{
final static int i;
}

Output:-generates Compile time error. variable i might not have been assigned.

We can perform initialization for the final static variables in the following places.

1) At the time of declaration
final static int i = 0;

2) Inside static blocks
static
{
i = 0;
}

3) If u r performing initialization anywhere else we will get compile time error
class Test
{
final static int i;
public static void main(String arg[])
{
i = 20;
}
}

Output:- will produce compile time error.


Final local Variables

Before using a local variable(whether it is final or non-final) we should perform initialization. If we are not using local variable then no need of perform initialization even though it is final.

Ex:
class Test
{
public static void main(String arg[])
{
int i;
System.out.println("hello");
}
}

This is valid Because we didn’t use “i” here.

class Test
{
public static void main(String arg[])
{
final int i;
System.out.println("hello");
}
}
This is also valid because we didn’t use “i” here.

class Test
{
public static void main(String arg[])
{
final int i = 0;
System.out.println("hello");
}
}
This is valid..

class Test
{
public static void main(String arg[])
{
final int i;
System.out.println(i);
}
}
This is not valid. Because Before going to use we didn’t initialize “i”.
The variables which are declared as formal are acts as local variables of the method.
if a formal parameter declared as the final then with in the method we are not allowed to change it’s values.

Ex:

class Test
{
public static void main(String arg[])
{
m1(10,20);
}
public static void m1(final int i,final int j)
{
//i=100;
//j=100;
System.out.println(i+"----"+j);
}
}

If you use final you can’t change i, j values.
Final parameter ‘i’ may not be assigned.

For the local variables the only applicable modifier is final.

Ex:
class Test
{
public static void main(String arg[])
{
private int i = 20;
System.out.println(i);
}
}
Output:

 Provides compile time error because we declare int as private.


Also Read post: Java User Defined Exception with example

Thursday, February 11, 2016

Java Programs On Collections and Arrays

In this Post we will discuss Java Programs on Collections and Arrays.These programs are frequently asked in interviews and written test as well.I already posted 
Arrays in java with example. 

Program 1: How to sort elements of Array

import java.util.Arrays;
import java.util.Comparator;
class ArraysSortDemo
{
public static void main(String args[])
{
int [] a={10,5,20,11,6};

System.out.println("primitive array before sorting:");
for(int a1:a)
{
System.out.println(a1);
}
Arrays.sort(a);
System.out.prinltn("primitive array after sorting");
for(int a1:a)
{
System.out.println(a1);
}
String[] s={"A","Z","B"};
System.out.println("object array before sorting");
for(String a2:s)
{
System.out.println(a2);
}
Arrays.sort(s);
System.out.println("object array after sorting");
for(String a1:s)
{
System.out.println(a1);
}
Arrays.sort(s,new MyComparator());
System.out.println("object array after sorting by comparator:");
for(String a1:s)
{
System.out.println(a1);
}
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}
}

Output:




Program 2: How To Search Elements of List

import java.util.*;
class CollectionSearchDemo
{
public static void main(String [] args)
{
ArraysList al=new ArrayList();
al.add("apple");
al.add("mango");
al.add("banana");
al.add("grape");
System.out.println(al);
//Collections.sort(al);
System.out.println(al);
System.out.println(Collections.birnarySearch(al,"apple"));
System.out.println(Collections.birnarySearch(al,"mango"));
}
}

Output:




Program 3: How to Reverse Elements of List

import java.util.*;
class CollectionReverseDemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(15);
al.add(0);
al.add(45);
al.add(10);
System.out.println(al);
Collections.reverse(al);
System.out.println(al);
}
}

Output:




Program 4:  How to View Array in List Form

import java.util.*;
class ArraysAsListDemo
{
public static void main(String args[])
{
String[] s={"A","Z","B"};
List l= Arrays.asList(s);//[A,Z,B]
s[0]="k";
System.out.println(l);//[K,Z,B]
l.set(1,"L");
for(String s1:s)
System.out.println(s1);//K,L,B
//l.add("lucky"); UnSupportedOperationException
//l.remove(2);     UnSupportedOperationException
}
}

Output:


Sunday, February 7, 2016

UNIX COMMANDS TUTORIAL

Introduction:
In this post I am introducing UNIX Commands 
for UNIX Beginners who need details of commands
that are likely to be of to use them. UNIX is a 
Computer Operating System.This OS has backbone
of the Internet especially for large servers.This is
a free version of UNIX called as linux . This linux
has most popular OS which is used by major software
organisations for good performance.Unix was developed
around in 1969 at AT & T  labs by Dennis Ritche and 
ken Thompson.why unix has rapidly growing in the
 industry means it has the capability to take activities
 from multiple user at the same time. 


Here are the some essential commands in order to get start with UNIX.

CD: change directory
It is used to change from one  directory to another

Ex: 
cd lucky

Here will change the directory from current to lucky directory. 
ls

When ever you  log in your current working directory  is home directory. so to find out list of all files in your home directory you need to write this command.

Ex: 
% ls

 ls -a 

This command is used when you want show list of all  files whose names begin with a dot in current directory.

Ex:

% ls -a

Note:  Here -a is an option. option changes the behavior of command.


ls -l

This command is used to list of all the file names,permissions etc.. in long format.


mkdir

This command is used to create new directory.suppose you have home directory,In that home directory you can create sub directory(new directory) to place all your list of files.

Ex:

% mkdir lucky (here we create new directory with name lucky)

To see all your content in the lucky directory which command you will used?

Ans:  % ls (Got it )




pwd(print working directory)

This command is used  to find out to absolute path name of your home directory.

EX:

% pwd

The full path name will look like this:

/home/programs/core/lucky

cp(copy)

This command is used to copy a file,if you want copy old file in your a current directory file named as new file.

cp oldfile newfile

I will give example how to copy file, I have a directory named as lucky then write

% cd  ~/lucky

Then your write immediately on unix prompt,

% cp examples/core/books.txt .

NOTE: At the end you must specify .  that means your current directory

 Mv:(move)

This command is used to move files from one directory to another directory.It can also be used rename a file,by moving the file to  the same directory,but giving different names.

mv oldfile newfile

This command will rename oldfile to newfile


rm(remove),rmdir(remove directory):

This command is used to delete(remove)a file.

suppose you have file named with  books.txt then you to write the command like this

% rm books.txt(here delete file named with books.txt)


If we want create directory we use mkdir command ,to delete directory we use rmdir.

Ex:
% rmdir lucky


Note: make sure  the directory is empty before deleting directory

clear:

This command is used to clear the terminal window of previous commands before you start next section.

Ex:

% clear

 cat(concatenate)

This command is used to display the contents of the files on the screen.
Suppose if you want to see books.txt file content, then you have to type like this

% cat books.txt


 head

This command is used to see first 10 lines of a file on the screen.Before checking this command clear the screen first then check it.

Ex:  % head books.txt


 tail

This command is used to writes the last ten lines of a file to the screen.

Ex:  % tail books.txt

Grep

This command is used to search files for specified words or patterns.

% grep  java books.txt 

In above command grep has printed out each line containing the word java

grep is case sensitive; so be careful about it since Java and java is difference.

Wc(word count)

This command is used to count the words in your file.

Ex:

% wc -w  books.txt


To find home many lines the file has,then type

% wc -l books.txt


sort

This command is used to sort the lines of files or file in Ascending order.

Example

Suppose, you have a file named with books.txt, 

java
dbms
c
artificial intelligence
python
big data

if you run this books.txt file with sort command then result look like this:

% sort books.txt

artificial intelligence
big data
c
dbms
java
python

vi

This command is used  to launches a vi sual editor.To edit a file type.
In all Unix version the default editor is vi editor.If you want write characters you will need to hit i to be in insert mode and then start typing. some options for insert mode


  • A appends the text at the end of the line
  • a appends the text after cursor
  • O open a new line of text above cursor
  • o open a new line of the text below cursor
For command mode

  • yy to copy a line to buffer
  • p to paste text from buffer
  • x to delete a single character
  • ndd to delete n number of lines
  • dd to delete entire line
  • nyy copy n number  of line to buffer
  • $ to move end of the line
  • lG to go to the first line of the file
  • /string to search string in a file
  • n to search for next occurrence of a file









Wednesday, February 3, 2016

JAVA INNER CLASS

Introduction:

In this post we will discuss what is inner class with examples.Every Java Programmer
should have knowledge on inner classes in java. I had already post what is class and
object in java with examples.Inner class topic is mostly useful in written Test Exams who are
attending as a java programmer.

 
Definition: 

we can declare a class inside another class such type of classes are called inner classes. This inner class concept is introduced in java 1.1 version as the part of event handling. After so much observing utilities and functionalities also using in regular coding also.

Here are the some real time example of inner class:

Syntax: 

class Outerclass{
class InnerClass{
}
}

Example1:

Without existing car object there is no chance of existing wheel object.Hence we have to declare wheel object inside car class.

Ex:

class car{
class wheel{
}
}

Example 2:

A map is collection of entry  object,without existing map object there is no chance of existing entry object.Hence we have define entry interface   inside map interface.

Ex:

interface Map{
interface entry{
}
}


Advantages of Inner classes in java:


  • Inner classes uses when you design  collection of cooperating classes
  • Inner classes enables you to write professional looking code to handle GUI Events.
  • By using inner classes or nested classes we can increase more readable and maintainable.

Types of Nested classes:

Nested classes are divided into two types.They are

a) static nested classes
b) Non-static nested classes

                In static nested classes static members are available in class whereas non-static nested class is nothing but inner classes  such as method local inner class,anonymous inner class,local inner class.

So we can mention inner classes are three types. They are

a. Inner class
b.method local inner class
c. anonymous inner class

method local  Inner class:

If we create a class inside another class is called Inner class. In this inner class can declare as private.If you declare inner class as private it can not be access from an object outside the class.

Here is an example of Inner class:

class outer{
private int num=80;
class inner{
void display()
{
System.out.println("num is"+num);
}
public static void main(String args[])
{
outer o=new outer();
outer.inner in=o.new inner();
in.display();
}
}

Output :

num is 80


Anonymous Inner class:


If class is declared with no name such type of classes are called anonymous inner class. This type of classes used in such a case where you need to override a method or interface.


Example:

abstract class Book{
abstract void java();
}
class Anonymous{
public static void main(String args[])
{
Book b=new Book();
void java()
{
System.out.println("this is java book");
}
b.book();
}
}

Output:

this is java book

c. Local Inner class:

we can declare a class inside another class is called inner class. To invoke methods of inner class you should instantiate this class inside the method.

Example:


class LocalInner{
private int num=80;
class inner{
void show()
{
class Local
{
void display()
{
System.out.println(num);
}
}
Local la=new Local();
la.display();
}

public static void main(String args[])
{
LocalInner li=LocalInner();
li.show();
}
}

Output:

80







High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...