Tuesday 9 August 2016

Using 'using namespace std;'? But why?

Consider a simple code :

#include <iostream>
using namespace std;

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {

    int a;
    int b;
    a = 7;
    b = 5;
    swap(a, b);
    cout << a << b;

    return 0;
}


Now when you will try to run this code you will find that the compiler doesn't give any error. Again question is why is the compiler unable to find the error?

So this is all due to the 'using namespace std;' basically our own defined method doesn't gets called in the whole program. The std::swap method gets called and the found these values swapped.

Now this is just a small example. When we write big codes then this can be a big pain in our ass. And sorting it our will be difficult unless we are not much experienced.

Don't forget String is immutable in Java

Generally we try to manipulate the String (in Java) as we manipulate std::string in C++. But String is immutable in Java.

Now consider a program where you may need to change all the space with some string literal as "#45", then to solve this problem in place we need to use the char array to store the string. Using the String will result creation of more that one copies of String ( or one copy of String and other char array).

Consider this program :


public class Four {
    
    public static void main(String []args)
    {
        String str = new String();
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        str = scanner.nextLine();
        Four obj = new Four();
        int len = str.length();
        str = obj.changedString(str, len);
        System.out.println("New String Formed : "+str);
        scanner.close();
    }
    
    public String changedString(String str, int len)
    {
        int sCount = 0;
        for(int i = 0; i < len; ++i)
        {
            if (str.charAt(i) == ' ')
                sCount++;
        }
        int newLen = (2*sCount) + len;
        
        char str2[] = new char[newLen+1];
        str2[newLen] = '\0';
        
        for (int i = len-1; i >= 0; i--) 
        {
            if (str.charAt(i) == ' ')
            {
                str2[newLen -1] = '0';
                str2[newLen -2] = '2';
                str2[newLen -3] = '%';
                newLen = newLen-3;
            }
            else
            {
                str2[newLen-1] = str.charAt(i);
                newLen = newLen - 1;
            }
        }
        return new String(str2);
    }
}


So this is not a in place algo. We need to use the char Array to make it in place.

Consider this program written in C++:


/*
program to replace all spaces in a string with '%20'. use inplace algo.
*/
#include<iostream>
#include<cstring>
int countSpaceLength(char *str, int len)
{
    int sCount = 0;
    for(int i = 0; i < len; ++i)
    {
        if(str[i] == ' ')
            sCount++;
    }
    return sCount;
}
int main()
{
    char str[500];
    std::cin.getline(str, sizeof(str));
    std::cout<<std::endl;
    int sLen = strlen(str);
    int sCount = countSpaceLength(str, sLen);
    int newStringLen = sLen + (2*sCount);
    str[newStringLen] = '\0';
    for(int i = sLen-1; i >= 0; --i)
    {
         if(str[i] == ' ')
         {
            str[newStringLen - 1] = '0';
            str[newStringLen - 2] = '2';
            str[newStringLen - 3] = '%';
            newStringLen -= 3;
         }
         else
         {
            str[newStringLen - 1] = str[i];
            newStringLen -= 1;
         }
    }
    std::cout<<"New String Formed "<<std::endl<<str<<std::endl;
    return 0;
}

We can some time use

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or we can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

Thanks

Thursday 30 June 2016

RestAdapter updated to Retrofit in new version of Retrofit v2 API

The RestAdapter class was renamed to Retrofit and the API was completely remade. After the API was completely remade its not only the RestAdapter class changed to the Retrofit class but method like setEndPoint() and many more method has also been changed.
Eg : when we have the dependencies as compile 'com.squareup.retrofit:retrofit:1.9.0', then we use : RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint("http://www.json-generator.com/api/json/get")
        .build();
Later when new version of Retrofit came i.e. Revrofit v2.0 then we have to write this : 
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.json-generator.com/api/json/get").build();

As of now we have the latest version of Retrofit v2.1. To know any updates about latest release of
Retrofit API visit :- http://square.github.io/retrofit/

Sunday 22 May 2016

An editorial on function to find the prime number with least time complexity :)

  • The algorithm can be improved further by observing that all primes are of the form 6m ± 1, with the exception of 2 and 3.
  • This is because all integers can be expressed as (6m + i) for some integer k and for i = −1, 0, 1, 2, 3, or 4; 2 divides (6m + 0), (6m + 2), (6m + 4); and 3 divides (6m + 3).
  • So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6m ± 1 ≤ √n(sqrt(n)).
  • This is 3 times as fast as testing all m up to √n.
    int CheckPrime(unsigned int number) {
        if (number <= 3 && number > 1) 
            return 1;            // as 2 and 3 are prime
        else if (number%2==0 || number%3==0) 
            return 0;     // check if number is divisible by 2 or 3
        else {
            unsigned int i;
            for (i=5; i*i<=number; i+=6) {
                if (number % i == 0 || number%(i + 2) == 0) 
                    return 0;
            }
            return 1; 
        }
    }
  • This code is written in C, in java we don't have unsigned keyword(however in java 8 it is included). 

Wednesday 11 May 2016

Converting char (Primitive Character) to String in Java.

Hi, Today I'm going to tell you 3 ways to convert a primitive char to a String.

First Method:
This one is the simplest a person can think.
String str = "" + 'c';

This internally compiles down to :
String str = new StringBuilder().append("").append('c').toString();

This one is less efficient due to StringBuilder class.

Second Method:
As we cannot invoke toString() on the primitive type char or any other primitive, so we  can create a wrapper class Character and then we can eaily invoke toString() to it.
ex.
char c = 'c';
Character ch = Character.valueOf(c);
String str = ch.toString();

Third Method:
char c = 'c';
String str = String.valueOf(c);

Thanks

Tuesday 10 May 2016

Installing Python3.5.1 on fedora 23

Okay, here I'm going to tell how to install Python 3.5.1 using the source tar and compiling it. Using package manager is a great idea but it doesn't seem to work for me always (it will work surely in ubuntu). Sometime I try this for fedora then it cause me problem. So here I will tell you how to install python3.5.1 by compiling the source.


  • Download the python3.5.1 tar file.
  • Extract it.
  • Change Directory to the Python-3.5.1
  • write './configure' in terminal
  • write 'make' in terminal after the above command executes.
  • write 'make install' in terminal after the above command executes.


And that's it.


Enjoy :)

Bug removed for fedora : Unable to run mksdcard SDK tool

If you are directly installing Android Studio on Fedora or any other Linux system then while installing SDK it gives an error message : 

Unable to run mksdcard SDK tool

This is one big bug and people can easily find its solution for ubuntu but for fedora you need to different libraries to install .
Just copy paste the command below in your terminal and this will solve your problem :

sudo dnf install compat-libstdc++-296 compat-libstdc++-33 glibc libgcc nss-softokn-freebl libstdc++ ncurses-libs zlib-devel.i686 ncurses-devel.i686 ant

Sunday 8 May 2016

Reference variable of parent class can access the overridden method in child class.

Hi,
As we know that the reference variable of parent class storing the object of child class can only access the members of its own class(i.e. the parent class). But you should keep in mind that it can access the overridden method in the child class.

The famous example is given here on oracle docs : - click here

I'm pasting that code snippet here also : -
public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
//The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

The output is : 


The static method in Animal
The instance method in Cat

This proves.

Tuesday 12 April 2016

My First Android app activity_main.xml file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/padding"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.aupadhyay.myfirstapp.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter Details"
        android:layout_marginTop="10dp"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName"
        android:hint="Enter Name"
        android:layout_below="@+id/textView"
        android:layout_marginTop="42dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextPhone"
        android:hint = "Enter Phone Number"
        android:layout_below="@+id/editTextName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="46dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/button"
        android:layout_below="@+id/editTextPhone"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp" />
</RelativeLayout>

My First Android app MainActivity.java file


package com.aupadhyay.myfirstapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText editTextName, editTextPhone;
    Button btnSubmit;

    void initViews()
    {
        editTextName = (EditText)findViewById(R.id.editTextName);
        editTextPhone = (EditText)findViewById(R.id.editTextPhone);

        btnSubmit = (Button)findViewById(R.id.button);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // v = btnSubmit;
                String strName = editTextName.getText().toString().trim();
                String strPhone = editTextPhone.getText().toString().trim();

                Toast.makeText(MainActivity.this, "You Entered : "+strName+" : "+strPhone, Toast.LENGTH_LONG).show();

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        Toast.makeText(this, "MainActivity - onCreate",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "MainActivity - onStart",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "MainActivity - onResume",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "MainActivity - onPause",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this, "MainActivity - onStop",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "MainActivity - onDestroy",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast.makeText(this, "MainActivity - onRestart",Toast.LENGTH_SHORT).show();
    }
}

Saturday 9 April 2016

Example to understand Life Cycle of an Activity in different stages

Below I have written the MainActivity.java file :

package com.aupadhyay.myfirstapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "MainActivity - onCreate",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "MainActivity - onStart",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "MainActivity - onResume",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "MainActivity - onPause",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this, "MainActivity - onStop",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "MainActivity - onDestroy",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Toast.makeText(this, "MainActivity - onRestart",Toast.LENGTH_LONG).show();
    }
}

You need to register this MainActivity.java file in your manifest file (AndroidManifest.xml) with the MAIN action and LAUNCHER category.

You need to see the sequence of the output and then you can get to know about the way of order of execution of the different API's on creation and destruction of the activity.

Saturday 19 March 2016

Stone Paper Scissor game in Java


import java.util.Random;
import java.util.Scanner;

public class Game
{
    private static int userWinningCount, computerWinningCount;
    private int userInput, computerInput;
    public void setUserInput(int userInput)
    {
        this.userInput = userInput;
    }
    public void setComputerInput()
    {
        Random r = new Random();
        computerInput = r.nextInt(3-1+1)+1;// corresponding to r.nextInt(max-min+1)+min;
    }
    public String computerChoice()
    {
        if(computerInput == 1)
            return "Stone";
        else if(computerInput == 2)
            return "Paper";
        else
            return "Scissor";
    }
    public String getResult()
    {
        if(userInput == computerInput)
            return "Tie ";
        else if(userInput == 1 && computerInput == 2)// stone = 1, paper = 2, scissor = 3;
            return "Computer won";
        else if(userInput == 1 && computerInput == 3)
            return "You won";
        else if(userInput == 2 && computerInput == 1)
            return "You won";
        else if(userInput == 2 && computerInput == 3)
            return "Computer won";
        else if(userInput == 3 && computerInput == 1)
            return "Computer won";
        return "You won";// i.e. user has scissor and computer has paper.
    }
    public static void main(String []args)
    {
        String s = "yes";
        Game obj = new Game();
        Scanner input = new Scanner(System.in);
        while(s.equalsIgnoreCase("yes"))
        {
            System.out.println("Ener your choice (Stone, Paper, Scissor)");
            String choice = input.next();
            choice = choice.toLowerCase();
            if(choice.equals("stone"))
                obj.setUserInput(1);
            else if(choice.equals("paper"))
                obj.setUserInput(2);
            else if(choice.equals("scissor"))
                obj.setUserInput(3);
            else
                System.out.println("Enter valid option");
            obj.setComputerInput();
            System.out.println("The computer chose : "+obj.computerChoice());
            if(obj.getResult().equals("You won"))
                userWinningCount++;
            else if(obj.getResult().equals("Computer won"))
                computerWinningCount++;
            System.out.println(obj.getResult());
            System.out.print("Your winning count = "+userWinningCount);
            System.out.print(" and Computer winning count = "+computerWinningCount);
            System.out.println("\n Wanna continue playing game ? (enter yes) ");
            s = input.next();
        }
        input.close();
    }
}

Java program to multiply any number with 7 without using * and + operator


import java.util.Scanner;

public class MultiplyWith7
{
    private Integer num, res;
        //private double res1;// for another solution to this problem
    public void getNum(Integer n)
    {
        num = n;
    }
    public void CalculateResult()
    {
                //res1 = num/((double)1/7);// then print res1
        res = num<<3;
        res = res-num;
    }
    public void showResult()
    {
        System.out.println("The result of "+num+"*7 is : "+res);
    }
    public static void main(String []args)
    {
        MultiplyWith7 obj = new MultiplyWith7();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number : ");
        obj.getNum(input.nextInt());
        obj.CalculateResult();
        obj.showResult();
        input.close();
    }
}

hexadecimal to octal conversion program in java


import java.util.Scanner;

public class HexadecimalToOctal 
{
    private String hex;
    private int dec;
    private String oct;
    public void setHex(String hex)
    {
        this.hex = hex;
    }
    public void getDec()
    {
        dec = Integer.parseInt(hex, 16);
    }
    public void setOct()
    {
        oct = Integer.toOctalString(dec);
    }
    public String getOct()
    {
        return oct;
    }
    public static void main(String []args)
    {
        HexadecimalToOctal obj = new HexadecimalToOctal();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a hexadecimal number : ");
        obj.setHex(input.next());
        obj.getDec();
        obj.setOct();
        System.out.println("The octal equivalent is : "+obj.getOct());
        input.close();
    }
}

Wednesday 17 February 2016

Constructor and problem of initialization in C++


  • Constructor is a member function of a class.
  • The name of constructor is same as the name of the class.
  • It has no return type, so the definition of constructor can not use the return keyword.
  • Normally, if we don't write return type of any function then by default its return type is considered as int.
  • But in case of constructor it has no return type.
  • It must be an instance member function, that is it can never be qualified with static keyword.

How to call constructor?
  • Constructor is implicitly invoked when as object is created.
  • Constructor is used to solve problem of initialization.
What is problem of initialization?
Okay, the answer to this question is the answer to the question " why is it called constructor? "
A constructor makes an object an object., this may sound crazy but yes this is true. As in our normal life we say "become a human" ( i.e. become a good person with good characteristics ). Similarly, the constructor makes an object as a good object.
Consider an example:
class
{
  private:
  int car_number;
  string color;
......
};
Now if we create an object to the class, then the instance member variables will have some garbage values into them and thus we can not point to a particular car. If we would have used a constructor to initialize the car_number and colour, then we can point to a particular car. Thus a constructor makes object as a perfect object. 
So we need to initialize the instance member variable at the time of creation of objects and that can be done by using the constructors.

Important topics in constructor:
  • Default constructor
  • Parametrized Constructor
  • Constructor overloading
  • Copy constructor.

Question on static member variable in C++

Question: What is the output of the program written below ?

#include<iostream>
class Account
{
  private:
    int balance;
    static float roi;
  public:
    void setBalance(int b)
    {
      balance = b;
    }
    void showBalance()
    {
      std::cout<<"Balance is : "<<balance<<std::endl;
    }
    static void setRoi(double r)
    {
      roi = r;
    }
    static void showRoi()
    {
      std::cout<<"Roi is : "<<roi<<std::endl;
    }
};
float Account:: roi;
int main()
{
  Account:: setRoi(3.6f);
  Account:: showRoi();
  Account obj;
  obj.setBalance(9999999);
  obj.showBalance();
  std::cout<<"Size of the Account object is : "<<sizeof obj<<std::endl;
  return 0;
}

Answer :
Roi is : 3.6
Balance is : 9999999
Size of the Account object is : 4

Reason :
The static member variable does not belong to the instance of class(i.e it does not belong to the object of the class). So, the object 'obj' has only on variable contained into it, which is 'balance'. And thus the size of the object 'obj' is 4 (size of an integer),

NOTE: this output is in context with the compiler GCC 5.1

Static member function in C++

Okay, before I start the main portion of the static member function, I would like you to know that a instance (normal) function can assess both the instance member variable as well as the static member variable. So, the question the arise is that "Why do we need static member function?"

Reason for static member function :
If we want to access the private static member variable then we need a member function. Now as we know that static member variable is class member variable i.e it will occupy memory in RAM even if the object of class is not created and if we make a instance(normal) member function then we need a object to call it. Thus the significance of the static member variable will be lost because anyway we are creating an object to access the static member variable. So we need to qualify the member function with static keyword to make it static member function. And now this member function can be accessed without any object of the class.

Example :

static void setValue(float sal)
{
    salary = sal;
}

Special things about static member functions:

  • They can access only static member variables because these functions can be called without any object.
  • If object is present then we can call it in two ways:

    a1.setValue(9999999.5f); // a1 is the object of class people
    people:: setValue(999999.5f);


  • If object is not present then we need to use the second method to call the static member function.


NOTE:
The instance member function can access both the static member variable and the instance member variable.
The static member function can be called with or without objects.