Thursday, July 28, 2016

HTTPURLConnection WebService Client

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; public class Test1 { private static final String serviceUrl = "http://www.webservicex.net/stockquote.asmx"; public static void main(String args[]) { try { final URL url = new URL(serviceUrl); StringBuilder message = new StringBuilder("<!--xml version=\"1.0\" encoding=\"UTF-8\"?-->"); message.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap= \"http://schemas.xmlsoap.org/soap/envelope/\">"); message.append(" <soap:Body>"); message.append(" <GetQuote xmlns=\"http://www.webserviceX.NET/\">"); message.append(" <symbol>").append("@").append("</symbol>"); message.append(" </GetQuote>"); message.append(" </soap:Body>"); message.append("</soap:Envelope>"); // Create the connection where we're going to send the file. URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; // Set the appropriate HTTP parameters. httpConn.setRequestProperty("Content-Length", String.valueOf(new String(message).length())); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", "\"http://www.webserviceX.NET/GetQuote\""); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); // Everything's set up; send the XML that was read in to the service. OutputStream out = httpConn.getOutputStream(); out.write(new String(message).getBytes()); out.close(); // Read the response and write it to standard out. InputStream inputStream = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream); BufferedReader in = new BufferedReader(isr); StringBuilder response = new StringBuilder(); String inputLine; while ((inputLine = in .readLine()) != null) { response.append(inputLine); } in .close(); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } } <!--xml version="1.0" encoding="utf-8"?--><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln s:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmlns="http://www.webserviceX.NET/"><GetQuoteResult>exception</GetQuoteResult></GetQuoteResponse ></soap:Body></soap:Envelope> //http://examples7x.wicket.apache.org/stock/wicket/bookmarkable/org.apache.wicket.examples.source.SourcesPage?0&SourcesPage_class=org.apache.wicket.examples.stockquote.StockQuotePage&source=StockQuotePage.html

Thursday, July 14, 2016

Difference between abstract and interface

 interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)


1) Abstract class can have abstract and non-abstract methods.
Interface can have only abstract methods.

2) Abstract class doesn't support multiple inheritance.
Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.

4) Abstract class can have static methods, main method and constructor.
Interface can't have static methods, main method or constructor.

5) Abstract class can provide the implementation of interface.
Interface can't provide the implementation of abstract class.

6) The abstract keyword is used to declare abstract class.
The interface keyword is used to declare interface.

7) Example:
public abstract class Shape{
public abstract void draw();
}

Example:
public interface Drawable{
void draw();
}

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc
Methods in interface are public or public static but methods in abstract class can be private and protected too
Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.
Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

This article explains why default methods have been introduced in java 8 :  To enhance the Collections API in Java 8 to support lambda expressions.


You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:

You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.

public interface Actor{
   Performance say(Line l);
}
public interface Director{
   Movie direct(boolean goodmovie);
}

public interface ActorDirector extends Actor, Director{
...
}

Difference between comparable and comparator

java.util.Comparator 

java.lang.Comparable

Some time you write code to sort object of a class for which you are not the original author, or you don't have access to code. In these cases you can not implement Comparable and Comparator is only way to sort those objects.



1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc.       
Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.

2) Comparable affects the original class i.e. actual class is modified.                         
Comparator doesn't affect the original class i.e. actual class is not modified.

3) Comparable provides compareTo() method to sort elements.
Comparator provides compare() method to sort elements.

4) Comparable is found in java.lang package.
Comparator is found in java.util package.

5) We can sort the list elements of Comparable type by Collections.sort(List) method.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.

public class Country implements Comparable{
    int countryId;
    String countryName;
    
    
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }
    
    @Override
    public int compareTo(Country country) {
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
    }
    
    
    public int getCountryId() {
        return countryId;
    }
    
    
    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }
    
    
    public String getCountryName() {
        return countryName;
    }
    
    
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
}

public class CountrySortByIdComparator implements Comparator{
    
    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }
    
}



ParameterComparableComparator
Sorting logicSorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objectsSorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
ImplementationClass whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by idClass whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling methodCollections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
PackageJava.lang.Comparable

Java.util.Comparator

Difference between collection and collections

Collection is a top level interface of java collection framework where as Collections is an utility class.

Collection : The root interface of Java Collections Framework.
Collection is an interface containing List, Set and Queue.

Collections : A utility class that is a member of the Java Collections Framework.
Collections is a class containing useful methods like Collections.sort() and Collections.synchronizedlist(), etc.

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface.

Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection.

Collections.max() This method returns maximum element in the specified collection.
Collections.min() This method returns minimum element in the given collection.
Collections.sort() This method sorts the specified collection.
Collections.shuffle() This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection() This method returns synchronized collection backed by the specified collection.
Collections.binarySearch() This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint() This method returns true if two specified collections have no elements in common.
Collections.copy() This method copies all elements from one collection to another collection.
Collections.reverse() This method reverses the order of elements in the specified collection.


Java 7 Features

Binary Literals

Strings in switch Statement

Try with Resources or ARM (Automatic Resource Management)

Multiple Exception Handling

underscore in literals

Type Inference for Generic Instance Creation using Diamond Syntax

Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods


Try-with-resources statement

this:

BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {
   br.close();
}
becomes:

try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();
}
You can declare more than one resource to close:

try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
{
 // code
}
Underscores in numeric literals

int one_million = 1_000_000;
Strings in switch

String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}
Binary literals

int binary = 0b1001_1001;
Improved Type Inference for Generic Instance Creation

Map> anagrams = new HashMap>();
becomes:

Map> anagrams = new HashMap<>();
Multiple exception catching

this:

} catch (FirstException ex) {
     logger.error(ex);
     throw ex;
} catch (SecondException ex) {
     logger.error(ex);
     throw ex;
}
becomes:

} catch (FirstException | SecondException ex) {
     logger.error(ex);
    throw ex;
}
SafeVarargs

this:

@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List... lists){
    for(List list : lists){
        System.out.println(list);
    }
}
becomes:

@SafeVarargs
public static void printAll(List... lists){
    for(List list : lists){
        System.out.println(list);
    }
}



Decorate Components with the JLayer Class:

The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.
Strings in switch Statement:

In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Type Inference for Generic Instance:

