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

Sunday 30 April 2017

Java List

 

List Interface

Java List

List is an interface in java collection framework. List interface can contains duplicate elements. List interface can maintain the insertion order of elements.

In List, we can insert and delete elements on the basis of index by using list interface's methods.

List interface allows n number of null values.

There are 4 classes which implements List interface in java. These are

Methods of List Interface In Java

There are some useful methods of list interface in java.

1) void add(int index, Object element)

This method is used to insert the elements into the list at the index passed in the index.

2) boolean addAll(int index Collection c)

This method is used to insert all the elements of c into the list at the index passed in the index.

3) object get(int index)

Used to return the object which is stored at the specified index in the collection.

4) object set(int index, Object element)

Used to set the elements to specified index in the list.

5) object remove(int index)

It is used to remove the particular element at position index and return removed elements  from the list.

6) ListIterator listIterator()

It is used to return an iterator to the begging of the list.

7) ListIterator listIterator(int index)

It is used to return an iterator from the list that starts at specified index.


Java List Example

import java.util.*;
class ListExample
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
al.add("ram");
al.add("hanuman");
al.add("ram");
al.add(1, "sita");//add sita at first index in the list
for(String s : al)
{
System.out.println(s);
}
}
}

output : ram
              sita
              hanuman
              ram


ListIterator Interface

ListIterator is an interface. ListIterator is a sub-interface of an iterator interface in java. ListIterator interface is used to iterate the elements in both direction i.e forward and backward direction.

We can traverse an elements of List and Set by using "iterator" interface but by using "ListIterator" interface we can traverse only "List" interface. 

ListIterator interface works  specially for List.


Methods of ListIterator Interface

1) boolean hasNext()

Returns true if the list iterator has more elements when traversing the list in the forward direction.

2) Object next()

Returns the next element in the list.

3) boolean hasPrevious()

Returns true if the list iterator has more elements when traversing the list in the reverse direction.

4) Object previous()

Returns the previous elements in the list.

5) Object previousIndex()

This method returns index of the element that could be returned by subsequent call to previous method.


Example of ListIterator Interface

There are simple example of ListIterator in collection . In this ListIterator program we will traverse  the list in backward and forward direction(both).

import java.util.*;
class ListIteratorExample
{
public static void main(String args[])
{
ListIterator<String> litr = null;
List<String> l = new ArrayList<String>();
l.add("siya");
l.add("sid");
l.add("simmu");
l.add("barkha");
//obtaining list iterator
litr = l.listIterator();
System.out.println("Traversing list in forward direction");
while(litr.hasNext())
{
System.out.println(litr.next());
}
System.out.println("Traversing list in backward direction");
while(litr.hasPrevious())
{
System.out.println(litr.previous());
}
}
}

output: Traversing list in forward direction
              siya
              sid
              simmu
              barkha
             Traversing list in backward direction
             barkha
             simmu
             sid
             siya
Share:

Thursday 27 April 2017

String Programs in Java

 String Programming

Here we will discuss some important string programs in java which is very important and good for interview. Let's start 


String Programs in Java



1) String Length

This is very simple program in String concept. In this program we will display the total number of characters in string.

For example :

class StringLenghtExample
{
public static void main(String args[])
{
String s1 = "java";
String s2 = "java programming";
System.out.println(s1.length());//print 4 length
System.out.println(s2.length());//print 16 space will count after java
}


output : 4
             16


2) String Concatenation in Java

By using the string concatenation we can combine the two string. In java String, there are two ways to concat string in java. these are
  • By concat() method
  • By +(plus) operator
In the below example we will concat string through + operator only.

String Concatenation by + operator

This operator(+) is used to append one string into another string.

For example 1 :

class StringConcatenationExample
{
public static void main(String args[])
{
String s1 = "java";
String s2 = "programming";
String s3 = "java"+" programming";

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);//String concatenation through + operator 
}
}


output : java
              programming
              java programming

For example 2 :

class StringConcatenationExample1
{
public static void main(String args[])
{
String s = 30+70+"india"+20+30;
System.out.println(s);
}
}

output : 100india2030

In the above example 2, In java string concatenation operator(+) can concat not only string but primitive type values also.

" All the + operator will be treated as String concatenation operator after a String literal ". 


3) Java String Array

In this example we will learn how to create and String array in java.

For example :

class StringArrayExample
{
public static void main(String args[])
{

//declaration,instantiation,initialization of String array in single line

String[] fruits = {"mango","banana","orange"};
System.out.println(fruits[1]);//print first index of array i.e banana

// or

//Another way of creating String array using multiple lines

String[] clothes = new String[3];//declaration,instantiation of String
clothes[0] = "paint";//initialization of String array
clothes[1] = "shirt";
clothes[2] = "cap";

//Iterate the String array using loop
for(int i = 0; i<clothes.length; i++)
{
System.out.println(clothes[i]);
}
}
}

output : banana
              paint
              shirt
              cap



4) Java Reverse String

In this program we will not using reverse method of String. We will reverse the string without using String API.

For example :

class ReverseString
{
public static void main(String args[])
{
String str = "Hello Java";

String reverse = "";
for(int i= str.length()-1; i>=0; --i)
{
reverse+=str.charAt(i);
}
System.out.println(reverse);
}
}

output : avaJ olleH


5) String Palindrome in Java

In this program, we will check given string is palindrome or not. Palindrome means remains the same after reverse e.g Madam is palindrome because if we reverse this string it will look same madam and sir is not palindrome.

For example :

class PalindromeString
{
public static void main(String args[])
{
String str = "MADAM";
String reverse = "";

for(int i= str.length()-1; i>=0; --i)

{

reverse+=str.charAt(i);

}

System.out.println(reverse);


if(reverse.equalsIgnoreCase(str))
{
System.out.println("String is palindrome");
}
else
{
System.out.println("String is not palindrome");
}
}
}


output : MADAM


6) String Sort

In this program, We will sort the String with String API.

For example 1 :

import java.util.*;
class SortStringExample
{
public static void main(String args[])
{
String sort = "ihgfedcba";
char[] c = sort.toCharArray();
Arrays.sort(c);
String s = new String(c);
System.out.println(s);
}
}

output : abcdefghi

For example 2 :

In this program, We will sort the String without String API.

class SortStringExample2
{
public static void main(String args[])
{
String s1 = "edcba";
char temp = 0;
char[] c = s1.toCharArray();
for(int i = 0; i<c.length; i++)
{
for(int j = 0; j<c.length; j++)
{
if(c[j]>c[i])
{
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}

for(int k = 0; k<c.length; k++)
{
System.out.print(c[k]);
}
}
}

output : abcde

Share:

Monday 24 April 2017

Wrapper Class in Java

 

Wrapper Class

Wrapper class in java is used to convert primitive types into object and object into primitive types. All the java wrapper classes are immutable and final.

Since J2SE 5.0, Autoboxing and Unboxing allows easy conversion automatically between primitive types and their corresponding wrapper classes.

Autoboxing : The automatic conversion of primitive types into object is known as autoboxing in java.

for example - conversion of int to Integer, double to Double, long to Long etc.

Unboxing : The automatic conversion of object into primitive types is known as unboxing in java. Unboxing is the reverse process of autoboxing. 

for example - conversion of Integer to int, Double to double, Long to long etc.

There are 8 wrapper classes in java.lang package. The list of eight wrapper classes is given below.


Wrapper Class in Java

Creating Object of Wrapper Class

Suppose we create an object of Integer wrapper class. There are two ways we can

Integer i = new Integer("32");
Integer i = new Integer(32);

By passing String or variable of the same data type as that of the type to which the wrapper class corresponds except for the character wrapper class.

 Wrapper Class Example : Converting Primitive to Wrapper

In this examples we will converting int(primitive) to Integer(wrapper).

For example 1 :

class WrapperClassFirst
{
public static void main(String args[])
{
int a = 30;
Integer i = Integer.valueOf(a);//converting int to Integer
Integer k = a;//compiler will write internally Integer.valueOf(a)
System.out.println(i);
System.out.println(k);
}


output : 30
              30

For example 2 :

class WrapperClassSecond
{
void age(Integer i)
{
System.out.println(i);
}
public static void main(String args[])
{
WrapperClassSecond  a = new WrapperClassSecond();
//passed int (primitive type), it will converted into Integer object
a.age(18);
}
}

output : 18

In the above example, we define a method which excepting Integer wrapper class object but we passed value as parameter of primitive type when we call a method. It will converted primitive to Integer at run time.

For example 3 :

Autoboxing in case of Collection Framework.

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(100);//Autoboxing int primitive to Integer wrapper
al.add(101);//Autoboxing int primitive to Integer wrapper


Wrapper Class Example : Converting Wrapper to Primitive

In this example we will convert wrapper to primitive types.

For example 1 :

class WrapperClassFirst
{
public static void main(String args[])
{
Integer i = new Integer(5);
int a = i.intValue();//converting wrapper to primitive
int b = i;//compiler will add i.intValue()
System.out.println(a+" "+b);
}
}

output : 5 5

For example 2 :

class WrapperClassSecond
{
public static void age(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
Integer a = new Integer(60);
//passed Integer wrapper class object ,will converted into int primitive
age(a);
}

}

output : 60

In the above example, there is static method age with primitive type parameter but we passed Integer wrapper class object when we call method.

For example 3 :

In case of collection Framework class.

ArrayList al = new ArrayList();
int i = al.get(0);//Unboxing, get method returns Integer object


Some Points about Wrapper Class

  • Wrapper class can be used to achieve polymorphism.
  • Primitive types cannot by null but wrapper class can be null.
  • 'Number' class is the super class of all wrapper classes in java. Which is available in java.lang package



Share:

Thursday 20 April 2017

LinkedList Java

 

Java LinkedList class

LinkeList is a class in java collection framework. LikedList class uses doubly linked list to store the elements. LinkedList class is a collection of nodes.

LinkedList class implements List interface and extends AbstractList class.

LinkedList class maintaining data in particular order.


Some of the important points about LinkedList class show below

  • LinkedList class can contain duplicate elements
  • LinkedList class maintains insertion order
  • LinkedList class are non-synchronized
  • LinkedList class is a collection of nodes
  • LinkedList class allows n number of null values
  • LinkedList class can be used as stack, list and queue.
  • LinkedList class provides fast manipulation because there is no shifting to be occurred 
In doubly linked list we can add or remove elements from both sides.


Hierarchy of LinkedList class in Java

LinkedList Java


Java LinkedList Constructor 

(1) LinkedList()

It is used to create an empty LinkedList.

(2) LinkedList(Collection c)

It is used to create an a linkedlist containing the elements of the specified collection.


LinkedList Methods

1) void add(int index, Object element)

This method is used to insert the specified element at the specified position index in LinkedList.

2) void addFirst(Object o)

This method is used to insert the given element at the begging of a list.

3) void addLast(Object o)

This method is used to add the given element to the end of a list.

4) boolean add(Object o)

This method is used to add the specified element to the end of a list.

5) int size()

This method returns the total number of elements in a list.

6) Object getFirst()

Return the first element in a list.

7) Object getLast()

Return the last element  in a list.

8) boolean contains(Object o)

Return true if the list contains a specified elements.

9) boolean remove(Object o)


Remove the first occurrence of a specified elements in the list.

10) void clear()

Removes all the elements of a list.

11) int indexOf(Object o)

Return the index of specified elements.

12) int lastIndexOf(Object o)

Return the index of last occurrence of the specified elements.

13) Object poll()

This method returns and removes the  first elements in a list.

14) Object pollFirst()

This method removes the  first elements in a list. Same as poll method.

15) Object pollLast()

This method removes and returns last elements in a list.

16) Object clone()

Return the copy of a list.

Java LinkedList Example

import java.util.*;
class LinkedListExample
{
public static void main(String args[])
{

//LinkedList declaration 

LinkedList<String> linkedlist = new LinkedList<String>();
linkedlist.add("red");//add String type elements in a list
linkedlist.add("blue");
linkedlist.add("yellow");
linkedlist.add("pink");
linkedlist.add("blue");

Iterator i = linkedlist.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

output : red
              blue
              yellow
              pink
              blue

Java LinkedList Example 2

import java.util.*;
class LinkedListExample2
{
public static void main(String args[])
{
LinkedList<String> linkedlist = new LinkedList<String>();

//Display the size of LinkedList before adding elements
System.out.println("size of LinkedList"+linkedlist.size());

//adding elements in list
linkedlist.add("ram");
linkedlist.add("ranbir");
linkedlist.add("shahid");
linkedlist.add("varun");
linkedlist.add("alia");

//Display elements of LinkedList

System.out.println("Elements of LinkedList"+linkedlist);

//Display the size of LinkedList after adding elements

System.out.println("size of LinkedList"+linkedlist.size());

//Add First and Last elements in the LinkedList

linkedlist.addFirst("Top");
linkedlist.addLast("Bottom");
System.out.println("after adding first and last elements"+linkedlist);

}

}

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate