Monday, 30 November 2015

Method Overriding Example - Java Program

package com.javaproficiency;


class Y {

void display(){
System.out.println(" Y is called");
}

}


public class X extends Y{

void display(){
System.out.println(" X is called");
}


public static void main(String[] args) {

    Y y = new Y();
    X x = new X();
    Y obj = new X();
   
    y.display();
    x.display();
    obj.display();
   
   

}

}



Output:

 Y is called

 X is called

 X is called

How to Find Common Element In Two arrays - java program

package com.javaproficiency;

public class CommonElementOfTwoArray {

public static void main(String[] args) {

  int []arr = {10,15,20,25,40};
       int []brr ={5,18,20,25,30,10};
     
       for( int i=0 ; i < arr.length ; i++ ){
            for( int j=0 ; j < brr.length ; j++  ){
                if(arr[i] == brr[j])
                    System.out.println(arr[i]);
            }
       }

}

}


Output:

10
20
25








Thursday, 26 November 2015

How to count the number of occurrences of a character in a string in java

Count the number of occurrences of a character in a string is good programming questions . It is ask in colleges and schools mostly. This question also asked in many times in interviews. 

Method 1:

We can count number of occurrences of a character in a string with the help of indexOf() method.

package com.javaproficiency;

public class CountCharOccurance {
public static void main(String[] args) {
String str = "javaproficiencyexamplebyannu";
 
    String findStr = "a";
    int lastIndex = 0;
    int counter = 0;
 
    while (lastIndex != -1) {
 
     lastIndex = str.indexOf(findStr, lastIndex);
 
     if (lastIndex != -1) {
      counter++;
      lastIndex += findStr.length();
 
     }
    }
    System.out.println(counter);
}


}


Output: 

4


Method 2:

In this example we will use charAt() method of string for count number of occurrences of a character in a string .

package com.javaproficiency;

public class CountCharOccurancejava {
public static void main(String[] args) {
String s = "javaproficiencyexamplebyannu";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
   if( s.charAt(i) == 'a' ) {
       counter++;
   } 
}
System.out.println( counter );
}

}


Output:

4


How to print numbers from 1 to 10 without using loop?

We can print numbers 1 to 10 or 1 to 100 using recursion. Recursion is a good alternatives of loop. There we can use recursion to print numbers 1 to 10. We also use goto statement but in java we can not used goto statement. visit java keyword list http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html. So we will use here recursion.


package com.javaproficiency;

public class PrintNumber {

public static void main(String[] args) {

printNumberWithRecursion(1);

}

public static void printNumberWithRecursion(int n){

if (n <= 10) {
System.out.println(" number is ="+ n);
printNumberWithRecursion(n+1);
}

}

}


Output :

 number is =1
 number is =2
 number is =3
 number is =4
 number is =5
 number is =6
 number is =7
 number is =8
 number is =9
 number is =10

How to Sort the String using string Method In java

Java have a lot of method for string operations. We can sort a string by convert in to array of characters , now we will sort array after that we will make a new string from sorted array.Now our new string is in sorted order of characters.

package com.javaproficiency;

import java.util.Arrays;

public class StringSort {

public static void main(String[] args) {
String str = "xyabds";
char [] arr = str.toCharArray();
Arrays.sort(arr);
String sortedStr = new String(arr);
System.out.println(" sorted string = "+sortedStr);
}

}

Output:

 sorted string = abdsxy

Wednesday, 25 November 2015

Object Cloning in java example?

package com.javaproficiency;

public class Emp implements Cloneable {
//Object Cloning in java example?

int id;
String name;

public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}

public Emp clone() throws CloneNotSupportedException{

return (Emp ) super.clone();

}

public static void main(String[] args) {

Emp  emp = new Emp(10, "java");
Emp emp1 = null;
try {
emp1 = emp.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(" clone object is ");
System.out.println("id ="+ emp1.id+ " name ="+ emp1.name);

}

}


Output:

 clone object is
 id =10 name =java




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 reverse a number in java

package com.javaproficiency;

public class ReverseNumber {

public static void main(String[] args) {
int num =251;
int rNum =0;
while(num > 0){
rNum = rNum*10+ num%10;
num = num/10;
}
System.out.println(" reverse number is ="+rNum);
}
}


Output:

 reverse number is =152

How to Check number is prime or not


A number which is divided by one and itself is called prime number. For Example

7 is a prime number and
8 is not a prime number

package com.javaproficiency;

public class PrintPrime {

public static void main(String[] args) {
int i =101;
boolean flag = false;
for(int j=2 ; j <= i/2; j++){
if(i%j==0)
{
flag = true ;
break;
}
}
if(flag){
System.out.println(" number "+ i +" is not prime");
}else{
System.out.println(" number "+ i +" is  prime");
}

}

}


Output :

 number 101 is  prime

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

Monday, 23 November 2015

Activator Eclipse Command is not working In PlayFramwork

When i run 


activator eclipse

command then i get following error.

[info] Set current project to demo (in build file:/home/anuj/playapp/demo/)
[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
[error]        ^

How can i import scala project to eclipse ?

I run this command for scala project import to eclipse . But when i run activator eclipse command , i get error.

Solution:

Go to project folder inside your project and Append this below to your plugins.sbt file:

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0")

now run again

activator eclipse command and you will run this command now successfully. After that you can import this project to eclipse.





Saturday, 21 November 2015

java.lang.UnsupportedClassVersionError: com/typesafe/config/ConfigException : Unsupported major.minor version 52.0

java.lang.UnsupportedClassVersionError: com/typesafe/config/ConfigException : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at com.typesafe.sbt.web.SbtWeb$$anonfun$com$typesafe$sbt$web$SbtWeb$$load$1.apply(SbtWeb.scala:535)
    at com.typesafe.sbt.web.SbtWeb$$anonfun$com$typesafe$sbt$web$SbtWeb$$load$1.apply(SbtWeb.scala:535)
    at scala.Option.fold(Option.scala:157)
    at com.typesafe.sbt.web.SbtWeb$.com$typesafe$sbt$web$SbtWeb$$load(SbtWeb.scala:549)
    at com.typesafe.sbt.web.SbtWeb$$anonfun$globalSettings$1$$anonfun$apply$1.apply(SbtWeb.scala:143)
    at com.typesafe.sbt.web.SbtWeb$$anonfun$globalSettings$1$$anonfun$apply$1.apply(SbtWeb.scala:143)
    at scala.Function1$$anonfun$andThen$1.apply(Function1.scala:55)
    at sbt.Project$.setProject(Project.scala:319)
    at sbt.BuiltinCommands$.doLoadProject(Main.scala:484)
    at sbt.BuiltinCommands$$anonfun$loadProjectImpl$2.apply(Main.scala:475)
    at sbt.BuiltinCommands$$anonfun$loadProjectImpl$2.apply(Main.scala:475)
    at sbt.Command$$anonfun$applyEffect$1$$anonfun$apply$2.apply(Command.scala:58)
    at sbt.Command$$anonfun$applyEffect$1$$anonfun$apply$2.apply(Command.scala:58)
    at sbt.Command$$anonfun$applyEffect$2$$anonfun$apply$3.apply(Command.scala:60)
    at sbt.Command$$anonfun$applyEffect$2$$anonfun$apply$3.apply(Command.scala:60)
    at sbt.Command$.process(Command.scala:92)
    at sbt.MainLoop$$anonfun$1$$anonfun$apply$1.apply(MainLoop.scala:98)
    at sbt.MainLoop$$anonfun$1$$anonfun$apply$1.apply(MainLoop.scala:98)
    at sbt.State$$anon$1.process(State.scala:184)
    at sbt.MainLoop$$anonfun$1.apply(MainLoop.scala:98)
    at sbt.MainLoop$$anonfun$1.apply(MainLoop.scala:98)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
    at sbt.MainLoop$.next(MainLoop.scala:98)
    at sbt.MainLoop$.run(MainLoop.scala:91)
    at sbt.MainLoop$$anonfun$runWithNewLog$1.apply(MainLoop.scala:70)
    at sbt.MainLoop$$anonfun$runWithNewLog$1.apply(MainLoop.scala:65)
    at sbt.Using.apply(Using.scala:24)
    at sbt.MainLoop$.runWithNewLog(MainLoop.scala:65)
    at sbt.MainLoop$.runAndClearLast(MainLoop.scala:48)
    at sbt.MainLoop$.runLoggedLoop(MainLoop.scala:32)
    at sbt.MainLoop$.runLogged(MainLoop.scala:24)
    at sbt.StandardMain$.runManaged(Main.scala:53)
    at sbt.xMain.run(Main.scala:28)
    at xsbt.boot.Launch$$anonfun$run$1.apply(Launch.scala:109)
    at xsbt.boot.Launch$.withContextLoader(Launch.scala:128)
    at xsbt.boot.Launch$.run(Launch.scala:109)
    at xsbt.boot.Launch$$anonfun$apply$1.apply(Launch.scala:35)
    at xsbt.boot.Launch$.launch(Launch.scala:117)
    at xsbt.boot.Launch$.apply(Launch.scala:18)
    at xsbt.boot.Boot$.runImpl(Boot.scala:41)
    at xsbt.boot.Boot$.main(Boot.scala:17)
    at xsbt.boot.Boot.main(Boot.scala)
[error] java.lang.UnsupportedClassVersionError: com/typesafe/config/ConfigException : Unsupported major.minor version 52.0
[error] Use 'last' for the full log.

solution:

Still you are using java7. You can download java8. If you already install java8 make sure it is active.You can change java version using bellow commands.

How To Change Java Version 

 

$ sudo update-alternatives --config java

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1061      auto mode
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1061      manual mode
  2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1051      manual mode

Press enter to keep the current choice[*], or type selection number: 2

update-alternatives: using /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
to provide /usr/bin/java (java) in manual mode
 
 Now you can check you java version using below command

java -version




Thursday, 19 November 2015

How to sort a TreeSet with user defined objects In Java


TreeSet have element in their natural ordering. If we make a TreeSet of Sting it have elements in alphabetical ascending order visit example here . If we want to own sorting with TreeSet on user defined objects , have to pass Comparator object along with TreeSet constructor call. The Comparator implementation holds the sorting logic. You have to override compare() method to provide the sorting logic on user defined objects. I have given examples sorted TreeSet of user defined object based on String(name) and Integer(rollNo).

package com.treesetsort;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetSort {
public static void main(String[] args) {
TreeSet<Stu> nameSort = new TreeSet<Stu>( new StuNameComp());
nameSort.add(new Stu("yogesh", 10));
nameSort.add(new Stu("shivam", 50));
nameSort.add(new Stu("amit", 30));
nameSort.add(new Stu("pankaj", 35));
System.out.println("printed sorted treeset base on name of student type object");
for (Stu stu : nameSort) {
System.out.println("name ="+ stu.getName()+ " roll No ="+ stu.getRollNo());
}
System.out.println("+++++++++++++++++");
TreeSet<Stu> rollNoSort = new TreeSet<Stu>( new StuRollComp());
rollNoSort.add(new Stu("yogesh", 10));
rollNoSort.add(new Stu("shivam", 50));
rollNoSort.add(new Stu("amit", 30));
rollNoSort.add(new Stu("pankaj", 35));

System.out.println("printed sorted treeset based on roll no of student type object");
for (Stu stu : rollNoSort) {
System.out.println("name ="+ stu.getName()+ " roll No ="+ stu.getRollNo());
}
}
}

class StuNameComp implements Comparator<Stu>{
@Override
public int compare(Stu s1, Stu s2) {
return s1.getName().compareTo(s2.getName());
}
}
class StuRollComp implements Comparator<Stu>{

@Override
public int compare(Stu s1, Stu s2) {
if(s1.getRollNo() > s2.getRollNo()){
return 1;
} else {
return -1;
}
}
}

class Stu {
private String name;
private int rollNo;
public Stu(String name, int rollNo) {
super();
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}



Output:

printed sorted treeset base on name of student type object
name =amit roll No =30
name =pankaj roll No =35
name =shivam roll No =50
name =yogesh roll No =10

+++++++++++++++++

printed sorted treeset based on roll no of student type object
name =yogesh roll No =10
name =amit roll No =30
name =pankaj roll No =35
name =shivam roll No =50



Related Posts: 

How to create TreeSet In Java

How to Convert a TreeSet to ArrayList

How to convert array to TreeSet

How to sort TreeSet with user defined objects.

How to copy all element of a Treeset to other 

How To Remove Element of Treeset 

How to remove all element from TreeSet

How to Remove Set From TreeSet 

How To Convert Treeset To Array 

How to find does TreeSet contains elements or not 

How to count number of element in TreeSet

How to check TreeSet Empty Or not


Saturday, 7 November 2015

Scala Variables

Variable is a name of reversed memory area of any values. In scala we can declare a variable with var and val keywords.

Declare variable with var :


Variable declare with var can change value.This type variable called mutable.

Syntax:

var varName : datatype = Initial value

ex: var age : int = 10

or we also use below syntax to declare variable
var age =10

In this case we can change the value of age.

Exampe:


object variable {

def main(args: Array[String]) {
var age : Int =10;
var name = "scala";
println(" age="+age +"name ="+name);
//now we will change the values og age and name
age =30;
name="java";
println("after changing the values of age and name");
println("age="+ age+"name ="+name);
}
}

Output:

age=10 name =scala
after changing the values of age and name
age=30 name =java


Declare variable with val:


Variable declare with val can not their value.This type variable called immutable.

Example:

val variableName : datatype = Initial value

or

val varaibleName = Initial value

Example:

object ValVaraible {
def main(args: Array[String]) {
val age : Int =10 ;
println("age="+ age);
// age = age+10 // we can not change value of val type varaibles
}
}

Output:

age=10

we can not change of value of val type variable. They behavior  like constant.


Multiple assignments:


Scala support to multiple assignments. We can assign multiple variable in a tupple.

Syntax:

val (var1: Int, var2: String) = Pair(10, "scala")

And the type inferencer gets it right:

val (var1, var2) = Pair(10, "java")

Example:

object mulAssign {
def main(args: Array[String]) {
val (val1: Int, val2: String) = Pair(10, "scala");
println(" val1 ="+val1 +" val2 ="+ val2);
}
}

Output:

val1 =10 val2 =scala

Variable Type:


variables in scala are three type fields , method parameter and local variables.

Fields:


Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with. Fields can be both val's and var's.

Method parameters:


Method parameters are variables which values are passed to a method when the method is called. Method parameters are only accessible from inside the method - but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always val's.we can say method parameter is immutable.

Local variables:


local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both var's and val's








Friday, 6 November 2015

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

When i run my project ,I get exception

 ClassNotFoundException : org.springframework.web.context.ContextLoaderListener

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:506)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:488)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:115)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4919)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)



Solution:    Step 1: 

                    Firstly right click on project and goto build path or  .Click on deployment Assembly now you see screen as  below . click on  add button. 








Step 2: Now click on Java Build Path Entries and press Next Button





Step 3:  Now add Maven Dependencies on click Finish Button.

           


 

Step 4:    Apply maven dependencies.

     




I hope Now you can run your project successfully.





Related Post :


Spring Tutorial


Spring MVC EXample