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





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.






Monday, 2 November 2015

Java - Variable Types With Example

Variable is a name of reversed memory area of any values. In java values of variable can be change during execution of program.
In java there is three type variable

1. Local variable
2. instance variable
3. static variable

1. Local Variable :


i. Variable declare inside method is called local variable.
ii. These variable only access inside the specific method/block/constructor.
ii. Access modifiers cannot be used for local variables.

public class LocalVariable {
public static void main(String[] args) {
        LocalVariable localVariable = new LocalVariable();
       localVariable.display();
 }

     public void display(){
             int i = 10;// Local Varaible
             System.out.println(" i ="+i);
       }
}

Output:
 i =10

2. Instance variable :


i. Variable declare inside the class but outside method is called instance variable .
ii. Instance variable belongs to object , not to class.
Iii. Access modifiers can be used for instance variables.

public class InstanceVariable {
int i =20;
public static void main(String[] args) {
InstanceVariable instanceVariable = new InstanceVariable();
System.out.println(" instance variable ="+ instanceVariable.i);
}
}


Output :
instance variable = 20


3. Static Variable :


i. Variable declare inside class with static keyword is called static variable .
ii. Static variable can not local.
iii. Static variable belogs to class ,not to object.
iv. Access modifiers can be used for static variables.
v. Static varible access as ClassName.StaticVariableName

public class StaticVariable {
static int i =100;
public static void main(String[] args) {
System.out.println("price of bag is ="+ i);
}

}

Output :

price of bag is =100




Related Posts:




Exception Hanlding


File Handling

Thursday, 15 October 2015

How to convert JSON to / from Java Object Gson Example

Today we will learn how to use Gson, JSON library, to convert json to/from java object.
JSON is stand for JavaScript Object Notation

we will use gson library's two method for this purpose

1. fromJson() – Convert JSON into Java object
2. toJson() – Convert Java object to JSON format

Firstly i have create a maven project and add gson dependency in pom

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>

if you will create java project then download gson jar.

Step 1: Cretae a pojo 


package com.jp.json;

public class Student {
private int id;
private String  name;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}


Step 2:   Convert JSON to Java Object Gson Example


package com.jp.json;

import com.google.gson.Gson;

public class JSONToObject {

public static void main(String[] args) {

String json = "{\"id\":1," +
" \"name\" : \"json\" }";

System.out.println(" json string ="+json);
Gson gson = new Gson();

Student stu = gson.fromJson(json, Student.class);

System.out.println(" values of java object ");

System.out.println(" id ="+ stu.getId() +" name ="+ stu.getName());

}

}


Output:

 json string ={"id":1, "name" : "json" }
 values of java object
 id =1 name =json


Step 3:   convert Java Object To JSON  Gson Example


package com.jp.json;

import com.google.gson.Gson;

public class ObjectToJSON {

public static void main(String[] args) {

Student stu = new Student();
stu.setId(10);
stu.setName("java");

System.out.println(" values of java object ");
System.out.println(" id ="+ stu.getId() +" name ="+ stu.getName());

Gson gson = new Gson();

String json = gson.toJson(stu);

System.out.println(" json string ="+ json);



}

}




Output:

 values of java object
 id =10 name =java
 json string ={"id":10,"name":"java"}




Related Posts:



How To Read JSON In Java (Set 1) 

How To Read JSON In Java (Set 2) 

How To Read JSON In Java (Set 3) 





Wednesday, 7 October 2015

Java8 Tutorial



      Java8 Tutorial
      Java8
      Java8 Enhancement to interfaces
      Lambda Expression
      Anonymous classes vs Lambda expressions
      Predicate interface
      Consumer interface
      Function interface
      Method Reference
      Streams
      Stream operations
      Streams: Searching and finding
      Streams: Reduce operation
      Numeric streams
      Collectors
      Convert stream to collection
      streams: parallel processing
      Optional class: Working with NullPointerException
      New Date and Time API