We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());
In comparison, the following example compiles:
List list2 = new ArrayList<>();
l.addAll(list2);
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:

catch (IOException e) {
    logger.log(e);
    throw e;
}
catch (SQLException e) {
    logger.log(e);
    throw e;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

catch (IOException|SQLException e) {
    logger.log(e);
    throw e;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
The java.nio.file package

The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7

Sunday, July 10, 2016

My Lab Manual

import java.io.*;

class AppendFile {
  public static void main(String[] args) {
    try {
      FileOutputStream out = new FileOutputStream(new File("new.txt"),
          true);
      String str = "There is always a way-if you're committed.\n";
     
//while(){
out.write(str.getBytes());
//}  
  out.close();
      System.out.println("String is appended.");
    } catch (IOException e) {
    }
  }
}/*


-----------------------------------------------------------------------------

(#)Vowels file.java
(#)5 aug
(#)

*/

// importing packages
import java.io.FileReader;
import java.io.BufferedReader;


public class lab$1{
public static void main(String args[])throws Exception{
System.out.println("vowels program");


FileReader fr= new FileReader("lab$1.java");
BufferedReader br= new BufferedReader(fr);

int c;
int count=0;
while((c=br.read())!=-1){
char temp=(char)c;
System.out.println(temp);

if(temp=='a'){
count++;
}
else if(temp=='e'){
count++;
}
else if(temp=='i'){
count++;
}
else if(temp=='o'){
count++;
}
else if(temp=='u'){
count++;
}
}


System.out.println("the number of vowels present in the system is...."+count);


}
}

-------------------------------------------------------------------------------------------

/*

(#)Raf.java
(#)5 aug 2011
(#)


*/


//importing packages
import java.io.RandomAccessFile;



public class lab$2{

public static void main(String args[])throws Exception{

System.out.println("random file");
RandomAccessFile rf= new RandomAccessFile("lab$2.java","r");

rf.seek(250);
int c;

StringBuffer sb= new StringBuffer();
for(int i=0;i<100 i="" p="">{
char temp=(char)rf.readByte();
sb=sb.append(temp);
//System.out.println(temp);


}


System.out.println("\n\n\n"+sb);

System.out.println("\n\nsize of the buffer: "+ sb.length());
}


}

---------------------------------------------------------------------------------
/*

(#)copy file
(#)5 aug 2011
(#)

*/

//importing packages
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class lab$3{
public static void main(String args[])throws Exception{
System.out.println("copy file");
FileInputStream in = new FileInputStream("lab$3.java");
FileOutputStream out = new FileOutputStream("temp.txt");
int c;
while((c=in.read())!=-1){
System.out.println((char)c);
out.write(c);


}





}



}
----------------------------------------------------------------------------------------------------------
/*
(#)employee file.java
(#)5 aug 2011
*/
//importing packages
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;

public class lab$4{
public static void main(String args[])throws Exception{
System.out.println("employee record");
String[] s={"anand male","siva male","banu female","ram male","guru male","latha female","mala female","geetha female","selvam male","ragu male"};

String memp[]= new String[10];
String femp[]= new String[10];

File f= new File("employee.txt");
f.createNewFile();
FileReader fr= new FileReader(f);
BufferedReader br = new BufferedReader(fr);
//Scanner in= new Scanner(fr);
FileWriter fw= new FileWriter("employee.txt");
PrintWriter pw= new PrintWriter(fw);

int fc=0;
int mc=0;

for(int i=0;i<10 i="" p="">//System.out.println(s[i]);
pw.println(s[i]);
}
pw.flush();
pw.close();

String temp;
while((temp=br.readLine())!=null){
if((temp.indexOf("female"))!=-1){

femp[fc]=temp;
//System.out.println(temp);
fc++;

}
else{
memp[mc]=temp;
//System.out.println(temp);
mc++;
}
}


System.out.println("\n\n\nMale employees");
for(int i=0;iSystem.out.println(memp[i]);

}

System.out.println("\n\n\nFemale employees");
for(int i=0;iSystem.out.println(femp[i]);

}

/*while(in.hasNextLine()){
System.out.println(in.nextLine());
}*/






}


}

----------------------------------------------------------------------------------------

/*
(#)employee file.java
(#)5 aug 2011
*/
//importing packages


import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.File;
import java.util.StringTokenizer;
public class lab$5{
public static void main(String args[])throws Exception{
System.out.println("employee record");
String[] s={"anand 20000 mgr","siva 2000 clrk","banu 10000 prog"};

File f= new File("employee.txt");
File f1= new File("nemployee.txt");
File f2= new File("above10k.txt");
File f3= new File("below10k.txt");


f.createNewFile();
f1.createNewFile();
f2.createNewFile();
f3.createNewFile();

FileReader fr= new FileReader(f);
FileReader fr1= new FileReader(f1);
FileReader fr2= new FileReader(f2);
FileReader fr3= new FileReader(f3);

BufferedReader br = new BufferedReader(fr);
BufferedReader br1 = new BufferedReader(fr1);
BufferedReader br2 = new BufferedReader(fr2);
BufferedReader br3 = new BufferedReader(fr3);


FileWriter fw= new FileWriter("employee.txt");
FileWriter fw1= new FileWriter("nemployee.txt");
FileWriter fw2= new FileWriter("above10k.txt");
FileWriter fw3= new FileWriter("below10k.txt");

PrintWriter pw= new PrintWriter(fw);
PrintWriter pw1= new PrintWriter(fw1);
PrintWriter pw2= new PrintWriter(fw2);
PrintWriter pw3= new PrintWriter(fw3);



for(int i=0;i<3 i="" p="">//System.out.println(s[i]);
pw.println(s[i]);
}

pw.flush();

String ename[]= new String[5];
String ecat[]= new String[5];
String ebpay[]= new String[5];
String egpay[]= new String[5];
String enetpay[]= new String[5];
String eallow[]= new String[5];
String edet[]= new String[5];

String temp;
int i=0;
StringTokenizer st= null;
while((temp=br.readLine())!=null){

//System.out.println(temp);

st= new StringTokenizer(temp);

while(st.hasMoreTokens()){
ename[i]=st.nextToken();
ebpay[i]=st.nextToken();
ecat[i]=st.nextToken();
if(ecat[i].equals("mgr")){
eallow[i]="1000";
int t1,t2,t3;
t1=Integer.parseInt(ebpay[i]);
t2=Integer.parseInt(eallow[i]);
t3=t1+t2;
egpay[i]=egpay[i].valueOf(t3);
double d;
d=t1*0.1;
edet[i]=edet[i].valueOf(d);
d=(double)t3-d;
enetpay[i]=enetpay[i].valueOf(d);
}

else if(ecat[i].equals("clrk")){
eallow[i]="500";
int t1,t2,t3;
t1=Integer.parseInt(ebpay[i]);
t2=Integer.parseInt(eallow[i]);
t3=t1+t2;
egpay[i]=egpay[i].valueOf(t3);
double d;
d=t1*0.1;
edet[i]=edet[i].valueOf(d);
d=(double)t3-d;
enetpay[i]=enetpay[i].valueOf(d);
}
else if(ecat[i].equals("prog")){
eallow[i]="100";
int t1,t2,t3;
t1=Integer.parseInt(ebpay[i]);
t2=Integer.parseInt(eallow[i]);
t3=t1+t2;
egpay[i]=egpay[i].valueOf(t3);
double d;
d=t1*0.1;
edet[i]=edet[i].valueOf(d);
d=(double)t3-d;
enetpay[i]=enetpay[i].valueOf(d);

}

}
i++;
}

String temp1;
for(int j=0;j<3 j="" p="">temp1=ename[j]+" "+ebpay[j]+" "+egpay[j]+" "+enetpay[j]+" "+edet[j]+" "+eallow[j];
pw1.println(temp1);
System.out.println("b: "+ebpay[j]);
System.out.println("g: "+egpay[j]);
System.out.println("d: "+edet[j]);
System.out.println("a: "+eallow[j]);
System.out.println("n: "+enetpay[j]);
double tvar;
tvar=Double.parseDouble(enetpay[j]);
if(tvar>10000){
pw2.println(temp1);
}
else{
pw3.println(temp1);
}

}
pw1.flush();
pw2.flush();
pw3.flush();

}
}

-------------------------------------------------------------------
import java.lang.String;

public class lab$6{
public static void main(String args[])throws Exception{

System.out.println("util package");

String s="E - EXPERT SOLUTIONS";

System.out.println("String: "+s);

System.out.println("\n\ns.charAt(5): "+s.charAt(5));

System.out.println("\n\ns.indexOf('T'): "+s.indexOf("T"));

String name= "OFFICE DEPOT, COIMBATORE 641002";

System.out.println("\n\nString : "+name+"\n\nname.substring(7,12):  "+name.substring(7,12)+"\n\nname.substring(14,24): "+name.substring(14,24)+"\n\nname.substring(25)

: "+name.substring(25));

String bomb="Bomb blast";

System.out.println("\n\nstring: "+bomb);

System.out.println("\n\nbomb.replace('B','C'): "+bomb.replace('B','C'));

System.out.println("\n\nbomb.replace('o','a'): "+bomb.replace('o','a'));

String st="feature lies in ecommerce";

int begin=7;
int end=11;

char[] buffer= new char[end-begin];

//line.getChars(begin,end,buffer,0);

//System.out.println(buffer);


String a="jini";
String A= "JINI";
System.out.println(a.equals(A));
System.out.println(a.equalsIgnoreCase(A));



int pincode=1234;

StringBuffer sb= new StringBuffer(30);

String s3;
s3= sb.append("pincode: ").append(pincode).toString();
System.out.println(s3);


StringBuffer sb4= new StringBuffer("software park " );

sb4.insert(9,"techno");
System.out.println(sb4);
}
}

------------------------------------------------------------------------------------
import java.util.StringTokenizer;

public class lab$7{
public static void main(String args[])throws Exception{

StringTokenizer st= new StringTokenizer("abc xyz blah blah");

String temp[]= new String[10];

int i=0;

while(st.hasMoreTokens()){
String t;
temp[i]= new StringBuffer(st.nextToken()).reverse().toString();
i++;

}


for(int j=0;j{

System.out.println(temp[j]);
}

}
}

--------------------------------------------------------------------------------------------------

import java.io.BufferedReader;
import java.util.Scanner;
import java.io.InputStreamReader;

public class test$1{

public static void main(String args[])throws Exception{

System.out.println("hello world");

Scanner in = new Scanner(System.in);

System.out.println(in.nextLine());

System.out.println(in.next());


InputStreamReader in1 = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in1);

String str;
str= br.readLine();
System.out.println(str);

int n;
n=Integer.parseInt(br.readLine());

System.out.println(n);
}

}

------------------------------------------------------------------------------
--------------------------------------------------------------------------

public class Test$10{
public static void main(String args[]){
System.out.println("Notepad program");
new Notepad();
}
}
/*

(#)program for applet demo 26 aug

*/

/*





*/

import java.awt.Dimension;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Date;
import java.util.Random;

public class test$11 extends Applet implements Runnable
{

Date d;

public void init(){
System.out.println("init method");
Thread t= new Thread(this);
t.start();

}
/*public void start(){
System.out.println("start method");
//repaint();
//d=new Date();


}*/

public void run(){
System.out.println("run method");

while(true){
repaint();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){

}

}


}
public void stop(){
System.out.println("stop method");
}
public void update(Graphics g){
System.out.println("update method");
paint(g);
}
public void destroy(){
System.out.println("destroy method");
}
public void paint(Graphics g){
Random r= new Random();
Dimension d1= getSize();
d=new Date();
System.out.println("height"+ d1.height);
 int x= r.nextInt(d1.height)+1;
 int y=r.nextInt(d1.width)+1;
System.out.println("x"+x+"y"+y);
//g.drawString("hello world",x,y);
//g.drawString(d.toString(),x,y);
g.fillRect(x,y,5,5);
}

}

--------------------------------------------------------------------------------
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Dimension;
/*



*/



public class test$12 extends Applet implements Runnable
 {

int x=1024;
int y=768;
int a;
int b;

public void init(){
Thread t= new Thread(this);
t.start();
}

public void run(){
for (int i=1;i{
for(int j=1;j{
a=j;
b=i;
repaint();
try{
Thread.sleep(10);
}
catch(Exception e)
{
}
}
}


}
public void paint(Graphics g)
{
System.out.println("paint"+a+b);
g.drawOval(a,b,50,50);

}


}

----------------------------------------------------------------------------------------
/*
(#) thread program demo 23 aug 2011
(#) file Test$13.java
*/


class gm extends Thread{

public void run(){
while(true){
try{
Thread.sleep(1000);
System.out.println("Good Morning");
}
catch(InterruptedException e){
}
}
}
}

class hello extends Thread{

public void run(){
while(true){
try{
Thread.sleep(2000);
System.out.println("Hello");

}
catch(InterruptedException e){
}
}

}
}

class welcome extends Thread{

public void run(){

while(true){
try{
Thread.sleep(3000);
System.out.println("welcome");

}
catch(InterruptedException e){
}
}

}

}

----------------------------------------------------------------------------------------
public class Test$13{
public static void main(String args[]){

System.out.println("thread program");

gm g= new gm();
hello h= new hello();
welcome w= new welcome();
g.start();
h.start();
w.start();


}
}
-----------------------------------------------------------------------------------------------
/*
(#) thread prog demo 23 aug 2011
(#) file: test$14.java

*/

class odd extends Thread{
odd(){
super("odd thread");
}

public void run(){

for (int i=0;i<50 i="" p="">if ((i%2)!=0){
System.out.println("Odd Thread : " + i );
}

}


}

}


class even extends Thread{
even(){
super("even thread");
}

public void run(){

for (int i=0;i<50 i="" p="">if ((i%2)==0){
System.out.println("Even Thread: "+ i);
}

}


}

}

--------------------------------------------------------

public class test$14{
public static void main(String args[]){

System.out.println("Thread program");

odd o = new odd();
even e= new even();
o.start();
e.start();

}


}
-------------------------------------------------------------------------------------------
/*
(#) thread prog demo 23 aug 2011
(#) file: test$14.java

*/

class odd extends Thread{
odd(){
super("odd thread");
}

public void run(){

for (int i=0;i<50 i="" p="">if ((i%2)!=0){
System.out.println("Odd Thread : " + i );
}

}


}

}


class even extends Thread{
even(){
super("even thread");
}

public void run(){

for (int i=0;i<50 i="" p="">if ((i%2)==0){
System.out.println("Even Thread: "+ i);
}

}


}

}


------------------------------------------------------------------------------------------------------
public class test$15{
public static void main(String args[]){

System.out.println("Thread program");

odd o = new odd();
even e= new even();
o.setPriority(Thread.MAX_PRIORITY);
e.setPriority(Thread.MIN_PRIORITY);
//e.setPriority(1);
//o.setPriority(10);
e.start();
o.start();

}


}
class sroot implements Runnable{


public void run(){
System.out.println("square root of first 30 natural numbers");
for (int i=1;i<=30;i++){
System.out.println("square root of "+i+" "+ Math.sqrt(i));
}
}


}

------------------------------------------------------------------------

public class test$16{

public static void main(String args[]){

//sroot s=new sroot();
//new Thread(s).start();
new Thread(new sroot()).start();
}

}

-------------------------------------------------------------------
/*
(#) thread program demo 23 aug 2011
(#) test$17.java
*/


class factorial extends Thread{
public void run(){
System.out.println("factorial of first twenty natural numbers: ");

long s=1;
int n=1;
while(n!=30){
s=1;
for (int i=1;i<=n;i++){

s=s*i;
}
System.out.println("factorial of "+n+ " is..."+s );
n++;
}

}
}

----------------------------------------------------------------------------------------
public class test$17{
public static void main(String args[]){

factorial f = new factorial();
f.start();

}
}
import java.io.BufferedReader;
import java.io.FileReader;
public class test$18{
public static void main(String args[]){

System.out.println("hello world");

String s="test$18.java";

try{
FileReader fr= new FileReader(s);

BufferedReader br = new BufferedReader(fr);

while(br.readLine()!=null)
System.out.println(br.readLine());



br.close();
}
catch (Exception e){}

}
}
---------------------------------------------------------------------
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class test$19{
public static void main(String args[]){



System.out.println("test program");

System.out.println((int)(Math.random()*1000));
System.out.println(Math.floor(Math.random() * 41) + 10);
System.out.println(Math.random()*41);
NumberFormat d= new DecimalFormat("0.000");
DecimalFormat d1= new DecimalFormat("0.000");
//NumberFormat d2= new NumberFormat("0.000");

double i=15.24566;

//System.out.println(d2.format(i));
System.out.println(d1.format(i));

System.out.println(d.format(i));
System.out.println(Math.round(i));

System.out.printf("%1$.2f", i);
}}


-------------------------------------------------------------------------
/*

program for abstract class


*/

abstract class hello{


void print(){

System.out.println("hello world print method");

}

}


------------------------------------------------------------------------------

public class test$2 extends hello {
public static void main(String args[]){

System.out.println("hello world");

test$2 t = new test$2();
hello h;
h=t;
h.print();

//hello h = new hello();
//h.print();

}


}
-----------------------------------------------------------------------------
import java.net.*;
import java.io.*;
public class test$20 {
    public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.dinamalar.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
 System.out.println(inputLine);
in.close();
    }
}
import java.lang.Thread;


class mythread extends Thread{
mythread(String s){

super(s);

}

public void run(){

for(int i=0;i<5 i="" p="">{
try{
join();
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName());
//yield();
}

}
}

--------------------------------------------------------------------
public class test$21
{
public static void main(String args[])throws Exception
{
int a;
//System.out.println("test program"+a);


mythread one = new mythread("one");
mythread two = new mythread("two");

one.start();
two.start();


String test = "This is a test string";
String[] tokens = test.split(" ");
System.out.println(tokens.length);


}
}

-----------------------------------------------------------------
import java.io.*;

/*

(#) prog file demo
(#) 31 aug 2011
*/

public class test$22{
public static void main(String args[])throws Exception {
System.out.println("hello world ");
System.out.println("Enter file name?");
FileReader fr = new FileReader("test$22.java");
BufferedReader br = new BufferedReader(fr);
while(br.readLine()!=null){

System.out.println(br.readLine());

}

br.close();
}
}import java.io.StreamTokenizer;
import java.io.FileReader;

public class test$23{

public static void main(String args[])throws Exception {

System.out.println("hello world ");

try{
StreamTokenizer s= new StreamTokenizer(new FileReader("test$23.java"));
while(s.nextToken()!=StreamTokenizer.TT_EOF){

if (s.ttype==StreamTokenizer.TT_WORD){

System.out.println(s.sval);
}



}

}
catch(Exception e){
}



}}

-------------------------------------------------------------------------------------------------
import java.io.StreamTokenizer;
import java.io.FileReader;


public class test$24{
public static void main(String args[]){
System.out.println("hello world ");



try{

StreamTokenizer s= new StreamTokenizer(new FileReader("numbers.txt"));

while(s.nextToken()!=StreamTokenizer.TT_EOF){

if(s.ttype==StreamTokenizer.TT_NUMBER){

System.out.println(s.nval);

}

}

}
catch(Exception e ){


}





}
}


-------------------------------------------------------------------------------------------------

import java.net.URL;

public class test$25{

public static void main(String args[])throws Exception{

System.out.println("Hello world program");

URL u= new URL("http://www.cs.rpi.edu/");

System.out.println("protocal: "+u.getProtocol());
System.out.println("host:  "+ u.getHost());
System.out.println("file name: "+ u.getFile());
System.out.println("port: "+ u.getPort());
System.out.println("refernece: "+u.getRef());

}



}
-------------------------------------------------------------------------------------------------

import java.io.*;


public class test$26{
public static void main(String args[]){
System.out.println("test program");
try{
StringReader s=new StringReader(" abc xcs werw werwe wrewrw sf");
StreamTokenizer st= new StreamTokenizer(s);
//while(st.nextToken()!=StreamTokenizer.TT_EOF){
while(st.nextToken()!=-1){
//while(st.nextToken()!=StreamTokenizer.TT_EOF){
if(st.ttype==StreamTokenizer.TT_WORD){
System.out.println(st.sval);
}
}

}
catch(Exception e){}


}
}

-------------------------------------------------------------------------------------------------

import java.io.*;
import java.util.*;

public class test$27{
public static void main(String args[])throws Exception{

System.out.println("test program");


 DataInputStream dis=new DataInputStream(System.in);

        System.out.println("Enter a sentence: ");
        String s=dis.readLine();
        StringTokenizer st=new StringTokenizer(s);
        while (st.hasMoreTokens())
            System.out.println(st.nextToken());





}
}

-------------------------------------------------------------------------------------------------


public class test$28{
public static void main(String args[]){
System.out.println("test program");

String s1=new String("hello ");

String s2=new String("abc");

Object[] o =new Object[2];

o[0]=s1;
o[1]=s2;

System.out.println(o[1]);

}
}public class test$29{
public static void main(String args[]){

System.out.println("test program");

String s="hello balaji hello hello, hello.";

System.out.println(s);

s=s.replace("hello","hai");

System.out.println(s);

}

}

-------------------------------------------------------------------------------------------------

import pack.*;

import pack.subpack.*;

public class test$3 {

public static void main(String args[])throws Exception{

pack1 p= new pack1();

sub s= new sub();

System.out.println("hai hello"+p.i+s.j);

}



}

-------------------------------------------------------------------------------------------------

class test$30 {
    public static void main(String[] args) {
        System.out.println(System.getProperty("user.home"));
    }
}
import java.awt.Font;

import java.awt.GraphicsEnvironment;


public class test$31 {

    public static void main(String[] args) {

        //
        // Get all available fonts from GraphicsEnvironment
 
          GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        Font[] fonts = ge.getAllFonts();

      //
        // Iterates all available fonts and get their name and family name

        for (Font font : fonts) {
            String fontName = font.getName();

            String familyName = font.getFamily();
 
         
            System.out.println("Font: " + fontName + "; family: " + familyName);

        }
    }
}
//Sample Java Program to generate the message digest from a given input file:


-------------------------------------------------------------------------------------------------


import java.security.MessageDigest;
import java.io.*;
import sun.misc.*;

public class test$32 {
/** * The only argument is the name of the file to be digested. */

public static void main (String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java DigestFile filename");

System.exit(1);
} // Create a message digest
MessageDigest md = MessageDigest.getInstance("MD5"); BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[0]));
int theByte = 0;
while ((theByte = in.read()) != -1) { md.update((byte)theByte);
}
in.close();
byte[] theDigest = md.digest(); System.out.println(new BASE64Encoder().encode(theDigest)); }
}

PrinterJob myPrinterJob = PrinterJob.getPrinterJob();
    myPrinterJob.setPrintable(new MyDocument());
    try
    {
      myPrinterJob.print();
    }
    catch (PrinterException ex)
    {
      JOptionPane.showConfirmDialog(null, ex.getMessage(), "Print Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
    }




class MyDocument implements Printable
{
  public int print(Graphics g, PageFormat pf, int pageIndex)
  {
  if (pageIndex > LoanCalculator.numberOfPages - 1)
  {
  return NO_SUCH_PAGE;
  }
  // print repayment knowing loan values
  // makes no assumptions about how many times print method is called per page
    Graphics2D g2D = (Graphics2D) g;
    Font printFont = new Font("Courier New", Font.PLAIN, 12);
    Rectangle2D fontRect = printFont.getStringBounds("A", g2D.getFontRenderContext());
    double currentY = pf.getImageableY() + fontRect.getHeight();
    g2D.setFont(printFont);
    // Print header
    g2D.drawString("Loan Repayment Schedule - Page " + String.valueOf(pageIndex + 1), (int) pf.getImageableX(), (int) currentY);
    currentY += 2 * fontRect.getHeight();
    g2D.drawString("Loan Amount: $" + new DecimalFormat("0.00").format(LoanCalculator.loan), (int) pf.getImageableX(), (int) currentY);
    currentY += fontRect.getHeight();
    g2D.drawString("Interest Rate: " + new DecimalFormat("0.00").format(LoanCalculator.interest) + "%", (int) pf.getImageableX(), (int) currentY);
    currentY += fontRect.getHeight();
    g2D.drawString("Number of Months: " + String.valueOf(LoanCalculator.months), (int) pf.getImageableX(), (int) currentY);
    currentY += fontRect.getHeight();
    g2D.drawString("Payment Amount: $" + new DecimalFormat("0.00").format(LoanCalculator.payment), (int) pf.getImageableX(), (int) currentY);
    currentY += 2 * fontRect.getHeight();
    g2D.setFont(new Font("Courier New", Font.BOLD, 12));
    g2D.drawString("Month     Payment     Principal     Interest     Balance", (int) pf.getImageableX(), (int) currentY);
    g2D.setFont(new Font("Courier New", Font.PLAIN, 12));
    currentY += fontRect.getHeight();
    double b;
    double pa;
    double p;
    double i;
    int mstart;
    int mend;
    // compute balance remaining at start of current page
    b = LoanCalculator.loan;
    if (pageIndex !=0)
    {
    for (int m = 1; m <= (pageIndex * LoanCalculator.monthsPerPage); m++)
    {
      // Find interest
      i = LoanCalculator.interest * b / 1200;
      // Round to two decimals
i = Double.valueOf(new DecimalFormat("0.00").format(i)).doubleValue();
// Calculate balance
        b -= LoanCalculator.payment - i;
    }
    }
    // find month range on current page
    mstart = (pageIndex * LoanCalculator.monthsPerPage) + 1;
    mend = mstart + LoanCalculator.monthsPerPage - 1;
    if (mend > LoanCalculator.months)
    {
    mend = LoanCalculator.months;
    }
    // compute current page payment schedule
for (int m = mstart; m <= mend; m++)
{
      // Find interest
      i = LoanCalculator.interest * b / 1200;
      // Round to two decimals
i = Double.valueOf(new DecimalFormat("0.00").format(i)).doubleValue();
// Determine payment amount - Compute principal and balance
      if (m != LoanCalculator.months)
      {
      pa = LoanCalculator.payment;
        p = pa - i;
        b -= p;
      }
      else
      {
        // Adjust last payment to payoff balance
        pa = b + i;
        p = b;
        b = 0;
      }
      // Print payment line
    currentY += fontRect.getHeight();
      g2D.drawString(paymentLine(m, pa, p, i, b), (int) pf.getImageableX(), (int) currentY);
    }
    return PAGE_EXISTS;
  }
 
  private String paymentLine(int m, double pa, double p, double i, double b)
  {
  // build up line with payoff information
  //  using info from Chapter 6
  char[] pl = new char[60];
  String s;
  // blank out line with spaces
  for (int j = 0; j < 60; j++)
  {
  pl[j] = ' ';
  }
    // Months
    s = String.valueOf(m);
    midLine(s, pl, 4 - s.length());
    // Payment amount
s = new DecimalFormat("0.00").format(pa);
    midLine(s, pl, 17 - s.length());
    // Principal
s = new DecimalFormat("0.00").format(p);
    midLine(s, pl, 31 - s.length());
    // Interest
s = new DecimalFormat("0.00").format(i);
    midLine(s, pl, 44 - s.length());
    // Balance
s = new DecimalFormat("0.00").format(b);
    midLine(s, pl, 56 - s.length());
    // convert character array to string
    s = String.copyValueOf(pl);
    return (s);
  }
 
  private void midLine(String inString, char[] charLine, int pos)
  {
  for (int i = pos; i < pos + inString.length(); i++)
  {
  charLine[i] = inString.charAt(i - pos);
  }
  }
 }

-------------------------------------------------------------------------------------------------


import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JPanel;

public class Test$34 extends JPanel {

  public static void main(String[] args) {
    try {
      PrinterJob pjob = PrinterJob.getPrinterJob();
      pjob.setJobName("Graphics Demo Printout");
      pjob.setCopies(1);
      pjob.setPrintable(new Printable() {
        public int print(Graphics pg, PageFormat pf, int pageNum) {
          if (pageNum > 0) // we only print one page
            return Printable.NO_SUCH_PAGE; // ie., end of job

          pg.drawString("www.java2s.com", 10, 10);

          return Printable.PAGE_EXISTS;
        }
      });

      if (pjob.printDialog() == false) // choose printer
        return;
      pjob.print();
    } catch (PrinterException pe) {
      pe.printStackTrace();
    }
  }

}

-------------------------------------------------------------------------------------------------

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;

 class JavaWorldPrintExample1 implements Printable {
  public static void main(String[] args) {

    JavaWorldPrintExample1 example1 = new JavaWorldPrintExample1();
    System.exit(0);
  }

  //--- Private instances declarations
  private final double INCH = 72;

  /**
   * Constructor: Example1
   *
   *
   */
  public JavaWorldPrintExample1() {

    //--- Create a printerJob object
    PrinterJob printJob = PrinterJob.getPrinterJob();

    //--- Set the printable class to this one since we
    //--- are implementing the Printable interface
    printJob.setPrintable(this);

    //--- Show a print dialog to the user. If the user
    //--- click the print button, then print otherwise
    //--- cancel the print job
    if (printJob.printDialog()) {
      try {
        printJob.print();
      } catch (Exception PrintException) {
        PrintException.printStackTrace();
      }
    }

  }

  /**
   * Method: print
   *
   *
   * This class is responsible for rendering a page using the provided
   * parameters. The result will be a grid where each cell will be half an
   * inch by half an inch.
   *
   * @param g
   *            a value of type Graphics
   * @param pageFormat
   *            a value of type PageFormat
   * @param page
   *            a value of type int
   * @return a value of type int
   */
  public int print(Graphics g, PageFormat pageFormat, int page) {

    int i;
    Graphics2D g2d;
    Line2D.Double line = new Line2D.Double();

    //--- Validate the page number, we only print the first page
    if (page == 0) {  //--- Create a graphic2D object a set the default parameters
      g2d = (Graphics2D) g;
      g2d.setColor(Color.black);

      //--- Translate the origin to be (0,0)
      g2d.translate(pageFormat.getImageableX(), pageFormat
          .getImageableY());

      //--- Print the vertical lines
      for (i = 0; i < pageFormat.getWidth(); i += INCH / 2) {
        line.setLine(i, 0, i, pageFormat.getHeight());
        g2d.draw(line);
      }

      //--- Print the horizontal lines
      for (i = 0; i < pageFormat.getHeight(); i += INCH / 2) {
        line.setLine(0, i, pageFormat.getWidth(), i);
        g2d.draw(line);
      }

      return (PAGE_EXISTS);
    } else
      return (NO_SUCH_PAGE);
  }

} //Example1

import java.awt.print.PrinterJob;
public class Test$36{

public static void main(String args[]){

System.out.println("hello world");

PrinterJob pj=  PrinterJob.getPrinterJob();

pj.printDialog();

}





}

-------------------------------------------------------------------------------------------------

import java.io.BufferedReader;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import javax.swing.JPanel;

public class Test$37 extends JPanel {

  public static void main(String[] args)throws Exception {
    try {
      PrinterJob pjob = PrinterJob.getPrinterJob();
   //   pjob.setJobName("Graphics Demo Printout");
      pjob.setCopies(1);
      pjob.setPrintable(new Printable() {
        public int print(Graphics pg, PageFormat pf, int pageNum) {
          if (pageNum > 0) // we only print one page
            return Printable.NO_SUCH_PAGE; // ie., end of job
try{
FileReader fr = new FileReader("Test$37.java");
BufferedReader br = new BufferedReader(fr);

String temp=" ";
int i=30;
while((temp=br.readLine())!=null){
i=i+15;
 pg.drawString(temp, 50, i);
     
       
}

}catch(Exception e){}

return Printable.PAGE_EXISTS;
}
      });

      if (pjob.printDialog() == false) // choose printer
        return;
      pjob.print();
    } catch (Exception pe) {
      pe.printStackTrace();
    }
  }

}-------------------------------------------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

 class addremove extends JPanel implements ActionListener{
private JButton addbut;
private JButton revbut;
private JPanel panel1;
private JPanel panel2;

public addremove() {

addbut = new JButton ("Add");
revbut = new JButton ("Remove");
panel1 = new JPanel();
panel2 = new JPanel();

panel1.setBackground(Color.blue);
panel2.setBackground(Color.red);

setPreferredSize (new Dimension (218, 160));
setLayout (null);


add (addbut);
add (revbut);
add (panel2);


addbut.setBounds (20, 120, 80, 25);
revbut.setBounds (120, 120, 80, 25);
panel1.setBounds (20,10,180,60);
panel2.setBounds (20,10,180,60);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource() == addbut)
{
remove(panel2);

add(panel1);

}
else if (e.getSource() == revbut)
{
remove(panel1);

add(panel2);

}


}


public static void main (String[] args) {
JFrame frame = new JFrame ("addremove");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new addremove());
frame.pack();
frame.setVisible (true);
frame.setLocation(450,280);
frame.setResizable(false);
}
}
interface xyz{

 void print();
void print1();
}

class one implements xyz{
public void print(){
System.out.println("class one");
}
public  void print1(){
System.out.println("class one");
}

}

class two implements xyz{
public void print(){

System.out.println("class two");
}
public  void print1(){
System.out.println("class one");
}


}


public class test$4
{
public static void main(String args[]){

System.out.println("hello world");

one o= new one();


two t= new two();

t.print();
o.print();

}






}

public class test$40{
public static void main(String arfs[]){
new test$41();
}
}

public class test$41{
public test$41(){
System.out.println("hello world");
}
}

import java.util.Map;
import java.util.Properties;
import java.io.Console;
import java.io.PrintWriter;
public class test$42{
public static void main(String args[])throws Exception{
System.out.println("Shut down program");
Properties p = new Properties();
Runtime r= Runtime.getRuntime();
//r.exec("shutdown -l");
String temp;
p=System.getProperties();
//System.out.println(temp);
//System.out.println(System.getProperty("user.home"));
//System.out.println(System.getProperties());
//System.out.println(System.getProperty("sun.boot.library.path"));
//System.out.println(p.toString());
//System.out.println(System.getenv());
//Console.WriteLine("hello");
Console c= System.console();
String temp1=c.readLine();
char[] c1= c.readPassword("enter password: ");
System.out.println(c1);
System.out.println(temp1);
c.printf("esdfsd"+"hello","balaji");

PrintWriter out= c.writer();
out.println("hello world");
}




}

-------------------------------------------------------------------------------------------------

/*

(#)System program
(#)10 aug 2011
(#)author : bala


*/

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.StringTokenizer;
import java.util.Properties;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JOptionPane;
import java.lang.Runtime;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

public class test$43 extends JFrame implements ActionListener {

private JButton sdown;
private JButton loff;
private JButton rstrt;
private JButton suser;
private JButton env;
private JButton prp;
private JButton abt;
private JPanel p;
private Container ct;
private Runtime r;
private Properties pr;
private StringTokenizer st;
private JTextArea ta;

public test$43(){

//super("System program");
sdown= new JButton("Shut Down");
loff=new JButton("Log Off");
rstrt=new JButton("Restart");
suser=new JButton("Switch User");
env=new JButton("Environment Variables");
prp=new JButton("System Properties");
abt= new JButton("About");
p= new JPanel();
//p.setLayout(new FlowLayout());

r= Runtime.getRuntime();
ct= getContentPane();
ct.setLayout(new FlowLayout());
ct.add(sdown);
ct.add(loff);
ct.add(rstrt);
ct.add(suser);
ct.add(env);
ct.add(prp);
ct.add(abt);

sdown.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
try{
r.exec("shutdown -s");
}
catch(Exception e1){
}
}
}
);
loff.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
try{
r.exec("shutdown -l");
}
catch(Exception e1){}
}
}
);
rstrt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
try{
r.exec("shutdown -r");
}
catch(Exception e1){}
}
}
);



suser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
try{
r.exec("shutdown -l");
}
catch(Exception e1){}



}
}
);

env.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());

//JOptionPane.showMessageDialog(null,"\n"+System.getenv());
String temp;
temp=JOptionPane.showInputDialog("Enter environment variable Name??");
System.out.println(temp);

if(temp.equals("")){
JOptionPane.showMessageDialog(null,"\nfield not be empty");
}
else{
JOptionPane.showMessageDialog(null,"\n"+System.getenv(temp));
}


}
}
);
prp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());


pr= new Properties();
pr=System.getProperties();
String temp=pr.toString();
String temp1="";
System.out.println(temp);
st= new StringTokenizer(temp,",");
int i=0;
while(st.hasMoreTokens()){
i++;
temp1=temp1+"\n"+st.nextToken();
}
JFrame jf= new JFrame();
ta= new JTextArea();
ta.setText(temp1);
jf.setVisible(true);
jf.setSize(1024,768);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
jf.add(ta);
System.out.println(temp1);
//new Text(temp1);
}
}
);


abt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(e.getActionCommand());
JOptionPane.showMessageDialog(null,"\nSystem Program\nVersion 1.0\nCopy Right@ 2011 SSK Technologies\n");
}
}
);










setResizable(false);
setSize(400,100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("System program");
}

public void actionPerformed(ActionEvent e){


}


public static void main(String args[])throws Exception{

System.out.println("shutdown gui");

new test$43();


}

}
-------------------------------------------------------------------------------------------------

import java.io.*;
import java.util.Properties;
class App
{
    public static void main( String[] args )
    {
    Properties prop = new Properties();

    try {
    //set the properties value
    prop.setProperty("database", "localhost");
    prop.setProperty("dbuser", "mkyong");
    prop.setProperty("dbpassword", "password");

    //save properties to project root folder
    prop.store(new FileOutputStream("config.properties"), null);

    } catch (IOException ex) {
    ex.printStackTrace();
        }
    }
}import java.lang.String;
public class test$5{

test$5(String s){


}
public String toString(String s){

return s;
}
public static void main(String args[]){

System.out.println("hello world");


String s="hello ";
String ss= "balaji";

System.out.println(s+ss);

System.out.println(s.equals(ss));

char sss;
sss=s.charAt(0);
System.out.println(sss);

sss=ss.charAt(0);
System.out.println(sss);

//string str= s.subString(1,3);

test$5 t= new test$5("test$5 program");

System.out.println(t);
}
}class ExA extends Exception{
ExA(String s ){
super(s);
}
}

class ExB extends Exception{
ExB(String s){
super(s);
}
}

-------------------------------------------------------------------------------------------------

public class test$6{
public static void main(String args[])
{
System.out.println("hello world");
try{
print();

}
catch(ExB e){

System.out.println(e);
e.printStackTrace();
}

}

public static void print()throws ExB{

System.out.println("print method");
throw new ExB("just testing..");
}


}

-------------------------------------------------------------------------------------------------

public class Test$7{

public static void main(String args[]){

System.out.println("test 7 program");

float f;
f=100.25034500f;

double d;
d=4646.1634;

System.out.println(f);
System.out.println(d);
}


}interface base3{
}
interface base4{
}



class base{

}
class base1{

}

class derived1 extends base implements base3,base4 {

}

class derived2 extends base{

}


public class Test$8
{
public static void main(String args[]){

System.out.println("test program");
}

}public class test$9
{

public static void main(String args[]){

System.out.println("test9 program");


String s=new String("one");

s=new String("two");

System.out.println(s);

StringBuffer s1=new StringBuffer("hello");

System.out.println(s1);

}


}

-------------------------------------------------------------------------------------------------

Saturday, July 2, 2016

Array and Object Creation - JavaScript


var arr =[1,2,3];

var arr = new Array(1,2,3);

var arr = new Array(); //empty Array

arr.push(10);
arr.pop();

var obj = new Object();
obj.test ="hello";

var obj= { "test" : "hello"};


function myFunction() {
    alert('It works!');
}
var name = 'myFunction';
window[name].call();


var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function(i) {
        return this.firstName + " " + this.lastName+i;
    }
};
document.getElementById("demo").innerHTML = myObject.fullName(1);
//John Doe1



//Passing value via constructor
function myFunction(arg1, arg2) {
    this.firstName = arg1;
    this.lastName  = arg2;
}
alert(JSON.stringify(new myFunction("John","Doe")))
var x = new myFunction("John","Doe")
//{"firstName":"John","lastName":"Doe"}

alert(JSON.stringify(new myFunction())) //{}

alert(JSON.stringify(new myFunction("John"))) //{"firstName":"John"}


//private method
var test = function(i){
alert(i);
}
//public method
this.test = function(i){
alert(i);
}
test("123");


var x = { foo : 1};
var output = (function(){
    delete x.foo;
    return x.foo;
  })();
alert(x.foo); //undefined
delete function used to delete the object properties, not a variable..


var Employee = {
  company: 'xyz'
}
var emp1 = Object.create(Employee);
//delete emp1 .company; //delete not working since its a referanced property.
alert(emp1 .company);

var foo = function(){ return 12; };
var foo = function bar(){ return 12; };
alert(foo());

function bar(){ this.y=12; return this.x=12; };
var dog = new bar();   // new return this referance .. eventhough it return anything
//alert(JSON.stringify(dog));
//alert(Object.keys(dog))
for(key in dog){}

function greeter(name, age) {
return name + " says howdy!! He is " + age + " years old";
}
// Generate the message
var message = greeter("James", 23);
//James says howdy!! He is 23 years old//



a.x=10;
a["x"] = 10;

isNaN
TypeOf
Undefined
this
alert
confirm
prompt
null
==
===
.value
.innerHTML


for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ alert(i); });
  document.body.appendChild(btn);
}

A callback function is executed after the current effect is 100% finished.
$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

Number()
parseInt()
parseFloat()

var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN

JSON.parse(obj);
JSON.stringify(obj);

Window Object
Document Object
Form Object

var uri = “EmpDetails.asp?Emp=årpit&mode=edit”;
document.write(encodeURI(uri) + “
”);
document.write(decodeURI(uri) + “
”);

EmpDetails.asp?Emp=%C3%A5&mode=edit
EmpDetails.asp?Emp=årpit&mode=edit.


The splice() method adds/removes items to/from an array, and returns the removed item(s).
array.splice(index,howmanyItemfordelete,item1,.....,itemX)


var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2, 0);//Banana,Orange,Apple,Mango

fruits.splice(2, 1);//Banana,Orange,Mango

fruits.splice(2, 2);//Banana,Orange

 fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango

fruits.splice(2, 1, "Lemon", "Kiwi");//Banana,Orange,Lemon,Kiwi,Mango

fruits.splice(2, 2, "Lemon", "Kiwi");//Banana,Orange,Lemon,Kiwi

splice always first delete and add the elements

array=[1,2,3];
number=2;
for(var i = array.length - 1; i >= 0; i--) {
    if(array[i] === number) {
       array.splice(i, 1); //1,3
//delete array[i]; //1,"",3
    }
}
alert(array);//1,3


உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...