Search This Blog

Sunday, 30 May 2021

Difference between a tuple and collection in scala

 

Difference between Tuple and Collections in Scala :


1. Tuple store heterogenous data, means it can store different data types at a time. Where as collection stores same data type.

2. If we want to return two values from a function, lets say, we would like to return 1 and "Scala" at a time from a function we can use Tuple.

3. At max tuple can store 22 elements, But Collection can store more than 22 elements ( No restriction).



Wednesday, 5 May 2021

Differences between creation of string in java string s = "abc" and String s= new String("abc")

 

 

String s = “abc”

String s = new String(“abc”)

Why?

Creation of string literals are the preferred way in java

At times, we may wish to create separate instance for each separate string in memory. We can create one string object per string value using new keyword.

If we create many strings with same char sequence assume

String s = “abc”

String s1 =”abc”

String s2 = “abc”

All these variables will have same reference, we will not create the string again with same value in memory , this will save lot of memory in runtime.

If we create

String s = new String(“abc”)

String s1 = new String(“abc”)

String s2 = new String(“abc”), then we will create different objects/instances in heap memory.

The strings that are created with string literals are stored in special memory in heap memory called string pool. String literals are stored in String pool, a special memory area created by JVM

The strings created with new operator will be stored in heap memory but not in string pool

 

String s1 =”abc”, If we try to create same object , will have the reference of first string stored in string pool Which is existing in pool already.

String s1= new string (“abc”)

String s2 = new String (“abc”)

Different objects with different references will be created in heap momory.

 

String literals are stored in string pool

String objects are stored in head memory.

 

A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored.

When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap

 

 

 

 

 

 

 

 

 

 

String str1 = "Hello";

Lightbox

 

 

String str1 = "Hello";
String str2 = "Hello";

Lightbox

 

 

 

 

String str1 = "Hello";
String str2 = "Hello";
String str3 = "Class";

 

 

String str1 = new String("John");
String str2 = new String("Doe");

 

Regards,

Swathi.

 

Wednesday, 28 September 2016

SingleTon Pattern, how can we restrict in serialization to create multiple objects

SingleTon Pattern :

Questions will be anserwed in this post
What is Singleton
Why do we need SingleTon
How can a class behaves singleTon
How can we fail singleton concept through serialization, how can we solve it..

For a given class, if only one instance needs to be created, we will go for this pattern.
why is SingleTon needed :  there are some requirements, where only one class needs to be created, for example, database connection object,
for an application, only one database is needed, for this kind of situations, we go for singleTon.

 If we restrict constructor as private , no one can create object,
 instead provide one method to give instance, this method will create a object if it didnt exists, else creates object and returns it.
 public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}





Through Serialization, lets say we need to serialize singleTon class, and deserialize n number of times , you can get n number of objects, which is failing singleTon principle, How can we restrict this

In order to make serialization and singleton work properly,we have to introduce readResolve() method in the singleton class.readResolve() method lets developer control what object should be returned  on deserialization.
For the current SingleObject singleton class,readResolve() method will look like this.


     /**
  * Special hook provided by serialization where developer can control what object needs to sent.
  * However this method is invoked on the new object instance created by de serialization process.
  * @return
  * @throws ObjectStreamException
  */
 private Object readResolve() throws ObjectStreamException{
  return INSTANCE;
 }
You need to implement readResolve method in your Singleton class. This small thing is used to override what serialization mechanism has created. What you return there will be used instead of data that came from serialization
 but readResolve will work properly only if all fields are transient,


The best way to do this is to use the enum singleton pattern:

public enum SingleObject {
  instance;
}


more details will be posted further

Tuesday, 27 September 2016

Different ways of creating an Object in Java

Here are the 5 different ways to create object in Java,
1. new Operator
2. Using Class.forName("class").newInstance()
3.Using de serialization  (by using ObjectInputstream readObject method)
4.using clone method
5.using newInstance method.

