Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Thursday 30 March 2017

Java Collection Framework

 Java Collections

Collections in java is a framework. A collection allows a "group of objects to be treated as a single unit". These objects can be stored, retrieved, and manipulated as an element of a collection.

Some collection allows duplicate elements and others do not. Some collection are ordered and others unordered. 


What is Framework ?

  • Framework provides readymade architecture.
  • Framework represents set of classes and interfaces.

What is Collection 

Collection represents the group of objects as a single unit. Java collection framework introduced in J2SE 1.2 released. Collections are set of classes and interfaces.

By using collection, You can perform operations on data such as insertion, deletion, searching, sorting and manipulation easily. The collection is an alternate of a java array.




What is Collection Framework in Java 

Collection framework in java is a unified architecture for storing and manipulating collections i.e group of objects. Java collection framework contains :
  • Interfaces
  • Interfaces implementer classes
  • Algorithm
Collection framework basically used to handle the data structure in java programming language.

Java collections framework provides  many interfaces and classes, these are :

Package :

java.util package 

Classes :

Interfaces :
  • Collection
  • List
  • Set
  • Queue
  • Dequeue

Hierarchy of Collection Framework

The java.util package contains all the classes and interfaces for the collection framework in java. When we wil make any collection program, we have to import java.util package in that program.


Java Collection Framework

Collection Interface Methods

There are many useful methods of collection interface in java.

(1) public boolean add(Object element)


This method is used to insert an element in the collection.


(2) public boolean addAll(Collection c)


This method is used to insert the specified collection elements in the invoking collection.


(3) public boolean remove(Object element)

This method is used to remove or delete an element from this collection.

(4) public boolean removeAll(Collection c)

This method is used to remove or delete all the elements of specified collection from the invoking collection.

(5) public boolean retainAll(Collection c)

This method is used to delete all the elements of invoking collection except the specified collection.

(6) public int size()

This is method is used to return the total number of elements in the collection.

(7) public void clear()

This method is used to remove the total number of elements in the collection.

(8) public boolean contains(Object element)

This method is used to search an element in the collection.

(9) public boolean containsAll(Collection c)

This method is used to search the specified collection in the collection.

(10) public Iterator iterator()

 returns an iterator.

(11) public Object[] toArray()

This is used to converts collection into array.

(12) public boolean isEmpty()

This is used to find collection is empty or not.

(13) public boolean equals(Object element)

This is used to matches two collection.

(14) public int hashCode()

 return the hashcode number for collection.


Visit for further topics like: 

Difference Between HashSet and HashMap in Collection.
Difference Between ArrayList and LinkedList in Collection.


Iterator Java

Iterator is an interface in java collection Framework. Iterator interface is basically used to iterate or draw an element in the collection in the forward direction only.


Iterator methods

There are three methods in the iterator interface, these are :

  1. public boolean hasNext() : It returns true if iterator has more elements.
  2. public object next() : It returns the elements and moves cursor pointer to the next element.
  3. public void remove() : It removes the last elements returned by the iterator.

Read More:

Share:

Wednesday 29 March 2017

Java String

 What is String ?

String in java is a sequence of characters. String is an object in java that represents sequence of characters and enclosed with the double quotes ( " ").

For example : String s = " Java ";

In the above example "Java" is a string with 4 characters.

String class are store in lang package. The java.lang.String class is basically used to create an object of string.

Character array work same as string.

For example : char array[] = {'j','a','v','a'};
                        String s = new String(array);

                        is same as : 
                                                String s = "java";

String class implements Comparable, Serializable, and CharSequence interfaces.


How to create String object

You can create string object in java by two ways, these are:

  1. By string literal
  2. By new keyword.

1) String Literal

You can create java string literal by using double quotes (" ") only.

For example : String s = "Java Programming";

Whenever you will create string object through string literal , It will go into special memory area called "String Constant Pool". Each time we create string literal, JVM checks first the string constant pool. If the string already exists in the pool, a reference to the pooled instance is returned. If string does not exists in the pool, a new string instance is created and placed in the pool.

For example:

String s = "Hello";
String ss = "Hello";//will not create new instance


Java String Constant Pool


In the above example only one object will be created "Hello" because string constant pool does not contains duplicate string object and it will return the reference to the same instance. If there is no duplicate objects then JVM create new objects e.g 

String s = "Hello";//will go into the constant pool
String ss = "Welcome";//will go into the constant pool

Both string objects will go into the constant pool because there is no duplicate objects. 

 


2) By new Keyword

You can create string object by new keyword.

For example: 

String s = new String("Java Program");//creates 2 objects

In the above example there is two object is created, first through new keyword(in heap memory) and second is through literal "Java Program"(will go in string constant pool). but priority goes to heap memory i.e reference variable 's' will refer to heap memory(new keyword).


String Example

In this example, we are creating string object through literal an new keyword.

class StringDemo
{
public static void main(String args[])
{
String s1 = "HelloJava";//Using string literal
String s2 = new String("Java Programming");//Using new keyword
System.out.println(s1);
System.out.println(s2);
}
};

output : HelloJava
              Java Programming

Immutable String in Java

There is two words, Mutable and Immutable

Immutable i.e Unchangeable or Unmodifiable .

Mutable i.e changeable or modifiable 

String is a immutable class in java. Once string object is created, its data or state cannot be changed but a new string object is created because string object is immutable. But StringBuffer and StringBuilder is mutable in java, we will learn in next chapter.

For example :

class ImmutableExample
{
public static void main(String args[])
{
String s = "United";
s.concat("States");//concat() method append string at the end
System.out.println(s);//print United because string is immutable
}
}

output : United

In the above example, Here United is not changed but a new object is created with UnitedStates, that is why string is immutable in java.
Immutable String
In the above diagram, two objects are create but  reference variable s refer to "United" object not "United States" objects because we cannot change string, once it created.


Q. Why String Literal is used in Java ?

Ans. To make memory efficient (because string constant pool does not take duplicate string objects).

Share:

Sunday 26 March 2017

Multithreading in Java

 What is Multithreading in Java ?

Java multithreading is a  process of executing more than one thread simultaneously is known as multithreading in java.

The main purpose of multithreading is to achieve the concurrent execution.


Advantage of Multithreading in Java

  • Save Time : By using multi-threading in java you can perform multiple operation at the same time so it saves time.
  • Doesn't Block Users : Java multithreading doesn't block the user because thread are independent, if exception occurs in one thread it does not affect other thread so you can perform multiple operation at the same time.

Thread

Thread in java is a light weight process and thread is a small part of a process or program. It is used to achieve multitasking.

Threads have separate path of execution and threads are independent if exception occurs in one thread, it does not affect other threads.

Thread share common memory area.


Thread in Java

There is at least one process is required for each thread. In the above picture, thread is executed inside the process. There is context-switching between these threads(T1, T2 and T3 threads). There can be multiple process inside the OS(operating system) and can be multiple thread in one process. 


Multitasking in Java

Executing multiple task or more than one task at the same time is called multitasking.


Real life example of Multitasking 

There are real life example of multitasking in given below picture

                                        Task 1 - Speaking on phone
                                        Task 2 - Writing note 


Multitasking Image



Example 2: We are able to play the music in our computer and still be able to work on a document
            
Task 1 - Play music on computer or  laptop
Task 2 - Work on notepad, Microsoft Word, etc.

Why use multitasking

  • We use multitasking to save time.
  • We use multitasking to utilize the CPU.

How to achieve multi-tasking 

You can achieve multitasking by two ways, these are :

  1. Process-based multitasking (Multiprocessing)
  2. Thread-based multitasking (Multithreading)

(1) Process-based Multitasking (Multiprocessing)

  • Process is heavy weight.
  • Running state of an instruction is call process.
  • Process taking separate memory area in a ram.
  • Between the process, the cost of communication is very high.
  • Switching from one process to another require some time for saving and loading registers, updated list, etc.

