Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, 25 November 2015

How to Make Singleton Class In Java

package com.javaproficiency;

public class SingletonDemo {

static SingletonDemo obj;
private  SingletonDemo(){
}

public static SingletonDemo getInstance(){
 if(obj!=null){
  return  obj;
 }
 else{
  obj=new SingletonDemo();
 return obj;
 }
}

public static void main(String[] args) {

SingletonDemo obj1 = SingletonDemo.getInstance();
SingletonDemo obj2 =  SingletonDemo.getInstance();

if( obj1 == obj2 ){
System.out.println(" singleton object ");
}else{
System.out.println(" not singleton object ");
}

System.out.println(obj1==obj2);
}


}

Output:

 singleton object
 true

How to print array without using loop in java

How to print array without using loop in java is frequently asked question in interview. We can print array without using any loop. For this purpose we will use Arrays's method toString().

package com.javaproficiency;

import java.util.Arrays;

public class PrintArray {
//print array without using loop in java
public static void main(String[] args) {

int [] arr = {15,60,32,33,12};
System.out.println(" Print array ="+ Arrays.toString(arr));

char [] crr = {'A','B','C','D','E','F'};

System.out.println(" Print Array ="+ Arrays.toString(crr));

}

}


Output:

 Print array =[15, 60, 32, 33, 12]
 Print Array =[A, B, C, D, E, F]

How to find largest element in an array with index and value ?

package com.javaproficiency;

public class LargestElement {
//How to find largest element in an array with index and value ?

public static void main(String[] args) {

int [] arr ={4,5,10,12,8,6};
int largest =0;
int index =0;
for(int i =0 ; i < arr.length; i++){
if( largest < arr[i]){
largest = arr[i];
index = i;
}
}
System.out.println(" largest element  ="+ largest + " index ="+index);

}

}

Output :

 largest element  =12 index =3

Program For nth Fibonacci Number in Java

The Fibonacci numbers are the numbers in the following integer sequence.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ……..

In simple word such series that each element is sum of two previous element is called Fibonacci series.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

    Fn = Fn-1 + Fn-2

1. Program to print Fibonacci Series without using Recursion In Java



package com.javaproficiency;

public class Fibonacciseries {
public static void main(String[] args) {
//Fibonacci series without using Recursive?
int n=10;
int x = 1;
int y = 0;
int z =0;
System.out.print(y +" "+ x);
int i=0;
while(i < n){
z=y+x;
System.out.print("  "+ z);
y=x;
x=z;
i++;
}

}

}


output :

0 1  1  2  3  5  8  13  21  34  55  89


2. Program to print Fibonacci Series using Recursion In Java 



package com.javaproficiency;

public class Fibonacciserieswithrecursion {

    public static void main(String[] args) {
int n = 10;
int a =0 ;
int b =1;
System.out.print( a + " " + b);
fibonaci(n, a, b);
}
   
    static void fibonaci(int n , int a ,int b){
    int sum = 0;
    if (n > 0 ) {
    sum = a+b;
    a = b;
    b = sum;
System.out.print(" "+ sum);
    fibonaci(n-1, a, b);
}
   
   
    }

}


output:

0 1 1 2 3 5 8 13 21 34 55 89

Wednesday, 4 November 2015

Access and Non-Access Modifiers in java


Modifiers are keywords that you add to those definitions to change their meanings.

There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

There are 4 types of java access modifiers:
   
 1. private
 2. default
 3. protected
 4. public

1.  private: 


private modifiers access only within class. If we try access private modifiers outside of class ,it produce compilation error. We There is two class user and test.User class have private variable and methods. If we try access private data out side of class then it gives error.

package com.javamodifier;

class User {
     private String name ="java";
      private void display(){
          System.out.println(" name of user is ="+ name);
    }
 }


public class Test{
public static void main(String[] args) {
            User user = new User();
            System.out.println( user.name); //compilation error   
            user.display() ////compilation error
        }
 }


How we can access private data outside class?

For this see public modifiers . Public modifies explain below in this post.


2 Default :


 Default has scope only inside the same package. If we try access default modifiers outside of class , it gives error.

There is two classes Demo and User in different packages.

package com.javamodifier;
import com.javatest.User;


public class Demo {

public static void main(String[] args) {
           User user = new User();
           System.out.println(user.name);// CE
     }
}



package com.javatest;

public class User {

         String name ;
         public void display(){
         System.out.println("name of user ="+name);
    }
}



3. protected : 


Protected has scope within the package and all sub classes. In this Example We access Student's protected method by inheritance.

package com.javamodifier;

import com.javatest.Student;

public class Demo extends Student {
public static void main(String[] args) {
           Student student = new Student();
           student.print();
     }
}


package com.javatest;

public class Student {
          protected void print(){
               System.out.println(" Student Called");
         }
}


Output:

Studnet Called

4. Public:


Public scope is visible everywhere. In previous examples we can access print method of student class without inherintance ,if it declare as public.


package com.javamodifier;

import com.javatest.Student;

public class Demo {
        public static void main(String[] args) {
            Student student = new Student();
              student.print();
        }
}


package com.javatest;

public class Student {
      public void print(){
           System.out.println(" Student Called");
       }
}






How to Access Private Modifiers Outside Class:

We can access private modifiers outside class using public method of this class(withoout using inherintance). Below we give example. Emp class have private data mamber empId and private method diplaySalary. These private modifiers we access throw public accessEmp() method.



package com.javamodifier;

public class MainTest {
public static void main(String[] args) {
Emp emp = new Emp();
emp.AccessEmp();
}
}

class Emp{
private int empId=10;
private void displaySalary(){
System.out.println("salary is = 10000");
}

public void AccessEmp(){
System.out.println("Emp id is ="+empId);
displaySalary();
}

}



Output:

Emp id is =10
salary is = 10000


Non Access Modifiers:


There is some non-access modifiers of java.

The static modifier for creating class methods and variables

The final modifier for finalizing the implementations of classes, methods, and variables.

The abstract modifier for creating abstract classes and methods.

The synchronized and volatile modifiers, which are used for threads.






Sunday, 20 September 2015

Sorting Algorithms - Java Example Programs

1 Comparison of algorithms
2 Popular sorting algorithms

    2.1 Simple sorts
        2.1.1 Insertion sort
        2.1.2 Selection sort
    2.2 Efficient sorts
        2.2.1 Merge sort
        2.2.2 Heapsort
        2.2.3 Quicksort
    2.3 Bubble sort and variants
        2.3.1 Bubble sort
        2.3.2 Shell sort
        2.3.3 Comb sort
    2.4 Distribution sort
        2.4.1 Counting sort
        2.4.2 Bucket sort
        2.4.3 Radix sort

3 Memory usage patterns and index sorting
4 Inefficient sorts
5 Related algorithms


Saturday, 29 August 2015

Java Memory Leak Cause

 In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations[1] in such a way that memory which is no longer needed is not released. In object-oriented
programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.[2] A memory leak has symptoms similar to a number of other problems (see below) and generally can only be diagnosed by a programmer with access to the program's source code. Here are the typical cause of  Memory Leak In Java:

1. Do not close DB, file, socket, JMS resources and other external resources properly.

2. Do not close resources properly when an exception is thrown.

3.  Keep adding objects to a cache or a hash map without expiring the old one.

3. Do not implement the hash and equal function correctly for the key to a cache

4. Leak in third party library or the application server

5. Bugs in the JDK.

6. In an infinite application code loop.

7. Leaking memory in the native code

9. Session data is too large.

 

Saturday, 4 July 2015

How To Convert Integer To String In Java


public class IntToString {

    public static void main(String[] args) {
         int num = 10;
      
       // method first
     
       String str1 = Integer.toString(num);
     
        System.out.println(" String is ="+str1);
       
        // method second
   
       String str2 = String.valueOf(num);
   
        System.out.println(" Striing is ="+str2);
  
   }

}

Monday, 29 June 2015

How to find all occurrences of string in a string Java

 Find all occurrences of string in a string. for this we will use one loop and indexof() method

public class StringCheck {
   
    public static void main(String[] args) {
       
        String str = "delhi is good city in india and india also good. there are many city good and people also good" +
                "so india is good country ";
        String mystr = "good";
        int index =0;
   while(index != -1){
       index = str.indexOf(mystr, index+1);
        System.out.println("index is = "+index);
   };
       
    }
}

Output:

index is = 9

index is = 43

index is = 69

index is = 90

index is = 106

index is = -1

Thursday, 7 May 2015

Check Array Element Even or Odd


Check Array Element  Even or Odd In Java

public class PrintEvenOrOdd {
    public static void main(String[] args) {
       int arr[]={10,2,5,21,37,48};
       for (int i = 0; i < arr.length; i++) {
        System.out.println("element ="+arr[i]+" is even="+isEven(arr[i]));
       }
    }
    private static boolean isEven(int n){
        return((n%2)==0);
    }
}


Output:

element =10 is even=true
element =2 is even=true
element =5 is even=false
element =21 is even=false
element =37 is even=false
element =48 is even=true

Thursday, 23 April 2015

How to Install Java In Ubuntu

Installing default JRE/JDK

 Step 1:
  
       sudo apt-get update
Step 2:
      sudo apt-get install default-jre  
Step 3:
  sudo apt-get install default-jdk
   
Step 4:

 java -version


Installing OpenJDK 7

 Step 1:

sudo apt-get install openjdk-7-jre

Step 2:

sudo apt-get install openjdk-7-jdk

 

 

 


 

 

 

 

Sunday, 5 April 2015

RESTful Web Services with Java (JAX-RS) using Jersey PUT Method Example


RESTful Web Services Using PUT Method Using Jersey
 
If we are use PUT method then need a client to run application . you have any client then ok.if you have not any idea about client then you first learn about client. There are many client postman,rest console etc. But I have use rest console client , for rest console client tutorial click here

So now i consider that you can use rest console client .

now follow these step for make a rest application using put method

Step 1: create handle class and define path , method and response.

UserHandler.java

package com.javaproficiency.jerseydemo.demo;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

@Path("/user")
public class UserHander {
 
/*
 Use @PUT annotation here
    */
    @PUT
    public Response getMessage(){
        String message="Jersey Hello";
        return Response.status(Status.OK).entity(message).build();
    }
   
}

Step  2. configure web.xml file as

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JerseyDemo</display-name>
    <servlet>
        <servlet-name>RestServices</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.javaproficiency.jerseydemo.demo</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>RestServices</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Step 3. Add dependency in pom.xml file as bellow.
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>JerseyDemo</groupId>
    <artifactId>JerseyDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.13</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.13</version>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <scope>provided</scope>
            <version>2.16</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-servlet</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-simple-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-servlet</artifactId>
            <version>2.16</version>
        </dependency>
    </dependencies>

</project>

Step 4:   Project Structure





 Step 5: Run Project and Hit url

How to decide url:

HostName:PortNumber/ProjectName/+Your Decide Path

Example:

http://localhost:8080/JerseyDemo/rest/user

   

                               


Output:










RESTful Web Services with Java (JAX-RS) using Jersey Example


Rest services with java(JAX-RS) using jersey example tutorial


Step 1: create handle class and define path , method and response.

UserHandler.java

package com.javaproficiency.jerseydemo.demo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

@Path("/user")
public class UserHander {

    @GET
    public Response getMessage(){
        String message="Jersey Hello";
        return Response.status(Status.OK).entity(message).build();
    }
   
}

Step  2. configure web.xml file as

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JerseyDemo</display-name>
    <servlet>
        <servlet-name>RestServices</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.javaproficiency.jerseydemo.demo</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>RestServices</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Step 3. Add dependency in pom.xml file as bellow.
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>JerseyDemo</groupId>
    <artifactId>JerseyDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.13</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.13</version>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <scope>provided</scope>
            <version>2.16</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-servlet</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-simple-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>2.16</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-servlet</artifactId>
            <version>2.16</version>
        </dependency>
    </dependencies>

</project>

Step 4:   Project Structure





 Step 5: Run Project and Hit url

How to decide url:
 
HostName:PortNumber/ProjectName/+Your Decide Path

Example:

http://localhost:8080/JerseyDemo/rest/user

                               

Download Project  JerseyDemo-Project