Let's learn java programming language with easy steps

Wednesday, 19 July 2017

Difference Between ArrayList and Vector

ArrayList vs Vector - Java Collection Framework

Difference Between ArrayList and Vector

Now here we will learn what is the differences between ArrayList and Vector class in java. " what is the differences between ArrayList and Vector in java " this is mostly asked question in any java interviews.

There are many differences between ArrayList and Vector in java collection framework. Let's see

First starts with ArrayList class.

ArrayList Class

  • ArrayList class are non-synchronized i.e multiple thread can access simultaneously. In other words, ArrayList class are not Thread safe.
  • ArrayList class is not a legacy class i.e old class in java collection.
  • ArrayList class is faster than vector class because it is non-synchronized.
  • The size increment of ArrayList class is 50% i.e half as needed.
  • ArrayList class uses Iterator interface to traverse the elements.

Java ArrayList Example

This is the simple example of java ArrayList class where we will insert some elements in this list and after inserting elements we will traverse all the elements from the array list.

import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListExample
{
public static void main(String args[])
{
//declaration of ArrayList class
ArrayList<String> al = new ArrayList<String>();
al.add("java");//insert elements
al.add("python");
al.add("c++");
al.add("c++");
al.add("html");
al.add("css");
al.add("java");

//traversing an elements by using Iterator interface
Iterator i = al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

output : java
              python
              c++
              c++
              html
              css
              java

In the above example, as we know ArrayList class can allow duplicate elements and maintains insertion order of an elements.

Now, move to Vector class in java collection.

Vector Class

  • Vector class is a synchronized class i.e multiple thread cannot access simultaneously, but one-by-one they can. In other words, Vector class is a Thread safe class.
  • Vector class is slower than ArrayList class because Vector class is synchronized(thread safe) class.
  • The size increment of Vector class is 100% i.e double as needed.
  • We can use both Iterator interface and Enumeration interface to traverse the elements of vector class.


Java Vector Example

In this example, we will use some method of Vector class for inserting an elements in Vector and use Enumeration interface to traverse the elements.

import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
//declare Vector class
Vector<String> v = new Vector<String>();
v.add("rahul");//collection's method
v.add("ravi");
v.add("mohit");
v.addElement("rahul");//vector's method
v.addElement("love");
v.addElement("kush");

//traversing an elements by using Enumeration interface
Enumeration e = v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}

output : rahul
              ravi
              mohit
              rahul
              love
              kush

In the above example, Vector class allows duplicate elements and maintains insertion order of an elements.

Similarities Between ArrayList and Vector Class

There are some similarities between ArrayList and Vector class in java.

(1) ArrayList and Vector both class implements List interface.
(2) ArrayList and Vector both allows duplicate elements.
(3) ArrayList and Vector both maintains insertion order of an elements.
(4) By using Iterator interface we can traverse all the elements of ArrayList and Vector.
(5) Both class ArrayList and Vector class belongs to the java.util package.



Share:

Tuesday, 18 July 2017

Java Runtime

Java Runtime Class

Java Runtime

In java Runtime is a class which is belong to the java.lang package. Every java application has a single instance of a class Runtime that allows the application to interface with the environment in which the application is running

The current runtime can be obtained from the getRuntime method and an application cannot create its own instance of this class.

Runtime class in java extends only super class of java i.e Object class.

public class Runtime extends Object 


Methods of Java Runtime Class

There are some methods of java Runtime class and these are given below.

(1) void addShutdownHook(Thread hook)

This method registers a new virtual-machine shutdown hook.

(2) int availableProcessors()

This method returns the number of processors available to the Java Virtual Machine.

(3) Process exec(String command)

This method executes the specified string command in a separate process.

(4) Process exec(String[] cmdarray)

This method executes the specified command and arguments in a separate process.

(5) Process exec(String command, String[] envp)

This method executes the specified string command  in a separate process with the specified environment.

(6) void exit(int status)

This method terminates the currently running Java Virtual Machine by initiating its shut down sequence.

(7) long freeMemory()

It is used to returns the amount of free memory in the java virtual machine.

(8) void gc()

It is used to runs the garbage collector.

(9) static Runtime getRuntime()

This method returns the run time object associated with the current Java application.

(10) long maxMemory()

This method returns the maximum amount of memory that the java virtual machine will attempt to use.

(11) void halt(int status)

Java virtual machine forcibly terminates by this method.

(12) void load(String filename)

This method loads the native library specified by the filename argument.

(13) boolean removeShutdownHook(Thread hook)

This method De-registers a previously-registers virtual machine shut down hook.

(14) long totalMemory()

This method returns the total amount of memory in the java virtual machine.


(1) Java Runtime exec() Method Example

By the help of this program, we will open notepad in java.

class Test
{
public static void main(String args[])throws Exception
{
Runtime.getRuntime().exec("notepad");
}
}

(2) Java Runtime availableProcessors() Method Example

public class Sample
{
public static void main(String args[])throws Exception
{
System.out.println(Runtime.getRuntime().availableProcessors());
}
}

(3) Java Runtime exit() Method Example

public class ExitExample
{
public static void main(String args[])
{
//program start here
System.out.println("program start");

//cause the program to exit
Runtime.getRuntime().exit(0);

//try to print after exit method
System.out.println("program will continue");
}
}

output : program start


(4) Java freeMemory() Method Example

public class Demo
{
public static void main(String args[])
{
//print when the program starts
System.out.println("program starts here");

//print the numbers of free bytes
System.out.println(Runtime.getRuntime().freeMemory());
}
}

output : program starts here
              57645872

(5) Java maxMemory() Method Example

public class Demo1
{
public static void main(String args[])
{
//print when the program starts
System.out.println("program starts here");

//print the numbers of free bytes
System.out.println(Runtime.getRuntime().maxMemory());
}
}

output : program starts here
              934281216

(6) Java totalMemory() Method Example

public class Demo1
{
public static void main(String args[])
{
//print when the program starts
System.out.println("program starts here");


System.out.println(Runtime.getRuntime().totalMemory());
}
}

output : program starts here
              64487424

Share:

Sunday, 16 July 2017

Difference Between Final, Finally, Finalize In Java

Java Final vs Finally vs Finalize

final, finally, finalize in java

Now here we will learn what is the difference between final, finally and finalize in java. This is very-very important question for any java interviews.

What is the difference between final and finally and finalize in java is mostly asked question in any java interviews. So let's starts

First we starts with final.


Final

  • Final is a keyword or non-access modifier in java.
  • Final keyword basically used to stop or restricted the users.
  • Final keyword can be apply with class, variables, and methods.
  • If you make any class as final class then you cannot inherit(extends) this class. If you make any variable as final variable then you cannot change the value of this variable after initialization. If you make any method as final method then you cannot override this method.
  • If we declare final variable along with static keyword will become a constants.

Syntax of final keyword

// Final keyword with class

final class Test
{
-----
-----
-----
}

// Final keyword with variable

final int a = 40;

// Final keyword with method

final void run()
{
-----
-----
-----
}


Java Final Keyword Example

In this example we will apply final keyword only with class, if you apply final keyword with class then you cannot inherit that class in java.

final class Test
{
void show()
{
System.out.println("hello");
}
}
class Simple extends Test
{
public static void main(String args[])
{
Simple s = new Simple();
s.show();
}
}

output : compile time error


Finally

  • Finally is a block in java.
  • Finally block basically used with try and catch block, you can use finally block only with try block or with try or catch.
  • Finally block used to execute important code or cleanup processing.
  • Finally block is always executes weather the exception is handled or not.
  • Finally block must be the last block in the program i.e first declare try block then finally block or first declare try then catch the finally.

Note : There are some situations where finally block doesn't executes e.g if exception occurs in finally block and if you call System.exit() in program.


Java Finally Block Example

class Test
{
public static void main(String args[])
{
try
{
int i = 42/0;//ArithmeticException occurs
System.out.println(i);
}
catch(Exception e)
{
System.out.println("exception is handled");
}
finally
{
System.out.println("finally block always executes");
}
}
}

output : exception is handled
              finally block always executes

In the above example, Exception is occurred in try block and catch in catch block and finally block always executes weather exception is handled or not.


Finalize

  • Finalize is a method in java.
  • Java finalize() method comes from Object class which is super class in java.
  • In java before an object is garbage collected, the garbage collectors calls finalize() method, In other words before removing or destroying unused object or un-referenced object, garbage collector calls finalize() method.
  • Java finalize() method generally used to close the connections, stream etc.

Java Finalize Example

class Simple
{
public void finalize()
{
System.out.println("finalize example");
}
public static void main(String args[])
{
Simple s = new Simple();
s = null;
System.gc();
}
}

output : finalize example






Share:

Friday, 14 July 2017

Java Keywords

Keywords In Java

java keywords


Now, Here in java programming language there are many java keywords are available. But we will learn some of them java keywords with example. So let's starts

(1) Java this Keyword

First we starts with this keyword in java. In java this is a keyword or reference variable which is refers to the current object. In java there are many uses of java this keyword, this keyword can be used to remove ambiguity error from the program, this keyword can be used in constructor chaining i.e calling one constructor from another constructor, etc.

Java this Keyword Example

class Student
{
String s;//data member
int rollno;//data member
Student(String s, int rollno)//constructor
{
this.s = s;
this.rollno = rollno;
}
void get()
{
System.out.println(s+" " +rollno);
}
public static void main(String args[])
{
Student s1 =  new Student(" krishna ", 100);
Student s2 =  new Student(" shankar ", 200);
s1.get();
s2.get();
}
}

output : krishna 100
              shankar 200

In the above example, there data member and arguments passed in constructor is same, so there may be ambiguity error, so remove this error we can use this keyword here.

(2) Java Static Keyword 

Java static keyword basically it is used to save memory. It can be used with variables, methods and nested class. 

We can apply static keyword with variable, method and nested class but in the below example we will use static keyword with method only .

If we declare any method as static than there is no need to create an object of that class because we can call any static method with the class name. If there is no object creation i.e save a memory because object goes into heap memory.

Java Static Keyword Example

class Employee
{
static int id = 50;
static String name = "varun";
static void show()//static method{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee.show();//accessing static method with class name
}
}


Some Rules of Static Keyword In Java

  • You can access static method with class name.
  • You cannot access non-static data member in static method.
  • You can change the value of static data member in static method.

 

(3) Java Extends Keyword

Java extends keyword basically used in inheritance concept for re-usability where child class extends(inherit) parent class so that child can use the data member(properties ) and methods of parent class.

Java Extends Keyword Example

class Parent
{
int age = 75;
void show()
{
System.out.println("parent is a teacher");
}
}
class Child extends Parent
{
int salary = 5000;
void get()
{
System.out.println("child is a pilot ");
}
public static void main(String args[])
{
Child c = new Child();
System.out.println(c.age);
c.show();
System.out.println(c.salary);
c.get();
}
}

output : 75
             parent is a teacher
             5000
             child is a pilot

(4) Java Super Keyword 

Java super is a keyword or reference variable which refers immediate parent class object and there are many uses of super keyword in java.

Java Super Keyword Example

class Parent
{
void show()
{
System.out.println("parent");
}
}
class Child extends Parent
{
void show()
{
System.out.println("child");
super.show();
}
public static void main(String args[])
{
Child c = new Child();
c.show();
}
}

output : child
              parent

In the above example, there are parent and child both have the same name method i.e show() method. If you will not use super keyword here, by default child's show method will execute only. If you will use super keyword here then both parent and child's show() method will execute.


