Friday, 31 August 2012

exception programs in java


exception programs in java:->

//EXCEPTION ZERO

package p2;

public class exc0 {

public exc0() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
int d=2;
try{
int a=42/d;

}catch(ArithmeticException e){
System.out.println("arithmatic exception=");
}finally{
System.out.println("finally =");
}
}

}

//DIVIDE BY EXCEPTION

package p2;

public class Exc1 {
static void subroutine(){
int d=0;
try{
int a=10/d;
}catch(Exception e){
}
}

public Exc1() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Exc1.subroutine();
}

}

//EXCEPTION USING BOTH DIVIDE BY & ZERO

package p2;
public class Exc2 {

public Exc2() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
int d,a;
try{
d=0;
a=42/d;
System.out.println("this wil nt be prntd");
}catch(ArithmeticException e){
System.out.println("division by zero");
}
System.out.println("after catch statement");
}

}

//exception example test

package p2;

import java.io.File;
import java.io.FileInputStream;

public class Extest {
public void doIt(){
File f=new File("C:\\himanshu.doc");
System.out.println(f.exists());
try{
FileInputStream in=new FileInputStream(f);
}
catch(ArithmeticException e){
}
catch(Exception e){
}
}
public static void main(String args[]){
Extest m=new Extest();
m.doIt();
}
}

package p2;

public class getCharDemo {

public getCharDemo() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="this is a demo of get char method";
int start =10;
int end=14;
char buf[]=new char[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf);

}

}

string handeling programs in java


string handeling programs in java

//CHANGE CASE FROM UPPER CASE TO LOWER

package p2;

public class ChangeCase {

public ChangeCase() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="this is a test";
System.out.println("original:"+s);
String upper=s.toUpperCase();
String lower=s.toLowerCase();
System.out.println("uppercase:"+upper);
System.out.println("lower:"+lower);
}

}

//CONCATINATION OF  TWO STRING

package p2;

public class ConCat {

public ConCat() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String longStr ="this could have been"+"a very long line that would have"+"wrap around bt str concat"+
"prevent this";
System.out.println(longStr);
}

}

//CURRENT THREAD DEMO

package p2;

public class CurrentThreadDemo {

public CurrentThreadDemo() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t=Thread.currentThread();
System.out.println("current thread:"+t);
t.setName("my thread");
System.out.println("After name change:"+t);
try{
for(int n=5;n>0;n--){
System.out.println(n);
Thread.sleep(5000);
}
}catch(InterruptedException e){
System.out.println("main thread interrupt");
}
}

}

//EXCEPTION USING JOIN(),ALIVE(),SLEEP()

package p2;

public class DemoJoin {

public DemoJoin() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stubThread
class NewThread implements Runnable{
String name;
Thread t;
NewThread(String threadname){
name =threadname;
t=new Thread(this,name);
System.out.println("new thread"+t);
t.start();
}
public void run(){
try{
for(int i=5;i>0;i--)
System.out.println(name+": "+i);
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println(name+"Interrupted");
}
System.out.println(name+"exiting");
}

}
NewThread obj1=new NewThread("one");

NewThread obj2=new NewThread("two");

NewThread obj3=new NewThread("three");
System.out.println("Thread one is alive:"+obj1.t.isAlive());
System.out.println("Thread two is alive:"+obj2.t.isAlive());

System.out.println("Thread three is alive:"+obj3.t.isAlive());

try{
System.out.println("waiting for threads for finish:");
obj1.t.join();
obj2.t.join();
obj3.t.join();
}catch(InterruptedException e){
System.out.println("main thread interrupted");
}
System.out.println("Thread one is alive :"+obj1.t.isAlive());
System.out.println("Thread two is alive :"+obj2.t.isAlive());
System.out.println("Thread three is alive :"+obj3.t.isAlive());
System.out.println("main thread exciting");


}
}

//STRING EQUAL OR NOT EQUAL TO

package p2;

public class EqualNotEqualTo {

public EqualNotEqualTo() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="hello";
String s2=new String(s1);
System.out.println(s1+"equals"+s2+"->"+s1.equals(s2));
System.out.println(s1+"=="+s2+"->"+(s1==s2));
}

}

//STRING USING EQUALS

package p2;

public class equalsDemo {

public equalsDemo() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="hello";
String s2="hello";
String s3="godbye";
String s4="HELLO";
System.out.println(s1+"equals"+s2+"->"+s1.equals(s2));
System.out.println(s1+"equals"+s3+"->"+s1.equals(s3));
System.out.println(s1+"equals"+s4+"->"+s1.equals(s4));
System.out.println(s1+"equals"+s4+"->"+s1.equalsIgnoreCase(s4));


}

}

