Arrays in JAVA

An array is a collection of variables which are of similar type. Arrays can be accessed with their indexes.

Arrays can be used to store numbers, list of values and other variables.

Consider the following example below :

int[ ] Bitcoin = new int[5];

Here, we are defining an array Bitcoin of integer datatype consisting of 5 Bitcoins.

We can reference each element in the array with an index, say the elements of the array are {5,50,85,22,78}. We can access the 2nd element by using Bitcoin[1]. Note indexing in Java starts at 0.

Let us look into a program to access arrays by referencing:

public class Cryptocurrency {

    public static void main(String[] args) {

        String[ ] Blockchain = { “Amsterdam”, “Berlin”, “Capetown”, “Delhi”};

        System.out.println(Blockchain[2]);

    }

}

Program to calculate length of an array.

public class Coins {

    public static void main(String[] args) {

        int[ ] Bitcoin = new int[5];

        System.out.println(Bitcoin.length);

    }

}

Program to find sum of an array.

public class Coins {

    public static void main(String[] args) {

        int [ ] Bitcoin = {5,50,85,22,78};

        int sum=0;

        for(int k=0; k<Bitcoin.length; k++) {

            sum += Bitcoin[k];

        }

        System.out.println(sum);

    }

}

In this code, the variable sum stores all the variables by adding all the elements of array. Initially the sum is assigned a value of zero. A for loop traverses through the array list because of the expression k<Bitcoin.length, that is the number of elements will be equivalent to a value less than length of the array. Remember, the indexing starts at [0] for arrays.

Printing values of an Array.

public class Coins {

    public static void main(String[] args) {

        int[ ] values = {5,50,85,22,78};

            for (int P: values) {

            System.out.println(P);

        }

    }

}

2D and 3D Arrays

Accessing 2D Array

public class Coins {

    public static void main(String[] args) {

        int[ ][ ] Bitpart = { {77, 55, 34}, {41, 54, 63} };

        int j = Bitpart[1][0];

        System.out.println(j);

    }

}

Accessing 3D Array

public class Coins {

    public static void main(String[] args) {

        int[ ][ ] Bitpart = { {17, 21, 32}, {41,70,44}, {51, 62, 75} };

        Bitpart[0][2] = 32;

        int m = Bitpart[1][0];

        System.out.println(m);

    }

}

Similarly, N dimensional arrays can also be accessed.

Source:1)THE Java™ Programming Language, Fourth Edition

       By Ken Arnold, James Gosling, David Holmes

       2) SoloLearn Online Platform.

Functions and Built-in Functions in Python

Function

A function is the simplest callable object in Python.

NOTE: For Indentation either use TAB space or 4 space characters, never both.

def tax(bill):
“””Adds 25% tax to a restaurant bill.”””
bill *= 1.25
print “With tax: %f” % bill
return bill

def tip(bill):
“””Adds 35% tip to a restaurant bill.”””
bill *= 1.35
print “With tip: %f” % bill
return bill

meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)

Function Syntax

def spam():                                             /*Header*/
“”” This is spam function”””            /* Comment*/
print “Spaceship!”                            /*body*/

spam()

Call and Response

def square(n):
“””Returns the square of a number.”””
squared = n**2
print “%d squared is %d.” % (n, squared)
return squared

square(5)

Parameters and Arguments

A function can require as many parameters as you’d like, but when called the function, it should generally pass in a matching number of arguments.

def power(base, exponent):  # Add your parameters here!
result = base**exponent
print “%d to the power of %d is %d.” % (base, exponent, result)

power(20, 6)  # Add your arguments here!

Functions Calling Functions

A function can call another function.

def n_plus_one(n):
return n + 1

def couple_add(n):
return n_plus_one(n) + 2

Importing Module

A module is a file that contains definitions, including variables and functions, that we can use once it is imported.

import math
print math.sqrt(25)

math includes a number of useful variables and functions, and sqrt() is one of those functions. In order to access math, all you need is the import keyword. When you simply import a module this way, it’s called a generic import.

It’s possible to import only specific variables or functions from a given module. Pulling in just a single function from a module is called a function import.

# Import *just* the sqrt function from math

from math import sqrt

if we want all the variables and functions in a module but don’t want to have to constantly type math then we can use

# Import *everything* from the math module

from math import *

Built-in Functions

max()

The max() function takes any number of arguments and returns the largest one.

>> maximum = max(10,35,64)
>> print maximum

min()

min() function returns the smallest of a given series of arguments.

>> minimum = (10,35,64)
>> print minimum

abs()

The abs() function returns the absolute value of the number it takes as an argument, it gives the number’s distance from 0 on an imagined number line.
>> absolute = abs(-42)
>> print absolute

type()

The type() function returns the type of the data it receives as an argument.

>> print type(42)
>> print type(4.2)
>> print type(‘spam’)

Now let us see the code which returns biggest, smallest and absolute values.

def biggest_number(*args):
print max(args)
return max(args)

def smallest_number(*args):
print min(args)
return min(args)

def distance_from_zero(arg):
print abs(arg)
return abs(arg)

biggest_number(-105, -53, 51, 100)
smallest_number(-106, -55, 54, 105)
distance_from_zero(-104)

These are some of the functions and built-in functions in python.

Basics of Python – Part 2

Start with Basics of Python – Part 1

Dot Notation

Using dot notation with strings.
Let us consider an example where we convert the string to upper case using dot notation.

>>> mysore = “The city is awesome !”

>>> print len(mysore)
>>> print mysore.upper()

Printing strings

>>> print(“This String”)

Printing Variables

>>> Stone_cold = “Stunner”
>>> print(Stone_cold)

Concatenation

Combining strings together is called concatenation . The + operator combine the strings.

>>> print “Indian “+ “Air ” +”Force ”

The space after the word is to make the string look like sentence.

String Conversion

The str() method converts non-strings into strings.

>>> print “Sourav Ganguly scored “+ str(100) + “on his Test Debut”

String Formatting

The % operator after a string combines a string with variables. The % operator will replace  %s in the string with the string variable.

Example 1:
>>> string_1 = “Sourav”
>>> string_2 = “Dada”

>>> print “Indian captain %s is also called as %s.” % (string_1, string_2)

Example 2:

>>> batsman = raw_input(“Who is the batsman?”)
>>> captain = raw_input(“Who is the captain?”)
>>> series = raw_input(“Which series did he win for India?”)

>>> print “The Indian %s and %s Sourav Ganguly won %s series for India.” % (batsman, captain, series)

Date and Time 

We can import datetime function from datetime module.

>>> from datetime import datetime

Current Date and Time

Here is the code to print current date and time.

>>> from datetime import datetime
>>> now = datetime.now()
>>> print datetime.now()

Control Flow

The ability to choose from different situations based on what’s happening in the program.

>>> x = int(input(“Please enter an integer: “))

Please enter an integer: 35

>>> if x < 0:

…     x = 0

…     print(‘Negative changed to zero’)

… elif x == 0:

…     print(‘Zero’)

… elif x == 1:

…     print(‘Single’)

… else:

…     print(‘More’)

if statements, for statements, range fuction, break and continue, else clause loops, pass statements are few of the control flow statements.

Comparators

Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Boolean Operators

AND 

OR 

NOT

Conditional Syntax

The statements used for decision making are called conditional statements.

if condition_1:

statement_block_1

elif condition_2:

statement_block_2

else:

statement_block_3

This post concludes basics of python.

Basics of Python – Part 1

Download the python interpreter from this link . Choose either 3.0 or 2.0 version depending upon your compatibility. In this exercise version 2.0 was used for examples. Based on the current and future trends I would recommend 3.0.

Now let us look into some basic concepts in python programming language.

Variables:

As with most programming languages, assigning a value for a variable is as simple as:
a = 10

Booleans:

The two switch states True or False can be assigned to a variable.
a = True
(or)
a = False

Reassigning variable values:

A variable b = 10 can be given a value as b = 5 in the next line, and the value can be printed using
print b

Indentation:

Indentation is one of the most important aspect of python, either use a Tab space or 4 white spaces but not both. Here’s an example of a simple python function.

def example()
var = 15
return var
print example()

Single-line Comment:

Use # at the beginning of a line to give a single line comment.
# This is a single line comment in python.

Multi-line Comments:

If the comment is more than one line use double inverted comma’s thrice at the start and end of the comment.
“”” This is a multi-line
comment”””

Basic Math Operations:

All basic math operations such as addition(+), subtraction(-), multiplication(*) and division(%) can be performed similar to other programming languages.
>>print 36 + 64
100
>>print 200 – 100
100
>>print 10 * 10
100
>>print 1000 / 10
100

Exponentiation:

In python, the function of exponential can be performed using ** keys.
>> chairs = 10 ** 2
>> print chairs
100

Modulo:

Modulo operation can be performed using %.

Strings:

Assigning strings values and printing them.
python = “Hello world!”
print(“python”)

Escaping characters:

In python both single quotes and double quotes can be used for commenting. When using single quote, the interpreter doesn’t understands the code. In such cases we can use escape characters such as backslash(\).
‘Isn\’t it the python?’

Accessing by Index:

We can access any character of a string by indexing. Indexing starts from 0.
>>sixth_letter = “python”[5]
>>print sixth_letter
n

String methods:

We can calculate length of the string using len()
>>python = “Indian”
>>len(python)
>>print len(python)
6

We can convert lower case string to upper case string
>>python = “indian”
>>”indian”.upper()
>>print python.upper()
INDIAN

We can convert upper case string to lower case string
>>python = “INDIAN”
>>”INDIAN”.lower()
>>print python.lower()
indian

We can convert a variable to a string
>>pi = 3.14
>>print str(pi)
3.14

So, this concludes basics of python part-1.

Difference between Process and Thread in Java

 

ProcessThread
1) Part of Concurrent Programming.1) Integral part of Concurrent Programming.
2) A process has a self-contained execution environment. 2) A thread is a lightweight process.
3) Process has its own memory space.3) Threads share the process's resources, including memory and open files.
4) Processes are synonymous with programs or applications.4) Threads do things such as memory management and signal handling.
5) A Java application can create additional processes using a ProcessBuilder object.5) A Main thread has the ability to create additional threads.
6) To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets.6) Threads exist within a process. This makes for efficient, but potentially problematic, communication.

Processing time for a single core is shared among processes and threads through an OS feature called time slicing.

Time Slice or Preemption : A technique to implement multitasking in operating systems. The period of time for which a process is allowed to run in a preemptive multitasking system is generally called the time slice or quantum. The scheduler is run once every time slice to choose the next process to run.

Source: 1) The Java™ Tutorials
        2) Wikipedia

Object-Oriented Programming (OOP)

OOP is based on “objects“. An object can perform a set of functions. The functions that the object performs defines the object’s behavior.

For example, the Batsman(object) can play shots or a Bowler(object) can Bowl.

Languages that support object-oriented programming have four important aspects:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction involves the process to define objects that represent abstract actions which can perform work,
report on and change their state, and interact with other objects in the system.

Encapsulation is the process of enclosing data and functions into a single element.

Inheritance is when an object or class is based on another object,
using parent objects properties to maintain the same behavior in the child object.

Polymorphism is the method of having a single interface to objects of different types.

Object-oriented programming (OOP) is a programming paradigm

Objects — > data — > fields — > attributes — > methods(code)

Some of the popular languages that support Object-Oriented Programming

Java, Python, C++, C#, Perl, Ruby , Objective-C, PHP, et al.

Algorithms in Java

Most algorithms in Java operate on list instances and subsequently with other collection instances. The different algorithms used in Java are:

  • Sorting
  • Shuffling
  • Routine Data Manipulation
  • Searching
  • Composition
  • Finding Extreme Values

Sorting

The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship. Two forms of the operation are provided.

FORM 1

The simple form takes a List and sorts it according to its elements’ natural ordering.

The sort operation uses a optimized merge sort algorithm which is fast and stable:

  • Fast: It is guaranteed to run in n log(n) time and runs substantially faster on nearly sorted lists. Empirical tests showed it to be as fast as a highly optimized quicksort. A quicksort is generally considered to be faster than a merge sort but isn’t stable and doesn’t guarantee n log(n) performance.
  • Stable: It doesn’t reorder equal elements. This is important if you sort the same list repeatedly on different attributes. If a user of a mail program sorts the inbox by mailing date and then sorts it by sender, the user naturally expects that the now-sequential list of messages from a given sender will (still) be sorted by mailing date. This is guaranteed only if the second sort was stable.

FORM 2

The second form of sort takes a Comparator in addition to a List and sorts the elements with the Comparator.

Shuffling

The shuffle algorithm does the opposite of what sort does, destroying any trace of order that may have been present in a List. That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. This algorithm is useful in implementing games of chance.

This operation has two forms:

One takes a List and uses a default source of randomness, and the other requires the caller to provide a Random object to use as a source of randomness.

Routine Data Manipulation

The Collections class provides five algorithms for doing routine data manipulation on List objects, as listed below:

  • reverse — reverses the order of the elements in a List.
  • fill — overwrites every element in a List with the specified value. This operation is useful for reinitializing a List.
  • copy — takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.
  • swap — swaps the elements at the specified positions in a List.
  • addAll — adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array.

Searching

The binarySearch algorithm searches for a specified element in a sorted List. This algorithm has two forms.

  1. The first takes a List and an element to search for (the “search key”). This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.
  2. The second form takes a Comparator in addition to the List and the search key, and assumes that the List is sorted into ascending order according to the specified Comparator. The sort algorithm can be used to sort the List prior to calling binarySearch.

The return value is the same for both forms.

Composition

The frequency and disjoint algorithms test some aspect of the composition of one or more Collections:

  • frequency — counts the number of times the specified element occurs in the specified collection.
  • disjoint — determines whether two Collections are disjoint; that is, whether they contain no elements in common.

Finding Extreme Values

The min and the max algorithms return, respectively, the minimum and maximum element contained in a specified Collection. Both of these operations come in two forms.

The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements’ natural ordering.

The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.

Source: The Java™ Tutorials

 

Java Collection Framework

A collection or container is an object that groups multiple elements into a single unit, they are used to store, retrieve, manipulate and aggregate data.

Collections Framework

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

  • Interfaces: Interfaces are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
  • Implementations: These are the concrete implementations of the collection interfaces. Implementations are reusable data structures.
  • Algorithms: Algorithms are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. Algorithms possess reusable functionality.

Interfaces

The  collection interfaces encapsulate different types of collections. These interfaces allow collections to be manipulated independently of the details of their representation.

  • Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn’t provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List.
  • Set — a collection that cannot contain duplicate elements.
  • SortedSet — a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.
  • List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position).
  • Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.

Queues usually order elements in a FIFO (first-in, first-out) manner.

  • Deque — Similar to queue but Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be inserted, retrieved and removed at both ends.
  • Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.
  • SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

If an unsupported operation is invoked, a collection throws an UnsupportedOperationException.

Note:  All core collection interfaces are generic.

Source: The Java™ Tutorials