Wednesday, 29 March 2017

some thing about LibreOffice calc

LibreOffice calc is a software using which a user can do all its jobs that is done with the help of software like MS EXCEL. that means any user want to work with spreadsheet can make the use of  LibreOffice calc. for more details on the working of LibreOffice calc check the book following the link  http://www.amazon.com/LibreOffice-Calc-Guide-KAMAL-PARKASH-ebook/dp/B00F2GSJA0/ref=sr_1_3?ie=UTF8&qid=1449507729&sr=8-3&keywords=kamal+parkash

Monday, 20 March 2017

Program based on Enumeration (or enum) in C


1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and ‘Freezed’ have same value 0.

#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
 
int main()
{
   printf("%d, %d, %d", Working, Failed, Freezed);
   return 0;
}
 
2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
 
int main()
{
    enum day d = thursday;
    printf("The day number stored in d is %d", d);
    return 0;
}
 
3. We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
          wednesday, thursday = 10, friday, saturday};
 
int main()
{
    printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
            wednesday, thursday, friday, saturday);
    return 0;
}
 
 
 
 

Python Script to Start and Stop Amazon AWS Instances

import boto.ec2
import sys

# specify AWS keys
auth = {"aws_access_key_id": "<key_id>", "aws_secret_access_key": "<access_key>"}

def main():
    # read arguments from the command line and 
    # check whether at least two elements were entered
    if len(sys.argv) < 2:
 print "Usage: python aws.py {start|stop}\n"
 sys.exit(0)
    else:
 action = sys.argv[1] 

    if action == "start":
 startInstance()
    elif action == "stop":
     stopInstance()
    else:
     print "Usage: python aws.py {start|stop}\n"

def startInstance():
    print "Starting the instance..."

    # change "eu-west-1" region if different
    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    # change instance ID appropriately  
    try:
         ec2.start_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def stopInstance():
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

if __name__ == '__main__':
    main()

Saturday, 18 March 2017

Recursive function to sum an integer set in PHP

<?
function summation ($count) {
     if ($count != 0) :
          return $count + summation($count-1);
     endif;
}
$sum = summation(10);
print "Summation = $sum";
?>

Android - Application Components

Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
There are following four main components that can be used within an Android application −
Sr.No Components & Description
1 Activities
They dictate the UI and handle the user interaction to the smart phone screen.
2 Services
They handle background processing associated with an application.
3 Broadcast Receivers
They handle communication between Android OS and applications.
4 Content Providers
They handle data and database management issues.

Features of Android

Android is a powerful operating system competing with Apple 4GS and supports great features. Few of them are listed below −
Sr.No. Feature & Description
1 Beautiful UI
Android OS basic screen provides a beautiful and intuitive user interface.
2 Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.
3 Storage
SQLite, a lightweight relational database, is used for data storage purposes.
4 Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
5 Messaging
SMS and MMS
6 Web browser
Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
7 Multi-touch
Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero.
8 Multi-tasking
User can jump from one task to another and same time various application can run simultaneously.
9 Resizable widgets
Widgets are resizable, so users can expand them to show more content or shrink them to save space.
10 Multi-Language
Supports single direction and bi-directional text.
11 GCM
Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution.
12 Wi-Fi Direct
A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection.
13 Android Beam
A popular NFC-based technology that lets users instantly share, just by touching two NFC-enabled phones together.

Examples of Successful Hashtag Campaigns

#WantAnR8—Audi

Audi’s #WantAnR8 campaign is still looked at as one of the single most successful Twitter campaigns in history. It all started when the car company saw that somebody had sent out a Tweet with the hashtag #WantAnR8 to explain why they wanted an Audi R8. Audi quickly created a contest that bolstered the use of this hashtag. All users had to do was create and post a Tweet using that hashtag and they’re entered for a chance to win an R8 for a day.

Impressions in digital marketing

Impressions are when an advertisement or any other form of digital media renders on a user's screen. Impressions are not action-based and are merely defined by a user potentially seeing the advertisement, making CPM campaigns ideal for businesses intent on spreading brand awareness.

Impressions In Digital Marketing

Digital marketing has made impression tracking significantly more quantitative than offline advertising. For example, a billboard owner has no concrete way of estimating the number of impressions his platform grants advertisers. Impression-based online campaigns, on the other hand, can measure impressions concretely, and are generally sold in terms of cost-per-thousand (CPM) impressions.
Impression tracking is a common metric for measuring the performance of most types of online marketing campaigns, including:
  • Pay-per-click impressions, measured against actual clicks
  • Number of times a meme appears on social media
  • On-site views of internal calls-to-action
  • Access of graphic materials through third-party sites, such as Pinterest or Google Image Search
Impressions generally come in two forms: served and viewable.

Served Impressions

The current standard for tracking online impressions is based on served content: whenever a marketing-related file is accessed and transmitted that activity counts as an impression. This is extremely easy to track as it relies on pure server data to count the impressions.
Counting impressions based on served content still has the 'billboard' problem, in that it's difficult to tell how much impact the content had without deeper data analysis. Also, in some cases files can be accessed without being viewable by the consumer.
As a result, ecommerce businesses purchasing impression-based advertising such as display ads have urged the adoption of more accurate systems for measuring impressions. The new viewable impressions standard seeks to address this need.

Viewable Impressions

The viewable impressions method uses data gathered from a user's device to refine the impression count by excluding cases where, in all likelihood, the content was not seen.
Viewable impression tracking can identify user behaviors which prevent ad viewing, including:
  • Ad-blocking software
  • Screen resolutions too small for the ad to appear onscreen.
  • Users browsing scrolling down before the requested ad has loaded.
  • Broken plug-ins preventing content display.
  • Mobile incompatibilities such as desktop-only websites.
  • Minimized browser windows.
  • User movement between different applications.
  • Pages loaded in background tabs then never accessed.
  • Non-user interference, like malware cloaking ads
The benefits of viewable impression tracking are twofold. First, a company receives more accurate information on the number of actual impressions made. Secondly, the data collected is highly actionable and suggests improvements which can ensure greater rates of content delivery.

Examples of Strong Digital Marketing Campaigns

Search Engine Marketing (PPC)
So many people consider PPC search engine marketing to be bland and dull, especially when focusing on text ads. However, some brands have leveraged the medium to deliver their message in an imaginative and engaging way.

This ad from Samsung is an excellent example of what can be achieved with a combination of effective targeting and creative marketing.

Facebook
Social media advertising doesn't have to be extreme to grab attention. This ad from NatureBox was compelling due to a combination of simple factors that anyone could repeat for their own business:
  • Fantastic image quality
  • A simple and clearly stated offer
  • Benefits/features included
  • Targeted to the right audience
Twitter
Twitter is all about the here-and-now, so the most engaging content needs to have some time-sensitivity about it. Doubletree by Hilton achieved time-sensitivity as well as creating intriguing interactions with its audience when they promoted this tweet.

LinkedIn
Fruit of the loom, a retail clothing brand ran a campaign where they sent an offer of free underwear & socks to individuals when their profile indicated they had a new job.

The offer is a perfect match for the LinkedIn audience, and their clever use of targeting, along with their witty ad creative resulted in a huge success for the brand.

Retargeting (remarketing)
GetResponse is an exceptional instance of using retargeting (or remarketing) to reach customers. Rather than presenting users with the same ads again and again, they used a series of ads that focused on the core features and benefits of their software.

As with all successful retargeting campaigns, they also cap their frequency to ensure that users don't feel 'stalked' by their ads.

Tips and Examples for Digital Marketing Success

Marketing in a digital world has evolved. There was a time when ads in leading newspapers, commercials during popular TV shows, and strategically placed billboards did the job. Now, with every passing day, getting noticed by your audience is becoming more and more difficult.
Facebook pages and Twitter feeds are overcrowded. Odds are fair that your post will get lost in the constant, unabated, overwhelming storm of information.
So, when you're ready to implement your digital marketing strategy, how can you gird yourself to do battle?
Being in the right place, at the right time, in front of the right people is about implementing the right tactics and ideas, as in the following five digital marketing examples.

1. Target the right audience
Facebook isn't the one-pill solution for all online ills. Neither is Twitter. Identify your audience, think about where they are likely to spend their time online, and then work on building a presence in those very areas.
The "who" and "where" become extremely important when you finally begin to study your ROI, much of that investment being your precious time, not just money.
Example: Uber focused on mobile-savvy professionals who didn't mind paying that little extra to travel in style and comfort. They made luxury standard, and backed it up with a brilliant app that made booking an Uber ride extremely quick and convenient. Uber is now a success story cited by many and studied in depth.

2. Pay attention to the important numbers
Increasing unique visitors to your website shouldn't be the end game. Converting visitors is what counts. How many of them subscribed to your newsletter, read your e-book, downloaded the free trail or simply filled out a form you wished they would?
Ditto with Facebook likes. Garnering thousands of fans on Facebook, though great by itself and no mean feat, doesn't help your bottom line. How many of them convert to paying buyers? Pay attention to the far more important numbers.
Many online marketing companies tend on focus on the vanity metrics, and pitch their services based on increase in shares, likes, visits, or comments. Instead, the focus ought to be on conversions, sales, signups, and relationships built.
Example: Pink Cake Box, a small specialty cake shop in New Jersey, began by setting up a WordPress website and blog, regularly posting about delicious cakes and cupcakes, keeping the focus on the pictures to entice viewers. It worked: Traffic grew, and orders with it. But the direct correlation worked up to a point, beyond which the traffic simply consisted of non-buyers who were just looking for information and recipes. To counter that trend, the company began streamlining its content and focusing on relevant traffic rather than aggregate traffic numbers.

3. Project clear goals and corresponding messages
Are your various marketing channels projecting mixed messages? A high bounce rate on your site should raise a red flag. Is your ad or post giving a different impression, while the landing page doesn't deliver what was expected, driving the visitor away? That phenomenon is prevalent in paid search. You are losing valuable money and potential customers.
Every digital marketing channel used must project a unified goal and picture of your business. Keep your goals clear and measurable, and your messages on point, when executing your digital marketing strategy.
Example: Kiva is a nonprofit microfinancing organization that allows people to lend money through the Internet to entrepreneurs and students worldwide. Its mission is "to connect people through lending to alleviate poverty." As of Nov 2013, Kiva was raising about $1 million every three days. The messages and goals from Kiva have been clear and uniform across all social channels. The platform now has a community of more than a million lenders from around the world.

4. Be accessible on the go
Being mobile-friendly isn't optional anymore. More and more people are accessing the Internet via mobile devices. Being easily available and shareable via smartphone is imperative for business success.
Example: BuzzFeed as tripled visitor figures over the last two years. It popularly targets the "Bored at Work" and "Bored in Line" people to consume and share interesting content. It found that people who consume content on their phones while waiting are major drivers of social sharing. It made sure its content was mobile-friendly, making reading, participating, and sharing very easy. Currently, more than one-third of BuzzFeed traffic is from mobile devices.

5. Connect and collaborate
What you can achieve alone has a limit. You need to try to maximize output with limited input by collaborating and getting people to happily do the work for you (much like Tom Sawyer). Create a great platform, post valuable information, build a community, and empower them to act... then watch it flourish.
Example: Ana White is a carpenter who created a website to help women do DIY carpentry projects. She has created a huge following, among men and women alike, who love, use, and share her blueprints and ideas. Ana encourages her visitors to post pictures of their projects. Remarkably, she has a very popular site where most of the content comes from the community. She herself does not post very often. Although she does comment on others' posts and engages with her readers, her community actively posts and answers each others' questions.


Tuesday, 14 March 2017

Java Program to Implement Binary search using recursion

public class MyRecursiveBinarySearch {
 
    public static int recursiveBinarySearch(int[] sortedArray, int start, int end, int key) {
         
        if (start < end) {
            int mid = start + (end - start) / 2
            if (key < sortedArray[mid]) {
                return recursiveBinarySearch(sortedArray, start, mid, key);
                 
            } else if (key > sortedArray[mid]) {
                return recursiveBinarySearch(sortedArray, mid+1, end , key);
                 
            } else {
                return mid;  
            }
        }
        return -(start + 1); 
    }
 
    public static void main(String[] args) {
         
        int[] arr1 = {2,45,234,567,876,900,976,999};
        int index = recursiveBinarySearch(arr1,0,arr1.length,45);
        System.out.println("Found 45 at "+index+" index");
        index = recursiveBinarySearch(arr1,0,arr1.length,999);
        System.out.println("Found 999 at "+index+" index");
        index = recursiveBinarySearch(arr1,0,arr1.length,876);
        System.out.println("Found 876 at "+index+" index");
    }
}

Java Program to implement Linear search or Sequential search algorithm


public class MyLinearSearch {
 
    public static int linerSearch(int[] arr, int key){
         
        int size = arr.length;
        for(int i=0;i<size;i++){
            if(arr[i] == key){
                return i;
            }
        }
        return -1;
    }
     