Thursday, 30 August 2012

package in java

package in java:->
A Java package is a mechanism for organizing Java classes into namespaces similar to the
modules of Modula. Java packages can be stored in compressed files called JAR files,
allowing classes to download faster as a group rather than one at a time. Programmers also
typically use packages to organize classes belonging to the same category or providing
similar functionality.

A package provides a unique namespace for the types it contains.
Classes in the same package can access each other's package-access members.


In general, a package can contain the following kinds of types. A package allows
a developer to group classes (and interfaces) together. These classes will all be
related in some way – they might all have to do with a specific application or perform
a specific set of tasks. The Java API is a collection of packages, for example the javax.xml
package. The javax.xml package and its subpackages contain classes to handle XML.


In a Java source file, the package that this file's class or classes belong to is specified
with the package keyword. This keyword is usually the first keyword in the source file.[1]
package java.awt.event;
To use a package's classes inside a Java source file, it is convenient to import the classes
 from the package with an import declaration. The following declaration
import java.awt.event.*;
imports all classes from the java.awt.event package, while the next declaration
import java.awt.event.ActionEvent;
imports only the ActionEvent class from the package. After either of these import
 declarations, the ActionEvent class can be referenced using its simple class name:
ActionEvent myEvent = new ActionEvent();
Classes can also be used directly without an import declaration by using the fully
 qualified name of the class. For example,
java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent();
does not require a preceding import declaration.
Note that if you do not use a package declaration, your class ends up in an unnamed
package.[2][3] Classes in an unnamed package cannot be imported from classes in any other package.[4]


Classes within a package can access classes and members declared with default
access and class members declared with the protected access modifier. Default
 access is enforced when neither the public, protected nor private access modifier
is specified in the declaration. By contrast, classes in other packages cannot access
classes and members declared with default access. Class members declared as protected
can be accessed from the classes in the same package as well as classes in other packages
that are subclasses of the declaring class.
Creation of JAR files

JAR Files are created with the jar command-line utility. The command
jar cf myPackage.jar *.class
compresses all .class files into the JAR file myPackage.jar. The ' c ' option on the command
line tells the jar command to "create new archive." The ' f ' option tells it to create a file.
 The file's name comes next before the contents of the JAR file.
[edit]Package naming conventions

Packages are usually defined using a hierarchical naming pattern, with levels in the hierarchy
 separated by periods (.) (pronounced "dot"). Although packages lower in the naming hierarchy
are often referred to as "subpackages" of the corresponding packages higher in the hierarchy,
there is almost no semantic relationship between packages. The Java Language Specification establishes
 package naming conventions to avoid the possibility of two published packages having the same name.
The naming conventions describe how to create unique package names, so that packages that are widely
distributed will have unique namespaces. This allows packages to be separately, easily and automatically
installed and catalogued.
In general, a package name begins with the top level domain name of the organization and then the
organization's domain and then any subdomains, listed in reverse order. The organization can then
choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions,
 naming the package ca.mysoft.fractions distinguishes the fractions package from another similar
package created by another company. If a German company named MySoft also creates a fractions package,
but names it de.mysoft.fractions, then the classes in these two packages are defined in a unique and
 separate namespace.
Complete conventions for disambiguating package names and rules for naming packages when the Internet
 domain name cannot be directly used as a package name are described in section 7.7 of the Java Language Specification.



interface in java


Interface (Java)

SITANSU


An interface in the Java programming language is an abstract type that is used to 
specify an interface (in the generic sense of the term) that classes must implement. 
Interfaces are declared using the interface keyword, and may only contain method 
signature and constant declarations (variable declarations that are declared to be both
 static and final). An interface may never contain method definitions.
Interfaces cannot be instantiated, but rather are implemented. A class that implements 
an interface must implement all of the methods described in the interface, or be an abstract
 class. Object references in Java may be specified to be of an interface type; in which case,
 they must either be null, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulate multiple inheritance. All classes 
in Java must have exactly one base class, the only exception being java.lang.Object 
(the root class of the Java type system); multiple inheritance of classes is not allowed.
A Java class may implement, and an interface may extend, any number of interfaces;
 however an interface may not implement an interface


a closer look at methods & class in java



AUTHOR
//SOME PIRAMID EXAMPLE IN JAVA
package com.swain.cell;

public class Piramid2 {

public static void main(String args[]){
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
System.out.print(" "+j);
System.out.print("\n");
}
}
}
//PIRAMID3 
package com.swain.cell;

public class Piramid3 {

public static void main(String args[]){
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
System.out.print(" "+j);
System.out.print("\n");
}
for(i=4;i>=1;i--)
{
for(j=1;j<=i;j++)
System.out.print(" "+j);
System.out.print("\n");
}
}
}
//PIRAMID4
package com.swain.cell;

public class Piramid4 {

public static void main(String args[]){
int i,k,j;
for(i=1;i<=200;i= i*2){

for(j=1; j<=i; j=j*2)
System.out.print(j + " ");

for(k=i/2; k>=1; k=k/2)
System.out.print( k + " ");
System.out.print("\n");
}
}
}
//PRIME NO IN JAVA
package com.swain.cell;

public class Prime {
public static void main(String args[])
  {
     int n, status = 1, num = 3;
n=5;
     if ( n >= 1 )
     {
        System.out.println("prime numbers are: ");
        System.out.println(2);
     }
 
     for ( int count = 2 ; count <=n ;  )
     {
        for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
        {
           if ( num%j == 0 )
           {
              status = 0;
              break;
           }
        }
        if ( status != 0 )
        {
           System.out.println(num);
           count++;
        }
        status = 1;
        num++;
     }         
  }

}
//STRING PALIDROM IN JAVA
package com.swain.cell;

public class StringPalindrome {
public static void main(String args[])
  {
     String original="1001";
     String rev="";
           
     int length = original.length();
 
     for ( int i = length - 1 ; i >= 0 ; i-- )
        rev = rev + original.charAt(i);
 
     if (original.equals(rev))
        System.out.println(original+" is a palindrome.");
     else
        System.out.println(original+" is not a palindrome.");
 
  }
}

overview of class in java


overview of class in java
//LINEAR SEARCH IN JAVA
package com.swain.cell;
public class LinearSearch {
public static void main(String[] args)
{
System.out.println("Linear Search List");

int[] arr = {0,2879, 15, 29, 78, 26, 24, 44, 167, 13,24,47};

int i;
int num = 44;
boolean flag=false;

for(i=0; i<arr.length; i++){
if(arr[i]==num){
flag=true;
break;
}

}//for

if(flag){
System.out.println(num + " index  position "+i);
}
else{
System.out.println(num + " no not found");
}

}

}
//MATCH TWO STRING IN JAVA
package com.swain.cell;

import java.util.HashMap;
import java.util.StringTokenizer;

public class MatchString {
public static void main(String arg[]) {
       String str = "hima hima sekhar swain hima";
       char ch1[]=str.toCharArray();
       HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
       for(int i=0; i<ch1.length; i++)
       {
           char ch=ch1[i];
           hm.put(ch,(hm.get(ch)==null?1:hm.get(ch)+1));
       }
       System.out.println(hm.get('a'));
       
       StringTokenizer t = new StringTokenizer(str);
       HashMap<String,Integer> hms=new HashMap<String,Integer>();
       
while(t.hasMoreTokens())
{
String word = t.nextToken();
hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));
System.out.println("Found the word " + word);
}
System.out.println("no of word " + hms.toString());
       
   }
}
//PALINDROME IN JAVA
package com.swain.cell;

public class Palindrome {

public static void main(String [] args){
 try{
 
 int num= 161;
 int n = num;
 int rev=0;
 for (int i=0; i<=num; i++){
 int r=num%10;
 num=num/10;
 rev=rev*10+r;
 i=0;
 }
  if(n == rev){
 System.out.print("Number is palindrome!");
 }
 else{
 System.out.println("Number is not palindrome!");
 }
 }
 catch(Exception e){
 System.out.println("Error");
 }
 }
}
//PIRAMID IN JAVA
package com.swain.cell;

public class Piramid {

public static void main(String args[]){
int p=1;
for(int i=1;i<=5;i++){
for(int j=i;j<5;j++){
System.out.print(" ");
}
for(int k=1;k<=p;k++){
if(k%2==0){
System.out.print(" ");

}else
System.out.print("*");

}
System.out.println();
p+=2;
}
}
}

some java example using hashmap



//some java example using hashmap
//DUPLICATE  CHARACTERNIN JAVA
package com.swain.cell;

import java.util.HashMap;

public class DuplicateCharacter {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

        String str = "Character duplicate word example java";
        char selectedchar='C';
        char ch1[]=str.toUpperCase().toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0; i<ch1.length; i++)
        {
            char ch=ch1[i];
            hm.put(ch,(hm.get(ch)==null?1:hm.get(ch)+1));
        }
     
        System.out.println(selectedchar+" contents  " + hm.get(selectedchar)+ " times.");
     
     
 
}

}
//DUPLICATE STRING IN JAVA
package com.swain.cell;

import java.util.HashMap;
import java.util.StringTokenizer;

public class DuplicateString {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

        String str = "java java android android java example";
        String selectedword="java";
         
        StringTokenizer t = new StringTokenizer(str);
        HashMap<String,Integer> hms=new HashMap<String,Integer>();
        
while(t.hasMoreTokens())
{
String word = t.nextToken();
hms.put(word,(hms.get(word)==null?1:hms.get(word)+1));
}
System.out.println(selectedword+" contents  " + hms.get(selectedword)+ " times.");
        
    
}

}
//FACTORIAL IN JAVA
package com.swain.cell;

public class Factorial {
public static void main(String args[])
  {
     int n, c, fact = 1;
 
     n=5;
     if ( n < 0 )
        System.out.println("Number should be non-negative.");
     else
     {
        for ( c = 1 ; c <= n ; c++ )
           fact = fact*c;
 
        System.out.println("Factorial of "+n+" is = "+fact);
     }
  }

}
//FIBONACI SERIES IN JAVA
package com.swain.cell;

public class Fibonacci {

public static long fibonacci(int n) {
       if (n <= 1) return n;
       else return fibonacci(n-1) + fibonacci(n-2);
   }

   public static void main(String[] args) {
       int n=15;
       for (int i = 1; i <= n; i++)
           System.out.println(i + ":- " + fibonacci(i));
   }

}

most important program is implemented by sitansu


MOST IMPORTANT PROGRAM Is PLIMENTED BY SITANSU
//ARMSTRONG IN JAVA
package com.swain.cell;

public class Armstrong {
public static void main(String args[])
  {
     int n, sum = 0, temp, r;
     n=407;
     temp = n;

     while( temp != 0 )
     {
        r = temp%10;
        sum = sum + r*r*r;
        temp = temp/10;
     }

     if ( n == sum )
        System.out.println(n+" is an armstrong number.");
     else
        System.out.println(n+" is not an armstrong number.");      
  }

}
//BINARY SEARCH IN JAVA
package com.swain.cell;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BinarySearch {
public static void main(String args[])throws IOException{

int i;
InputStreamReader x=new InputStreamReader(System.in);
BufferedReader y=new BufferedReader(x);
int a[]=new int[10];
System.out.println("ENTER THE NUMBER TO BE SEARCHED");
int n=Integer.parseInt(y.readLine());
System.out.println("ENTER 10 NUMBERS FOR THE ARRAY");
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(y.readLine());
   } 
   System.out.println("CONTENTS OF ARRAY ARE");
   for(i=0;i<10;i++)
   {
    System.out.println(a[i]);
   }
   System.out.println("NUMBER TO BE SEARCHED IS "+n);
   int p=-1,mid,l=0,u=9;
   while(l<=u)
   {
    mid=(l+u)/2;
    if(a[mid]==n)
    {
    p=mid;
    break;
    }
    else if(n> a[mid])
    {
    l=mid+1;
    }
    else if(n<a[mid])
    {
    u=mid-1;
    }
   }
   if(p==-1)
   {
    System.out.println("NUMBER DOES NOT EXIST IN THE ARRAY");
   }
   else
   {
    System.out.println("NUMBER EXISTS AT THE INDEX "+p);
   }
}
}
//COUNT WORD IN JAVA
package com.swain.cell;

import java.util.StringTokenizer;

public class CountWords {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
        String st="how to count word in java?";
        int count=0;
        StringTokenizer stk=new StringTokenizer(st," ");
        while(stk.hasMoreTokens()){
            String token=stk.nextToken();
            count++;
        }
        System.out.println("Number of words are: "+count);

}

}
//MULTIPLECATION TWO STRING
package com.swain.cell;

public class Div {

public String Mul (int a, int b){
int sum=a*b;
System.out.println("Sum="+sum);
return "temp="+sum;
}
public static void main (String args[]){
Div p=new Div();
String str=null;
str=p.Mul(15, 5);
System.out.println(str);
}
}