(2) Thread-based Multitasking (Multithreading)

  • Thread is a small part of a program or process.
  • Thread is a lightweight process.
  • Thread share common memory area in a ram.
  • Between two thread, the cost of communication is very low.

Multitasking can be achieved by two ways through multiprocessing and multithreading but we use multithreading not multiprocessing because thread is lightweight than process and thread share common memory area whereas process taking separate address space in memory.

So we are going to use thread-based multitasking to achieve multitasking in java.

Multithreading is mostly used for the game, animations, etc.

In java multi-threading, we will learn many concepts like How to create thread in java, How to sleep a thread in java, How to join a thread with another thread, What is thread scheduler in java thread and more.
Share:

Thursday 23 March 2017

Java Array

 Array

Array is a collection of similar types of elements or data that have contiguous memory location.

Array is an object in java. In java, array is represented via an object. Java array is a data structure where we store similar data types. Java array is fixed in size i. e you cannot increase the size of array at runtime. You can store only fixed set of elements in a java array.

Java array is indexed based, first elements of the array is stored at 0 index.
Array indexe


Advantage of Java Array

  • Code Optimization : There is no need to declare a lot of variable of same data types. We can retrieve and sort data easily.
  • Random Access : In an array, we can get any data located at any index position.
  • Performance : The performance of an array is good because you can search any element in an array on the basis of index.


Disadvantage of Java Array

  • Size Limit : Once an array has got a memory then that memory can't increase of decrease at runtime.
To solve this problem there is ''collection'' framework in java. Collection framework is an alternate of java array.


Types of Array

There are two types of array in java.

  1. Single Dimensional Array (e.g dataType[] var;)
  2. Multi Dimensional Array (e.g dataType[][] var;)

Single Dimensional Array in Java

Array Declaration in Java

Single dimensional array declaration.
dataType[] var;
        or
dataType []var;
        or
dataType var[];


Instantiation of an Array in Java

Array in java is an object, Hence we can create object by new keyword.

dataType var[] = new dataType[size];//instantiation and size of array 


Example of Single Dimensional Array in Java

In the below example, we are going to declare, instantiate, initialize and traverse an array.

For example:

class Numbers
{
public static void main(String args[])
{
int a[] = new int[5];//declaration and instantiation 

a[0] = 1;//initialization
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;

//print array

for(int i = 0; i<a.length; i++)//length is the property of array
{
System.out.println(a[i]);
}
}
}

output :1
              2
              3
              4
              5


Java Array Declaration, Instantiation, and Initialization

You can declare, instantiate and initialization an array in one step e.g

int a[] = {10,20,30,40,50};//declaration, instantiation, initialization 

For example

class Numbers
{
public static void main(String args[])
{
int number[] = {99,100,80,40};//declaration,instantiation,initialization
for(int i = 0; i<number.length; i++)
{
System.out.println(number[i]);
}
}
}

output: 99
             100
             80 
             40


Accessing Array Elements in Java

You can access the elements of array by using the index value of the element.

For example:

class Test
{
public static void main(String args[])
{
int a[] = {2,4,6,8,1};
System.out.println(a[3]);
}
}

output: 8


Multidimensional Array in Java

In the multidimensional array, data is stored in row and column based index(also known as matrix form).


Multidimensional Array Declaration in Java

dataType[][] var;
          or
dataType [][]var;
          or
dataType var[][];
          or 
dataTytpe []var[];


Instantiation of Multidimensional Array in Java

int var[][] = new int[3][3];//3 rows and 3 column 

Initialization of Multidimensional Array in Java

var[0][0] = 1;
var[0][1] = 2;
var[0][2] = 3;
var[1][0] = 4;
var[1][1] = 5;
var[1][2] = 6;
var[2][0] = 7;
var[2][1] = 8;
var[2][2] = 9;


Example of Multidimensional Array in Java

In the below example, we are going to declare, instantiate, initialize and print multidimensional array in java.

For example:

class Numbers
{
public static void main(String args[])
{
int a[][] = { {1,2,3}, {4,5,6},{7,8,9}};//dec..insta..initiz

//print 2d array

for(int i =0; i<3; i++)
{
for(int j =0; j<3; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}


output: 1 2 3
             4 5 6
             7 8 9


How to find class name of Java Array

Array is an object in java. For array object , proxy class is created whose name can be obtained by getClass() and getName() methods on the object.

For example:

class ArrayName
{
public static void main(String args[])
{
int arr[] = {1,2,3};
class c = arr.getClass();
String s = c.getName();
System.out.println(s);
}
Share:

Wednesday 22 March 2017

Exception Handling in Java

 

Java Exception Handling

The exception handling in java is the way to handle run-time errors so that the normal flow of the application can be maintained. Exception handling is the most powerful feature of java.

First we understand what is exception?


What is exception

If we say exception in other word is "abnormal" condition which arise in application. Java Exception is an event that disrupts the normal flow of the program and an exception is an object which is thrown at run-time.


What is exception handling

Exception handling in java is used to control the normal flow of the program by using the exception handling in program. Exception handling is used to handle run-time errors such as IO, SQL, ClassNotFound, etc. 


Why use exception handling in java

  • To maintain the normal flow of the program
  • To convert the system error generated massages into user friendly error massages.

For example:

Suppose there is 5 statements in your program and there occurs an exception at statement 3 and rest of the statements or code will not be executed i.e 4 to 5 statements will not execute. If we use exception handling, rest of the statements will execute perfectly. That is why we use exception handling.

statements 1;
statements 2;
statements 3;//exception occurs
statements 4;
statements 5;

Exception Handling in java
In the above diagram, Object is the top most class in java, all the classes extends Object class by default in java. It is super class in java. We will learn in detail in later about Object class.

Here Throwable is  top most class of exception classes and it is located in lang package.


Types of Exception

There are mainly two types of exceptions,where error is considered as unchecked exception
  1. Checked Exception
  2. Unchecked Exception
  3. Error

Checked Exception

Checked exception are the exception which checked at compile-time e.g SQL Exception, IO Exception, etc.

Unchecked Exception

Unchecked exception are not checked at compile-time, Unchecked exception are checked at run-time e.g ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.


Error

Error is irrecoverable e.g VirtualMachineError, AssertionError, OutOfMemoryError, StackOverflow, etc.


There are many reasons for Exception

  • Open a non existing files
  • Network Connection Problems

Common scenarios where exceptions may occurs

There are given some scenarios where unchecked exception may occurs, these are:

(1) ArithmeticException 

If we divide any number by zero, there occurs an ArithmeticException.

For example:

int number = 32/0;//ArithmeticException

(2) NullPointerException

If we have null values in any variables.

For example:

String a = null;
System.out.println(a.length());//NullPointerException

(3) ArrayIndexOutOfBoundsException

If you are inserting any value in the wrong index, there occurs an ArrayIndexOutOfBoundsException.

For example:

int a[] = new int[5];
a[6]=10;//ArrayIndexOutOfBoundsException

(4) NumberFormatException

The wrong formatting of any values, suppose i have a string variable that have characters, converting this variable into digit will occur NumberFormatException.

For example:

String s = "xyz";
int a = Integer.parseInt(s);//NumberFormatException


Difference between Error and Exception 

Error
  • Error cannot be handle
  • For example NoSuchMethodError, OutOfMemoryError, JVM error

Exception
  • Exception can be handle easily
  • For example ArrayIndexOutOfException, ArithmeticException


Java Exception Handling Keyword 

To maintain the normal flow of the program we are going to use some useful keywords so that we can easily handle the exceptions.
  • try
  • catch
  • finally
  • throw
  • throws
learn in next chapter
Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate