Wednesday, 10 June 2015
Program sets up a String variable containing a paragraph of text of your choice. Extract the words from the text and sort them into alphabetical order
Code for Program sets up a String variable containing a paragraph of text of your choice. Extract the words from the text and sort them into alphabetical order in Java
import java.util.StringTokenizer;
classstring
{
publicstaticvoid main(String args[])
{
operations op = new operations();
op.getToken();
op.sort();
op.diffOp();
}
}
class operations
{
static String in="My first name is Vidyadhar and my last name is Yagnik";
static String arr[]=new String[30];
staticint c=0;
void getToken()
{
StringTokenizer st=new StringTokenizer(in," ");
while(st.hasMoreTokens())
{
arr[c]=st.nextToken();
c++;
}
System.out.println("The original string is:::"+in);
System.out.println("-------The Tokens of the strings--------");
for(int i=0;i<c;i++)
{
System.out.println(arr[i]);
}
}
void sort()
{
for(int i=0;i<c;i++)
{
for(int j=i+1;j<c;j++)
{
if(arr[j].compareToIgnoreCase(arr[i]) < 0)
{
String t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
System.out.println("--------The sorted array of strings---------");
for(int k=0;k<c;k++)
{
System.out.println(arr[k]);
}
}
void diffOp()
{
int space=0,capital=0,vowel=0;
//Count no. of white spaces,capital letters,vowels from the stringchar temp;
for(int i=0;i<in.length();i++)
{
temp=in.charAt(i);
if(temp==' ')
space++;
if(temp>=65 && temp<=90)
capital++;
if(temp=='a' || temp=='A' || temp=='e' || temp=='E' || temp=='i' || temp=='I' || temp=='o' || temp=='O' || temp=='u' || temp=='U')
vowel++;
}
System.out.println("The no. of white space is::"+space);
System.out.println("The no. of capital letter is::"+capital);
System.out.println("The no. of vowel is::"+vowel);
//replace space with '/'
String newString=new String(in);
newString=newString.replace(' ','/');
System.out.println("The replaced string is:::"+newString);
//reverse string
StringBuffer revers=new StringBuffer(in);
revers.reverse();
System.out.println("The reverse string is:::"+revers);
}
}
/*
Output
java string
The original string is:::My first name is Vidyadhar and my last name is Yagnik
-------The Tokens of the strings--------
My
first
name
is
Vidyadhar
and
my
last
name
is
Yagnik
--------The sorted array of strings---------
and
first
is
is
last
my
My
name
name
Vidyadhar
Yagnik
The no. of white space is::10
The no. of capital letter is::3
The no. of vowel is::13
The replaced string is:::My/first/name/is/Vidyadhar/and/my/last/name/is/Yagnik
The reverse string is:::kingaY si eman tsal ym dna rahdaydiV si eman tsrif yM
*/
Program, which creates a three thread. One thread display the numbers from 1 to 5, second thread display the square root of that number etc
Code for Program, which creates a three thread. One thread display the numbers from 1 to 5, second thread display the square root of that number etc in Java
class numbers implements Runnable
{
Thread t;
boolean running=true;
public numbers(String name, int p)
{
t=new Thread(this,name);
t.setPriority(p);
t.start();
}
publicvoid run()
{
System.out.println("\n"+t+ " start");
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
System.out.println(t+ " exiting");
}
}
class squareRoot implements Runnable
{
Thread t;
boolean running=true;
public squareRoot(String name,int p)
{
t=new Thread(this,name);
t.setPriority(p);
t.start();
}
publicvoid run()
{
System.out.println("\n"+t+ " start");
for(int i=1;i<=5;i++)
{
System.out.println(i*i);
}
System.out.println(t+ " exiting");
}
}
class ThreadPri
{
publicstaticvoid main(String args[])
{
new numbers("Numbers HIGH PRIORITY",Thread.MAX_PRIORITY);
new squareRoot("Square MIDDLE PRIORITY",Thread.NORM_PRIORITY);
Thread t=Thread.currentThread();
t.setPriority(Thread.MIN_PRIORITY);
t.setName("Cube LOW PRIORITY");
System.out.println("\n"+t+ " start");
for(int i=1;i<=5;i++)
{
System.out.println(i*i*i);
}
System.out.println(t+ " exiting");
}
}
/*
Output
Thread[Numbers HIGH PRIORITY,10,main] start
1
2
3
4
5
Thread[Numbers HIGH PRIORITY,10,main] exiting
Thread[Square MIDDLE PRIORITY,7,main] start
1
4
9
16
25
Thread[Square MIDDLE PRIORITY,7,main] exiting
Thread[Cube LOW PRIORITY,3,main] start
1
8
27
64
125
Thread[Cube LOW PRIORITY,3,main] exiting
*/
Write a class whose objects holds a current value and have a method to add that value, printing the new value
Code for Write a class whose objects holds a current value and have a method to add that value, printing the new value in Java
class Arr
{
int int_array[]=newint[5];
synchronized void add_to_array(int int_array[], int k)
{
for(int i=0; i<5; i++)
{
int_array[i]+=k;
System.out.println(int_array[i]);
}
}
}
class Caller implements Runnable
{
Arr A;
int array[]={1, 2, 3, 4, 5};
int val;
Thread t;
public Caller(Arr ar, int k)
{
A=ar;
val=k;
t=new Thread(this);
t.start();
}
publicvoid run()
{
System.out.println("Thread starts..");
A.add_to_array(array, val);
System.out.println("Thread stops..");
}
}
class ThreadArrAdd
{
publicstaticvoid main(String args[])
{
Arr A1=new Arr();
Caller ob1=new Caller(A1, 2);
Caller ob2=new Caller(A1, 4);
Caller ob3=new Caller(A1, 1);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted...");
}
}
}
/*
OUTPUT
Thread starts..
3
4
5
6
7
Thread stops..
Thread starts..
5
6
7
8
9
Thread stops..
Thread starts..
2
3
4
5
6
Thread stops..
*/
Write a class whose objects holds a current value and have a method to add that value, printing the new value
Code for Write a class whose objects holds a current value and have a method to add that value, printing the new value in Java
class Arr
{
int int_array[]=newint[5];
synchronized void add_to_array(int int_array[], int k)
{
for(int i=0; i<5; i++)
{
int_array[i]+=k;
System.out.println(int_array[i]);
}
}
}
class Caller implements Runnable
{
Arr A;
int array[]={1, 2, 3, 4, 5};
int val;
Thread t;
public Caller(Arr ar, int k)
{
A=ar;
val=k;
t=new Thread(this);
t.start();
}
publicvoid run()
{
System.out.println("Thread starts..");
A.add_to_array(array, val);
System.out.println("Thread stops..");
}
}
class ThreadArrAdd
{
publicstaticvoid main(String args[])
{
Arr A1=new Arr();
Caller ob1=new Caller(A1, 2);
Caller ob2=new Caller(A1, 4);
Caller ob3=new Caller(A1, 1);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted...");
}
}
}
/*
OUTPUT
Thread starts..
3
4
5
6
7
Thread stops..
Thread starts..
5
6
7
8
9
Thread stops..
Thread starts..
2
3
4
5
6
Thread stops..
*/
Program for Thread Priority
Code for Program for Thread Priority in Java
class thrun implements Runnable
{
Thread t;
boolean runn = true;
thrun(String st,int p)
{
t = new Thread(this,st);
t.setPriority(p);
t.start();
}
publicvoid run()
{
System.out.println("Thread name : " + t.getName());
System.out.println("Thread Priority : " + t.getPriority());
}
}
class priority
{
publicstaticvoid main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
thrun t1 = new thrun("Thread1",Thread.NORM_PRIORITY + 2);
thrun t2 = new thrun("Thread2",Thread.NORM_PRIORITY - 2);
System.out.println("Main Thread : " + Thread.currentThread());
System.out.println("Main Thread Priority : " + Thread.currentThread().getPriority());
}
}
/*
Output
Thread name : Thread1
Main Thread : Thread[main,10,main]
Thread name : Thread2
Thread Priority : 7
Main Thread Priority : 10
Thread Priority : 3
*/
Write a program for restaurant
Code for Write a program for restaurant in Java
import java.io.*;
class customerOrder
{
boolean valueset=false;
String str[]=new String[3];
synchronized void d_takeOrder(Thread t)
{
if(valueset)
{
try
{
wait();
}catch(InterruptedException e)
{
System.out.println(e);
}
}
System.out.println("\n"+t);
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<3;i++)
{
System.out.print("\n Take an Order "+(i+1)+" :: ");
str[i]=br.readLine();
}
}catch(IOException e)
{
System.out.println(e);
}
valueset=true;
notify();
}
synchronized void d_dispOrder(Thread t)
{
if(!valueset)
{
try
{
wait();
}catch(InterruptedException e)
{
System.out.println(e);
}
}
System.out.println("\n"+t);
for(int i=0;i<3;i++)
{
System.out.print("\n Place an Order "+(i+1)+" :: "+str[i]);
}
valueset=false;
notify();
}
}
class takeOrder implements Runnable
{
customerOrder d;
Thread t;
takeOrder(customerOrder d)
{
this.d=d;
t=new Thread(this,"Manager take an order");
t.start();
}
publicvoid run()
{
for(int i=0;i<2;i++)
{
d.d_takeOrder(t);
}
}
}
class dispOrder implements Runnable
{
customerOrder d;
Thread t;
dispOrder(customerOrder d)
{
this.d=d;
t=new Thread(this,"Manager place an order");
t.start();
}
publicvoid run()
{
for(int i=0;i<2;i++)
{
d.d_dispOrder(t);
}
}
}
class Restaurant
{
publicstaticvoid main(String args[])
{
customerOrder d=new customerOrder();
new takeOrder(d);
new dispOrder(d);
}
}
/*
Output
Thread[Manager take an order,5,main]
Take an Order 1 :: 2 Roti
Take an Order 2 :: 1 plat Veg.Jaipuri Sabji
Take an Order 3 :: 1 plat Pulav
Thread[Manager place an order,5,main]
Place an Order 1 :: 2 Roti
Place an Order 2 :: 1 plat Veg.Jaipuri Sabji
Place an Order 3 :: 1 plat Pulav
Thread[Manager take an order,5,main]
Take an Order 1 :: 3 Roti
Take an Order 2 :: 1 plat Paneerkadai Sabji
Take an Order 3 :: 1 plat Biriyani
Thread[Manager place an order,5,main]
Place an Order 1 :: 3 Roti
Place an Order 2 :: 1 plat Paneerkadai Sabji
Place an Order 3 :: 1 plat Biriyani
*/
Tuesday, 9 June 2015
An applet program to perform quick sort
Code for An applet program to perform quick sort in Java
import java.io.*;
class sort
{
String str;
int size,sortArr[];
publicvoid getdata()
{
System.out.print("Enter how many data you want to enter : ");
System.out.flush();
try{
BufferedReader obj=new BufferedReader(new
InputStreamReader(System.in));
str=obj.readLine();
size=Integer.parseInt(str);
sortArr=newint[size];
for(int i=0;i<size;i++)
{
System.out.print("Enter element at "+(i+1)+"th
position : ");
System.out.flush();
str=obj.readLine();
sortArr[i]=Integer.parseInt(str);
}
}
catch(Exception e) {}
QuickSort(sortArr,0,size-1);
}
publicvoid QuickSort(int sortArr[],int lb,int ub)
{
int i,j,key,flag=0,temp;
if(lb<ub)
{
i=lb;
j=ub+1;
key=k[i];
while(flag!=1)
{
i++;
while(k[i]<key)
i++;
j--;
while(k[j]>key)
j--;
if(i<j)
{
temp=k[i];
k[i]=k[j];
k[j]=temp;
}
else
{
flag=1;
temp=k[lb];
k[lb]=k[j];
k[j]=temp;
}
}
QuickSort(sortArr,lb,j-1)
QuickSort(sortArr,j+1,ub);
}
}
publicvoid display()
{
System.out.println("\nAfter Sorting");
for(int i=0;i<size;i++)
System.out.println(sortArr[i]);
}
}
class QuickSort
{
publicstaticvoid main(String args[])
{
sort ob1=new sort();
System.out.println("=====QUICK SORT=====\n");
ob1.getdata();
ob1.display();
}
}
An applet of displaying simple moving banner
Code for An applet of displaying simple moving banner in Java
import java.awt.*;
import java.applet.*;
publicclass simpleBanner extends Applet implements Runnable
{
String msg=" A Simple Moving Banner. ";
Thread t=null;
int state;
boolean stopflag;
publicvoid init()
{
setBackground(Color.yellow);
setForeground(Color.red);
}
publicvoid start()
{
t = new Thread(this);
stopflag=false;
t.start();
}
publicvoid run()
{
char ch;
for(;;){
try{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg=msg+ch;
if(stopflag)
break;
}catch(InterruptedException e) {}
}
}
publicvoid stop()
{
stopflag=true;
t=null;
}
publicvoid paint(Graphics g)
{
g.drawString(msg,50,30);
showStatus("Simple Banner");
}
}
An applet program that concatenates two string entered in TextField
Code for An applet program that concatenates two string entered in TextField in Java
import java.awt.*;
import java.applet.*;
publicclass concat2Str extends Applet
{
TextField Ts1,Ts2;
publicvoid init(){
Ts1 = new TextField(10);
Ts2 = new TextField(10);
add(Ts1);
add(Ts2);
Ts1.setText("");
Ts2.setText("");
}
publicvoid paint(Graphics g){
String str1,str2;
g.drawString("Enter Two String to Concat Them ",10,50);
str1=Ts1.getText();
str2=Ts2.getText();
g.setColor(Color.red);
g.drawString(str1+" "+str2,10,70);
showStatus("Concatination of 2 String");
}
public boolean action(Event e, Object o){
repaint();
returntrue;
}
}
An applet program to perform merge sort
Code for An applet program to perform merge sort in Java
import java.io.*;
import java.util.*; //for working with Vectorsclass MergSort
{
String str;
intvalue=0;
staticint s1=0,s2=0;
Vector list1 = new Vector();
Vector list2 = new Vector();
Integer intval; //object of Integer class for converting primitive numbers to object numbersvoid getdata()
{
try{
System.out.println("\n=====MERGE SORT=====");
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nNOTE : Data should be entered in sorted order");
System.out.print("\nEnter size of First List : ");
System.out.flush();
str=obj.readLine();
s1=Integer.parseInt(str);
for(int i=0;i<s1;i++)
{
System.out.print("Enter value for Element "+(i+1)+" : ");
System.out.flush();
str=obj.readLine();
value=Integer.parseInt(str);
intval = new Integer(value);
list1.addElement(intval);
}
System.out.print("\nEnter size of Second List : ");
System.out.flush();
str=obj.readLine();
s2=Integer.parseInt(str);
for( int i=0;i<s2;i++)
{
System.out.print("Enter value for Element "+(i+1)+" : ");
System.out.flush();
str=obj.readLine();
value=Integer.parseInt(str);
intval=new Integer(value);
list2.addElement(intval);
}
}
catch(Exception e) {}
}
//MERGE LOGICvoid merging() //method to merg
{
for(int i=0;i<s2;i++)
{
list1.insertElementAt(list2.elementAt(i),(s1+i));
}
System.out.println("\n\nAFTER MERGING");
for(int i=0;i<s1+s2;i++)
{
System.out.println("Element at("+(i+1)+") : "+list1.elementAt(i));
}
}
//SORT LOGICvoid sorting() //method for sorting
{
//creating temporary arrayint size=list1.size();
Vector sort=new Vector();
int a,b; //extra for converting object to primitive numbers
Integer A,B; //extra for taking object valueint first=0,second=s1,third=s1+s2,i,j,c=0;
i=first;
j=second;
while(i<second && j<third)
{
A=(Integer)list1.elementAt(i); //Assigning object to object
B=(Integer)list1.elementAt(j); //Assigning object to object
a=A.intValue(); //converting object to primitive number
b=B.intValue(); //converting object to primitive numberif(a < b) //list1.elementAt(i) < list1.elementAt(j)
{
sort.insertElementAt(A,c);
i++;
}
else
{
sort.insertElementAt(B,c);
j++;
}
c++;
}
if(i<second)
{
while(i<second)
{
sort.insertElementAt(list1.elementAt(i),c);
i++;
c++;
}
}
if(j<third)
{
while(j<third)
{
sort.insertElementAt(list1.elementAt(j),c);
j++;
c++;
}
}
System.out.println("\n\nAFTER SORTING");
for(int k=0;k<sort.size();k++)
System.out.println("Element at("+(k+1)+") : "+sort.elementAt(k));
}
}
class MergSortData
{
publicstaticvoid main(String[] args)
{
MergSort obj=new MergSort();
obj.getdata();
obj.merging();
obj.sorting();
}
}
An applet program to draw circle in center of the canvas
Code for An applet program to draw circle in center of the canvas in Java
import java.awt.*;
import java.applet.*;
publicclass centerCircle extends Applet
{
publicvoid paint(Graphics g){
Dimension d = getSize();
int x = d.width/2;
int y = d.height/2;
int radius = (int) ((d.width < d.height) ? 0.4 * d.width : 0.4 * d.height);
g.setColor(Color.cyan);
g.fillOval(x-radius, y-radius, 2*radius, 2*radius);
g.setColor(Color.red);
g.drawString("Width = "+d.width,10,10);
g.drawString("Height = "+d.height,10,20);
}
}
An applet program to display moving banner
Code for An applet program to display moving banner in Java
import java.awt.*;
import java.applet.*;
publicclass movingBanner extends Applet implements Runnable
{
String msg=" A moving Banner. ";
char ch;
boolean stopFlag= true;
Thread t= null;
publicvoid start(){
t = new Thread(this);
stopFlag=false;
t.start();
}
publicvoid run(){
for(;;){
try{
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg = msg + ch;
if(stopFlag)
break;
}catch(InterruptedException e) {}
}
}
publicvoid stop(){
stopFlag=true;
t = null;
}
publicvoid paint(Graphics g){
g.drawString(msg,60,30);
}
}
Boolean Operators
This article lists and explains boolean operators available in java.
Boolean operators
Operators
Meaning
a && b
Conditional AND.
If both variables a and b are true, the result is true.
If either of the variable is false, the result is false.
If a is false then b is not evaluated.
a & b
Boolean AND.
If both variables are true, the result is true.
If either of the variable is false, the result is false.
a || b
Conditional OR.
If either of the variable is true, the result is true.
If a is true, b is not evaluated.
a | b
Boolean OR.
If either of the variable is true, the result is true.
! a
Boolean NOT.
If a is true, the result is false.
If a is false, the result is true.
a ^ b
Boolean XOR.
If a is true and b is false, the result is true.
If a is false and b is true, the result is true.
In other cade, the result is false.
Examples of Boolean Operators
Example 1 : Program that displays use of boolean operators i.e &&, &, ||, |, !, ^
class BoolOptrDemo
{
public static void main(String args[])
{
boolean b1 = true;
boolean b2 = false;
System.out.println("b1|b2 = "+(b1|b2));
System.out.println("b1&b2 = "+(b1&b2));
System.out.println("!b1 = "+(!b1));
System.out.println("b1^b2 = "+(b1^b2));
System.out.println("(b1|b2)&b1 = "+((b1|b2)&b1));
}
}
Operators
|
Meaning
|
a && b
|
Conditional AND.
If both variables a and b are true, the result is true.
If either of the variable is false, the result is false.
If a is false then b is not evaluated.
|
a & b
|
Boolean AND.
If both variables are true, the result is true.
If either of the variable is false, the result is false.
|
a || b
|
Conditional OR.
If either of the variable is true, the result is true.
If a is true, b is not evaluated.
|
a | b
|
Boolean OR.
If either of the variable is true, the result is true.
|
! a
|
Boolean NOT.
If a is true, the result is false.
If a is false, the result is true.
|
a ^ b
|
Boolean XOR.
If a is true and b is false, the result is true.
If a is false and b is true, the result is true.
In other cade, the result is false.
|
{
public static void main(String args[])
{
boolean b1 = true;
boolean b2 = false;
System.out.println("b1|b2 = "+(b1|b2));
System.out.println("b1&b2 = "+(b1&b2));
System.out.println("!b1 = "+(!b1));
System.out.println("b1^b2 = "+(b1^b2));
System.out.println("(b1|b2)&b1 = "+((b1|b2)&b1));
}
}
Variable modifiers in java
This article explains about variable modifiers available in java with example.
There are seven possible modifiers that may precede the declaration of a variable as listed below.
Keyword
|
Description
|
Is a constant
| |
Can be accessed only by code in the same class
| |
Can be accessed only by code in a subclass or the same package
| |
Can be accessed by any other class
| |
Is not an instance variable
| |
Is not part of the persistent state of this class
| |
Can change unexpectedly
|
IF Control Statement
Syntax of IF statement
if(expr) statement;
expr is any expression that evaluates to a boolean value. If expr is evaluated as true, the statement will be executed otherwise, the statement is bypassed and the line of code following the if is executed.
The expression inside if
compares one value with another by using relational operators. Below
table lists the java relational operators. It test relationship between
two operands where operands can be expression or value. It returns boolean value.
Relational Operators In Java
Operator
|
Meaning
|
Example
|
==
|
Equals
|
a == b
|
!=
|
Not equals
|
a != b
|
>
|
Greater than
|
a > b
|
<
|
Less than
|
a < b
|
>=
|
Greater than or equals
|
a >= b
|
<=
|
Less than or equals
|
a <= b
|
Examples of If Statement
Example 1 : Program that displays a message based on condition checking
class IfStateDemo
{
public static void main(String args[])
{
if(args.length == 0)
{
System.out.println("No arguments are passed to the command line.");
}
}
}
//Call application from command line
java IfStateDemo
Output
No arguments are passed to the command line.
Example 2 : Program that compares 2 numbers and displays greatest
class IfStateDemo
{
public static void main(String args[])
{
int num1 = 10;
int num2 = 15;
if(num1 > num2)
{
System.out.println("Number1 having value " + num1 + " is greater than number2 having value " + num2);
}
if(num2 > num1)
{
System.out.println("Number2 having value " + num2 + " is greater than number1 having value " + num1);
}
}
}
Corba program to Write a Echo server and client with UDP server and client
Code for Corba program to Write a Echo server and client with UDP server and client in Java
import java.io.*;
import java.net.*;
publicclass EServer
{
publicstaticvoid main(String[] args) throws IOException
{
ServerSocket S = new ServerSocket(3000);
while(true)
{
Socket Client = S.accept();
InputStream in = Client.getInputStream();
DataInputStream Dis = new DataInputStream(in);
System.out.println(Dis.readUTF());
Client = new Socket("localhost",4000);
BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
String Str = buff.readLine();
OutputStream out = Client.getOutputStream();
DataOutputStream Dos = new DataOutputStream(out);
Str = "Server Says :: " + Str;
Dos.writeUTF(Str);
Client.close();
}
}
}
// Client
import java.io.*;
import java.net.*;
import java.util.*;
publicclass EClient
{
publicstaticvoid main(String[] args) throws IOException
{
Socket C = new Socket("localhost",3000);
BufferedReader buff = new BufferedReader(new InputStreamReader (System.in));
String Str = buff.readLine();
OutputStream out = C.getOutputStream();
DataOutputStream Dos = new DataOutputStream(out);
Dos.writeUTF("Client Say :: " + Str);
Dos.flush();
ServerSocket S = new ServerSocket(4000);
Socket Client = S.accept();
InputStream in = Client.getInputStream();
DataInputStream Dis = new DataInputStream(in);
System.out.println(Dis.readUTF());
Client.close();
}
}
OUTPUT :
========= Client ============
C:\jdk1.1.3\bin>javac EClient.java
C:\jdk1.1.3\bin>java EClient
hi, how are you Server?
Server Says :: Fine, Thankyou. Bye.
========= Server =============
C:\jdk1.1.3\bin>javac EServer.java
C:\jdk1.1.3\bin>java EServer
Client Say :: hi, how are you Server?
Fine, Thankyou. Bye.
Corba program of UDP client server application which sends the news to the client. Server takes the news from the NewsDataFile located at the server
Code for Corba program of UDP client server application which sends the news to the client. Server takes the news from the NewsDataFile located at the server in Java
import java.io.*;
import java.net.*;
publicclass news_server
{
publicstaticvoid main(String[] args) throws IOException
{
int ch1;
String str;
FileReader fr = new FileReader("news.txt");
BufferedReader br = new BufferedReader(fr);
Socket C = new Socket("localhost",4000);
OutputStream out = C.getOutputStream();
DataOutputStream Dos = new DataOutputStream(out);
while( (str = br.readLine()) != null)
{
Dos.writeUTF("Latest News (From Server ) :: " + str);
}
Dos.flush();
fr.close();
}
}
// Client// Client // =====
import java.io.*;
import java.net.*;
import java.util.*;
publicclass news_client
{
publicstaticvoid main(String[] args) throws IOException
{
ServerSocket S = new ServerSocket(4000);
Socket Client = S.accept();
InputStream in = Client.getInputStream();
DataInputStream Dis = new DataInputStream(in);
System.out.println(Dis.readUTF());
Client.close();
}
}
// OUTPUT
News.txt
=========================
India won the Worldcup by beating
Australia by 6 wkt.
===========================
// Server
C:\jdk1.1.3\bin>javac news_server.java
C:\jdk1.1.3\bin>java news_server
// Client
C:\jdk1.1.3\bin>java news_client
Latest News (From Server ) :: India won the Worldcup by beating
Australia by 6 wkt.
CORBA PROGRAM TO GET THE HTML CODE FROM ANY URL
Code for CORBA PROGRAM TO GET THE HTML CODE FROM ANY URL in Java
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class HTMLGetter extends Frame implements ActionListener
{
TextField tURL = new TextField(50);
Button btn = new Button("Get HTML");
Button exit = new Button("Exit");
TextArea ta = new TextArea(50,20);
HTMLGetter() throws Exception
{
Panel p = new Panel();
add(p,BorderLayout.NORTH);
p.add(tURL);
p.add(btn);
p.add(exit);
add(ta);
btn.addActionListener(this);
exit.addActionListener(this);
setSize(600,400);
show();
}
publicstaticvoid main(String args[]) throws Exception
{
HTMLGetter hg = new HTMLGetter();
}
publicvoid actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btn)
{
try
{
URL htmlURL = new URL(tURL.getText());
InputStream in = htmlURL.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String getLine;
while((getLine=br.readLine())!=null)
{
ta.append(getLine);
}
br.close();
in.close();
}
catch(Exception e)
{
//No handling exception here;
}
}
else
{
System.exit(0);
}
}
}
corba program of client and a DNS server where given a URL the server sends back an IP address
Code for corba program of client and a DNS server where given a URL the server sends back an IP address in Java
import java.net.*;
import java.io.*;
import java.util.*;
class eserver implements Runnable
{
Socket socket;
int id;
int count;
publicstaticvoid main(String args[])
{
int count=0;
try
{
ServerSocket s= new ServerSocket(13);
while(true)
{
Socket socket=s.accept();
eserver server=new eserver(socket,count);
Thread t=new Thread(server);
t.start();
}
}
catch(Exception e)
{
System.out.println("Exception caught is::"+e);
}
}
eserver(Socket sa,int i)
{
socket=sa;
id=i;
}
publicvoid run()
{
int flag=0;StringTokenizer t;
String id,ipAddress,str;
int i;
try{
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String cls=br.readLine();
System.out.println("Client Requested : "+cls);
if(cls.trim().equals("quit"))
{
System.out.println("Client has Disconnected.....");
br.close();
}
try{
OutputStream op=socket.getOutputStream();
PrintWriter pw=new PrintWriter(op);
String clientid=cls;
String val="";
String msg="";
FileReader fr=new FileReader("iptable.txt");
BufferedReader bf=new BufferedReader(fr);
while(flag==0)
{
String b=bf.readLine();
if(b==null)
break;
t=new StringTokenizer(b);
id=t.nextToken();
ipAddress=t.nextToken();
if(id.equals(clientid))
{
System.out.println("URL :: "+id);
System.out.println("IP Address :: "+ipAddress);
val="*";flag=1;msg="URL="+id+" IP Address= "+ipAddress;
}
else
{
flag=0;msg="Sorry, Given URL is not Found.....";
}
}
bf.close();
fr.close();
if(flag==1)
pw.println(msg);
else
pw.println(msg);
pw.flush();
pw.close();
} //endtry2catch(Exception e)
{
System.out.println("Exception caught is::"+e);
}
}//endtry1catch(IOException e){}
//end while
}//end run
}
// Client
import java.net.*;
import java.io.*;
publicclass eclient
{
publicstaticvoid main(String args[])
{
String instr,str;
try{
while(true)
{
InetAddress address=InetAddress.getByName(null);
System.out.println("\n\n==========================");
System.out.println("Enter Name / Enter 'quit' to exit");
System.out.println("Client : ");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
instr=br.readLine();
while(!instr.trim().equals("quit"))
{
Socket s=new Socket(address,13);
OutputStream os= s.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
PrintWriter pw=new PrintWriter(osw);
pw.println(instr);
pw.flush();
InputStream inStream=s.getInputStream();
InputStreamReader ipr=new InputStreamReader(inStream);
BufferedReader brs=new BufferedReader(ipr);
str=brs.readLine();
System.out.println("Reply form Server is : "+str);
System.out.println("\n\n==========================");
System.out.println("Enter Name / Enter 'quit' to exit");
System.out.println("Client : ");
instr=br.readLine();
}
br.close();
System.exit(0);
}
}
catch(Exception e)
{
System.out.println("Exception caught is::"+e);
}
}
}
OUTPUT :
iptabel.txt
----------
www.yahoo.com 127.0.0.1 13
www.hotmail.com 127.12.1.1 13
www.glsict.org 127.0.2.12 13
www.rediffmail.com 127.1.32.1 13
// Client
C:\jdk1.1.3\bin>java eclient
==========================
Enter Name / Enter 'quit' to exit
Client :
www.glsict.org
Reply form Server is : URL=www.glsict.org IP Address= 127.0.2.12
==========================
Enter Name / Enter 'quit' to exit
Client :
quit
C:\jdk1.1.3\bin>
// Server
C:\jdk1.1.3\bin>java eserver
Client Requested : www.glsict.org
URL :: www.glsict.org
IP Address :: 127.0.2.12
Client has Disconnected.....
C:\jdk1.1.3\bin>
Subscribe to:
Comments (Atom)