package com.test.objectcreation;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Add implements Cloneable {
    public int number = 1;

    public int add(int a, int b) {
        return a + b;
    }

    public int change() {
        number = 2;
        return number;
    }

    public static void main(String args[]) throws InstantiationException, IllegalAccessException,
            CloneNotSupportedException, ClassNotFoundException, IOException {
        Add add = new Add(); // creation of object with new operator
        System.out.println(add.add(2, 3));

        Add a = Add.class.newInstance();// creation of object with newInstance
                                        // method
        // System.out.println(a.getName());
        // System.out.println(a.getMethod("add", "2","3"));
        System.out.println(a.add(2, 3));
        a.change();
        Add b = (Add) a.clone(); // creation of object using clone, Class needs to implement clonenable, otherwise you  will get clonenotsupportedException and you need to typecast to class to which you need to clone.
        System.out.println(b.add(2, 3));
        System.out.println(b.toString());
        System.out.println("static int in object a :" + a.number);
        System.out.println(a.toString());
        System.out.println("static int in object b (cloned object) :" + b.number);
        FileInputStream fileIn = new FileInputStream("/E/Add.txt");
        ObjectInputStream in = new ObjectInputStream(fileIn);// here reading serializable object which stored in add.txt file, we are creating Add  classinstance,used mostly for deserialization.

        Add e = (Add) in.readObject();// reading object and type casting.
        in.close();
        fileIn.close();

        Class s = Class.forName("com.test.objectcreation.Add");// using forName
        Add obj = (Add) s.newInstance(); // we are creating object from Object s
        System.out.println(obj.hashCode());
    }

}

Wednesday, 9 March 2016

How can we call Function in Scala

Here are couple of scala points

  • You can call a function without using . operator example : emp getName , Here emp is the object getName is function, just by giving space you can call the function.
  • No need to provide braces after the function Name, unlike in java we use paranthesis (getName()).

Wednesday, 9 December 2015

Ignore JUnit Test Case

How can we stop a test case not to run??


Dont use java comment to comment the test case function,
Please use @Ignore annotation to comment test case,


Example


on function level


@Ignore("not ready yet")
@Test public void testOnething() {
System.out.println("This method is ignored because its not ready yet");
}


on class level

@Ignore public class Ignored {
@Test public void test1() {
System.out.println("Ignored test case 1");
}
@Test public void test2() {
System.out.println("Ignored test case 2");
}
 }

Monday, 7 December 2015

How to turn off interactive prompt while sending bulk files to an ftp server



When we want to send 1000 number of files at a time to an ftp server,

We will use mput *, but for every file it will ask you to enter yes or no to transfer the file,
to avoid this,
use command prompt.

Example below

ftp hostname
username : username
password : password
prompt (this will turn off interactive mode)

now you use mput * to send all files .


Wednesday, 24 September 2014

Hibernate Introduction



  • Hibernate is an ORM (Object Relational Mapping) Tool
  • Hibernate is Open Source
  • Hibernate is used to persist data to Databases
  • Hibernate was started in 2001 by Gavin King
  • ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables,instances are mapped to rows and attributes of instances are mapped to columns of table.
  • Using Hibernate we can save data from Java Applications to Databases. This acts a medium between Java and Database. 

Wednesday, 12 September 2012

Unix Command passwd

One of the Unix Commands which is useful our day to day life is passwd. We will learn now how to use this command.

To change your password this command is useful.
How to change a password for your login:

Login to unix machine with your login id and enter your password
Now if you want to change the current password  passwd command is used to change password.
Type passwd in your command prompt:
Now machine will ask you to enter your current password,please enter it, then it will ask for new password
please enter new password ,the machine will ask again to confirm the new passward please enter it.

Now you changed your password now.

Tuesday, 28 August 2012

Email and URL validation in Javascript using Regular Expression

JavaScrip URL & Email Validation
Enter Valid URL :
Enter Valid Email :

Sunday, 18 December 2011

Difference between Statement and Prepared Statement

Statement:

When you use normal statements compilation of statement or
parsing of statement will happen every time. This is time
consuming when u have multiple queries to execute.

Statement s = conn.createStatement();
s.executeQuery();

Prepared Statement:
In prepared statement SQL query will be compiled or parsed
for the very first time and kept in some kind of pool. When
u execute one more time the same statement with different
values it saves the parsing time.

The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement.

The PreparedStatement may be parametrized.
Prepared statement is precompiled statement it is used when
we want one query to be executed n no. of times.
Prepared Statement is Pre-compiled class , but Statement is not.
So in PreparedStatement the execution will be faster.