    public static void main(String a[]){
         
        int[] arr1= {23,45,21,55,234,1,34,90};
        int searchKey = 34;
        System.out.println("Key "+searchKey+" found at index: "+linerSearch(arr1, searchKey));
        int[] arr2= {123,445,421,595,2134,41,304,190};
        searchKey = 421;
        System.out.println("Key "+searchKey+" found at index: "+linerSearch(arr2, searchKey));
    }
}

Java LinkedList - use of basic function

import java.util.LinkedList;
 
public class MyBasicOperations {
 
    public static void main(String a[]){
         
        LinkedList<String> ll = new LinkedList<String>();
        ll.add("Orange");
        ll.add("Apple");
        ll.add("Grape");
        ll.add("Banana");
        System.out.println(ll);
        System.out.println("Size of the linked list: "+ll.size());
        System.out.println("Is LinkedList empty? "+ll.isEmpty());
        System.out.println("Does LinkedList contains 'Grape'? "+ll.contains("Grape"));
    }
}

programming a simple generics class in java

public class MySimpleGenerics {
 
    public static void main(String a[]){
         
        //we are going to create SimpleGeneric object with String as type parameter
        SimpleGeneric<String> sgs = new SimpleGeneric<String>("JAVA2NOVICE");
        sgs.printType();
        //we are going to create SimpleGeneric object with Boolean as type parameter
        SimpleGeneric<Boolean> sgb = new SimpleGeneric<Boolean>(Boolean.TRUE);
        sgb.printType();
    }
}
 
/**
 * Here T is a type parameter, and it will be replaced with
 * actual type when the object got created.
 */
class SimpleGeneric<T>{
     
    //declaration of object type T
    private T objReff = null;
     
    //constructor to accept type parameter T
    public SimpleGeneric(T param){
        this.objReff = param;
    }
     
    public T getObjReff(){
        return this.objReff;
    }
     
    //this method prints the holding parameter type
    public void printType(){
        System.out.println("Type: "+objReff.getClass().getName());
    }
}

Java Program to read all elements in vector by using iterator

import java.util.Iterator;
import java.util.Vector;
 
public class VectorIterator {
 
    public static void main(String a[]){
        Vector<String> vct = new Vector<String>();
        //adding elements to the end
        vct.add("First");
        vct.add("Second");
        vct.add("Third");
        vct.add("Random");
        Iterator<String> itr = vct.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}

Java program to get list of all IPs of a given Host

import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class MyAllIpAddresses {
 
    public static void main(String a[]){
     
        try {
            InetAddress[] myHost = InetAddress.getAllByName("www.google.com");
            for(InetAddress host:myHost){
                System.out.println(host.getHostAddress());
            }
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
    }
}

Java program to get machine or local host IP address

import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class MyIpAddress {
 
    public static void main(String a[]){
     
        try {
            InetAddress ipAddr = InetAddress.getLocalHost();
            System.out.println(ipAddr.getHostAddress());
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
    }
}

Design Pattern in Object Oriented Programming

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that the programmer must implement in the application. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Patterns that imply object-orientation or more generally mutable state, are not as applicable in functional programming languages.
The types of design patterns are Creational, Structural, and Behavioral design patterns.
Creational Design Pattern
Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation. Types of creational design patterns are:
  1. Singleton Pattern
  2. Factory Pattern
  3. Abstract Factory Pattern
  4. Builder Pattern
  5. Prototype Pattern
Structural Design Pattern
Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
  1. Adapter Pattern
  2. Composite Pattern
  3. Proxy Pattern
  4. Flyweight Pattern
  5. Facade Pattern
  6. Bridge Pattern
  7. Decorator Pattern
Behavioral Design Pattern
Behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
  1. Template Method Pattern
  2. Mediator Pattern
  3. Chain of Responsibility Pattern
  4. Observer Pattern
  5. Strategy Pattern
  6. Command Pattern
  7. State Pattern
  8. Visitor Pattern
  9. Iterator Pattern
  10. Memento Pattern

Java program for multi threading

Java Thread By Implementing Runnable Interface

class MyRunnableThread implements Runnable{
 
    public static int myCount = 0;
    public MyRunnableThread(){
         
    }
    public void run() {
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    }
}
public class RunMyThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MyRunnableThread mrt = new MyRunnableThread();
        Thread t = new Thread(mrt);
        t.start();
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

 Java Thread By Extending Thread Class

class MySmpThread extends Thread{
    public static int myCount = 0;
    public void run(){
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    }
}
public class RunThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MySmpThread mst = new MySmpThread();
        mst.start();
        while(MySmpThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MySmpThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

 

Java Program to remove an element from collection using Iterator object

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class MyItrRemoveElement {
 
    public static void main(String a[]){
         
        String removeElem = "Perl";
        List<String> myList = new ArrayList<String>();
        myList.add("Java");
        myList.add("Unix");
        myList.add("Oracle");
        myList.add("C++");
        myList.add("Perl");
        System.out.println("Before remove:");
        System.out.println(myList);
        Iterator<String> itr = myList.iterator();
        while(itr.hasNext()){
            if(removeElem.equals(itr.next())){
                itr.remove();
            }
        }
        System.out.println("After remove:");
        System.out.println(myList);
    }
}

Java Program to iterate through collection objects

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class MyCollectionIterator {
 
    public static void main(String a[]){
         
        List<String> myList = new ArrayList<String>();
        myList.add("Java");
        myList.add("Unix");
        myList.add("Oracle");
        myList.add("C++");
        myList.add("Perl");
        Iterator<String> itr = myList.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}

Java ClassPath

Question: What is the meaning of PATH and CLASSPATH ? How it is set in environment variable? Why we must learn it.
ANS:- Java is an OOP language. In java programming language for compiling the program we use the compiler that converts the source code into the byte code after that, that byte code is interpreted by JVM that converts the bytecode into the machine independent code.  In java how the Java compiler and the JVM use the class search path to locate classes when they are referenced by other Java code. Searching class  path is important for all Java developers.Many  development tools have their own ways of manipulating the class path, which vary from product to product.For doing this we will use only simple command-line tools to carry out the compile operations. No difference, between the way that the Java compiler searches for classes, and the way that the JVM does it at run time. The compiler has the ability to compile classes from source code, where the JVM does not.  We will use the compiler, but similar issues apply at run time.

java program for different types of array example

public class ArrayExamples
{    public static void main(String[] args)
    {    int[] list = {1, 2, 3, 4, 1, 2, 3};
        findAndPrintPairs(list, 5);
        bubblesort(list);
        showList(list);

        list = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        bubblesort(list);
        showList(list);

        list = new int[]{11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2};
        bubblesort(list);
        showList(list);

        list = new int[]{1};
        bubblesort(list);
        showList(list);
    }
 public static int findMin(int[] list)
    {    assert list != null && list.length > 0 : "failed precondition";

        int indexOfMin = 0;
        for(int i = 1; i < list.length; i++)
        {    if(list[i] < list[indexOfMin])
            {    indexOfMin = i;
            }
        }

        return indexOfMin;
    }

    public static void badResize(int[] list, int newSize)
    {    assert list != null && newSize >= 0 : "failed precondition";

        int[] temp = new int[newSize];
        int limit = Math.min(list.length, newSize);

        for(int i = 0; i < limit; i++)
        {    temp[i] = list[i];
        }

        // uh oh!! Changing pointer, not pointee. This breaks the
        // relationship between the parameter and argument
        list = temp;
    }

  public static int[] goodResize(int[] list, int newSize)
    {    assert list != null && newSize >= 0 : "failed precondition";

        int[] result = new int[newSize];
        int limit = Math.min(list.length, newSize);

        for(int i = 0; i < limit; i++)
        {    result[i] = list[i];
        }

        return result;
    }


   public static void findAndPrintPairs(int[] list, int target)
    {    assert list != null : "failed precondition";

        for(int i = 0; i < list.length; i++)
        {    for(int j = i + 1; j < list.length; j++)
            {    if(list[i] + list[j] == target)
                {    System.out.println("The two elements at indices " + i + " and " + j
                        + " are " + list[i] + " and " + list[j] + " add up to " + target);
                }
            }
        }
    }
    public static void bubblesort(int[] list)
    {
        assert list != null : "failed precondition";

        int temp;
        boolean changed = true;
        for(int i = 0; i < list.length && changed; i++)
        {    changed = false;
            for(int j = 0; j < list.length - i - 1; j++)
            {    assert (j > 0) && (j + 1 < list.length) : "loop counter j " + j +
                    "is out of bounds.";
                if(list[j] > list[j+1])
                {    changed = true;
                    temp = list[j + 1];
                    list[j + 1] = list[j];
                    list[j] = temp;
                }
            }
        }

        assert isAscending( list );
    }


    public static void showList(int[] list)
    {    for(int i = 0; i < list.length; i++)
            System.out.print( list[i] + " " );
        System.out.println();
    }

  public static boolean isAscending( int[] list )
    {    boolean ascending = true;
        int index = 1;
        while( ascending && index < list.length )
        {    assert index >= 0 && index < list.length;

            ascending = (list[index - 1] <= list[index]);
            index++;
        }

        return ascending;
    }
}

java program for string manipulation

public class StringExample
{    public static void main(String[] args)
    {    String s1 = "Computer Science";
        int x = 307;
        String s2 = s1 + " " + x;
        String s3 = s2.substring(10,17);
        String s4 = "is fun";
        String s5 = s2 + s4;
       
        System.out.println("s1: " + s1);
        System.out.println("s2: " + s2);
        System.out.println("s3: " + s3);
        System.out.println("s4: " + s4);
        System.out.println("s5: " + s5);
       
        //showing effect of precedence
       
        x = 3;
        int y = 5;
        String s6 = x + y + "total";
        String s7 = "total " + x + y;
        String s8 = " " + x + y + "total";
        System.out.println("s6: " + s6);
        System.out.println("s7: " + s7);
        System.out.println("s8: " + s8);
    }
}

java program to calculate factorial using for loop

public class Factorial
{
    public static void main(String[] args)
    {    final int NUM_FACTS = 100;
        for(int i = 0; i < NUM_FACTS; i++)
            System.out.println( i + "! is " + factorial(i));
    }
   
    public static int factorial(int n)
    {    int result = 1;
        for(int i = 2; i <= n; i++)
            result *= i;
        return result;
    }
}

java program for prime number

import java.math.BigInteger;
import java.util.Random;

public class PrimeEx {

    /**
     * @param args
     */
    public static void main(String[] args) {
        printTest(10, 4);
        printTest(2, 2);
        printTest(54161329, 4);
        printTest(1882341361, 2);
        printTest(36, 9);

        System.out.println(isPrime(54161329) + " expect false");
        System.out.println(isPrime(1882341361) + " expect true");
        System.out.println(isPrime(2) + " expect true");
        int numPrimes = 0;
        Stopwatch s = new Stopwatch();
        s.start();
        for(int i = 2; i < 10000000; i++) {
            if(isPrime(i)) {
                numPrimes++;
            }
        }
        s.stop();
        System.out.println(numPrimes + " " + s);
        s.start();
        boolean[] primes = getPrimes(10000000);
        int np = 0;
        for(boolean b : primes)
            if(b)
                np++;
        s.stop();
        System.out.println(np + " " + s);

        System.out.println(new BigInteger(1024, 10, new Random()));
    }

    public static boolean[] getPrimes(int max) {
        boolean[] result = new boolean[max + 1];
        for(int i = 2; i < result.length; i++)
            result[i] = true;
        final double LIMIT = Math.sqrt(max);
        for(int i = 2; i <= LIMIT; i++) {
            if(result[i]) {
                int index = 2 * i;
                while(index < result.length){
                    result[index] = false;
                     index += i;
                }
            }
        }
        return result;
    }


    public static void printTest(int num, int expectedFactors) {
        Stopwatch st = new Stopwatch();
        st.start();
        int actualFactors = numFactors(num);
        st.stop();
        System.out.println("Testing " + num + " expect " + expectedFactors + ", " +
                "actual " + actualFactors);
        if(actualFactors == expectedFactors)
            System.out.println("PASSED");
        else
            System.out.println("FAILED");
        System.out.println(st.time());
    }

    // pre: num >= 2
    public static boolean isPrime(int num) {
        assert num >= 2 : "failed precondition. num must be >= 2. num: " + num;
        final double LIMIT = Math.sqrt(num);
        boolean isPrime = (num == 2) ? true : num % 2 != 0;
        int div = 3;
        while(div <= LIMIT && isPrime) {
            isPrime = num % div != 0;
            div += 2;
        }
        return isPrime;
    }

     public static int numFactors(int num) {
        assert num >= 2 : "failed precondition. num must be >= 2. num: " + num;
        int result = 0;
        final double SQRT = Math.sqrt(num);
        for(int i = 1; i < SQRT; i++) {
            if(num % i == 0) {
                result += 2;
            }
        }
        if(num % SQRT == 0)
            result++;
        return result;
    }

}