(5) Java Implements Keyword

Java implements keyword is used when a class implements an interface in java.


Java Implements Keyword Example

interface Simple
{
void show();
}
class Test implements Simple
{
public void show()
{
System.out.println("hello java ");
}
public static void main(String args[])
{
Simple s = new Test();
s.show();
}
}

output : hello java

(6) Java Final Keyword

Java final is a keyword or non-access modifier which is used to restrict the user. Java final keyword can be used with class, variable, method.


  • If you make any class as a final then you cannot inherit that class.
  • If you make any variable as final then you cannot change the value of this variable.
  • If you make any method as final, you can't override this method in java.



Java Final Keyword Example

If you make any variable as final variable after that you can't change the value of this final variable.

class FinalExample
{
final int a = 45;//final variable 
void show()
{
a = 50;
System.out.println(a);
}
public static void main(String args[])
{
FinalExample f = new FinalExample();
f.show();
}
}

output : compile time error


(7) Java Throw Keyword

Java throw is a keyword in java which mainly used to throw custom exception or user defined exception in java.

Java Throw Keyword Example

class ThrowExample
{
static void test(int age)
{
if(age<18)
{
throw new ArithmeticException("not valid age");
}
else
{
System.out.println("your welcome");
}
}
public static void main(String args[])
{
ThrowExample.test(5);
}
}

output : Exception in thread "main" java.lang.ArithmeticException : not valid age


(8) Java Throws Keyword

Java throws is a keyword in java which is mainly used to declare an exception in java and makes our program handler free.


Java Throws Keyword Example

import java.io.IOException;
class ThrowsExample
{
void a()throws IOException
{
throw new IOException("error");
}
void b()throws IOException
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("exception is handled");
}
}
public static void main(String args[])
{
ThrowsExample t = new ThrowsExample();
t.c();
}
}

output : exception is handled


 
Share:

Facebook Page Likes

Popular Posts

Translate