SQL select * from employee where employeeID=?,empName=?;
PreparedStatement ps = conn.PreparedStatement();
ps.execute(1,aru);
ps.execute(2,arya);

Callable Statement:

Callable statements are used to execute stored procedures
similar to java functions.

Tuesday, 6 December 2011

Object Class functions in java

Object Class
Object Class is the Super class for all classes in JAVA.The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
The Object Class Functions:
equals:
This function is used to compare two objects whether they have equivalent values are not.
It returns true if they are equal else returns false.
The getClass() Method:
The getClass method is a final method (cannot be overridden)
This method returns a Class object.With this class you can get the information of object like name, its super class, and the names of the interfaces that it implements.
use of the getClass method is to create a new instance of a class without knowing what the class is at compile time. This sample method creates a new instance of the same class as obj which can be any class that inherits from Object (which means that it could be any class):
Object createNewInstanceOf(Object obj) {
return obj.getClass().newInstance();
}
The toString Method
Object's toString method returns a String representation of the object. You can use toString to display an object.
The Object class also provides five methods that are critical when writing multithreaded Java programs:
• notify
• notifyAll
• wait (three versions)
hashCode()
Returns a hash code value for the object.
finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Thursday, 1 December 2011

System.out.println

Some people dont know what is System,out,println in System.out.println.
As per my Knowledge,

System is a class in java which is final class(Final will stop inheritance)

out is a static final PrintStream object that is in System Class
And println is a function in PrintStream class
Since out is a static object with out creating object we can access
directly
As
System.out.println();

Thursday, 29 September 2011

Basics of Tables in MYSQL


A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns.

Example:Suppose you want to store the details of your company employees.
Generally Employees will have name, employee id,address.these properties we will represent them as columns.And the data of each employee will be as one Row.

Thursday, 23 June 2011

Example on Java script

Most of the people are thinking about programming language java and java script are
same.But they are different.
Java script is mainly used for client side validations,not only this we can have so many uses from java script.

Thursday, 5 May 2011

Overloading And Overriding Concepts

Method Overloading:
Method overloading in Java is nothing but two or more functions having same function name but with different parameters and signatures.

This can be implemented by compile time polymorphism


Method Overriding:


Method overriding in java is nothing but the function present in super class is overrides the function in sub class in other way add additional functionality to the function in super class
One thing to be noted down is
the function names in super class and sub class are same with signatures also..
Method overriding can be implemented by runtime polymorphism.

Tuesday, 19 April 2011

Interface

Interface:
An interface in the java programing is an abstract type.
Interface can have variables and methods.
variables in interface are final,means the variables are constant,
and the methods dont have any definition.
An interface is declared as
interface interfacename
{
//variables
//method names with out any body definition
}
For an interface we cannot create any object for it.
If we want to create object we need to implement this interface through a class.
and the implemting class should all the methods in interface if not the class becomes abstract.
An interface can implement another interface also.


Thursday, 14 April 2011

Types of Inheritance

1.Simple inheritance
Simple inhertance means one class extends the the class
Example
Class B extends A
B is the sub class and A is sub class
2.Multiple inheritance
Java implements multiple inheritance through interfaces but not through classes
multiple inheritance example
interface A
interface B
class C implements B,A
so multiple inheritance means one class can have one or more super classes.
3.Hybrid inheritance:
Suppose take an example
class A
class B extends A
class C extends B
means here class C has two super class B inturn B has a super class A
Advantages of inheritance
Main advantage of inheritance is code reusability
means the code in one class can be reused with out writing the code again.

Wednesday, 13 April 2011

Inheritance

This is one of the important Oops. concept.
what is inheritance:
Aquiring the properties of one object class to another object class is called inheritance.
Means suppose take an example of  mother and child,some of the mother features will come to child.
Like this only in java suppose take class A it contains a variable test as int data type.
and a method function as display with return type void.
now take another class B it extends Class A means A is super class and now B is subclass
now B class will contain variable test and function display.
syntax of this is as follows......
Class A
{
//variables and functions
}

Class B extends A
{
//you can add your own functions also here
}
I will post the types of inheritance in my next post...

Class

A class is a blueprint or prototype from which objects are created.
In a class we can have class variables and methods.
Through these methods we can do operations on variables as per the requirement.
A class can be public private.
public class can access outside the package also but not the private class
A class can be abstract, final static.