}catch(Exception e)
{
head=new Vector();
head.add("No data found");
data=new Vector();
data.add(head);
}
return data;
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_execute)
{
obj.
}
}
public static void main(String arg[])
{
try
{
obj=(SalsRemote)Naming.lookup("rmi://localhost:1099/OBJ3");
System.out.println("Calling remote methods");
new SalsClient();
}
catch{}
}
}
import java.rmi.*;
public interface SalRemote extends Remote
{
public vector getData(String query) throws RemoteException;
}import java.io.*;
import java.lang.*;
public class sam
{
public static void main(String arg[])
{
System.out.println("welcome");
}
}public class sample
{
public static void main(String args[])
{
System.out.println ("\n\n\n hi this is my first program!!! \n\n hello!! how r u!!");
}
}public class sample1
{
public static void main(String args[])
{
System.out.println("\n\n hi am bala!!!");
}
}/*
- This program illustrates the use of the Scanner class.
*/
import java.io.*;
import java.util.*;
import javax.swing.*;
class scanners
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a statement: ");
input.nextLine();
System.out.print("Enter your name: ");
input.next();
System.out.print("Enter your age: ");
input.nextInt();
String temp = JOptionPane.showInputDialog("What is your name?");
System.out.print("Thank you for using Scanner Class.");
}
}class scope
{
static int no=100;
public static void main(String[] args)
{
System.out.println("no : "+no);
System.out.println("no : "+scope.no);
}
}
//to create a scroll bar
/* Compiled from Scrollbar.java
public class java.awt.Scrollbar extends
java.awt.Component implements java.awt.Adjustable {
public static final int HORIZONTAL;
public static final int VERTICAL;
public java.awt.Scrollbar();
public java.awt.Scrollbar(int);
public java.awt.Scrollbar(int,int,int,int,int); */
//
import java.awt.* ;
import java.applet.* ;
public class scrollbar extends Applet {
public void init() {
Scrollbar sb=new Scrollbar(); //creates vertical scrollbar
Scrollbar h=new Scrollbar(Scrollbar.HORIZONTAL);
Scrollbar horsb=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,200);
Scrollbar versb=new Scrollbar(Scrollbar.VERTICAL,0,1,0,200);
//(style,initial value,thumbsize,min,max)
//min and max for month is 1-12
//min and max for colours is 1-256
add(sb); add(h); add(horsb); add(versb);
}
}
/*
- This program will take a set of strings from the user and store it in an array.
- I have also written a search algorithm to search from the list that the user has entered
*/
import java.io.*;
class search
{
public String sTotalInputs;
public int iTotalInputs = 0;
public String[] sInput = new String[50];
public String searchElement;
public BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void takeInput()
{
try
{
System.out.print("Enter the total no. of elements you want: ");
sTotalInputs = br.readLine();
iTotalInputs = Integer.parseInt(sTotalInputs);
for(int i=1; i<=iTotalInputs; i++)
{
sInput[i] = br.readLine();
}
}
catch(IOException ioe)
{
System.out.println("ERROR!!!");
System.exit(1);
}
}
public void giveOutput()
{
for(int i=1; i<=iTotalInputs; i++)
{
System.out.println(i + ". " + sInput[i]);
}
}
public void search()
{
System.out.print("Enter the element you want to search: ");
try
{
searchElement = br.readLine();
System.out.println("Please wait. Searching.....");
for(int i=1; i<=iTotalInputs; i++)
{
if(sInput[i].equals(searchElement))
{
System.out.println("The element id you were looking for is " + i);
}
}
}
catch(IOException ioe)
{
System.out.println("ERROR!!!");
System.exit(1);
}
}
public static void main(String[] args)
{
search s1 = new search();
s1.takeInput();
System.out.println("\n The elements you entered are:");
s1.giveOutput();
s1.search();
}
}public class second{
public second()
{
system.out.println(("\n constructor!!!");
}
};public class second{
public int no;
public void sec()
{
System.out.println("\n constructor!!!");
}
}/**
* @author Yogesh
*
* Program for selecting a group of attribute values
* from the "xxx.DATA" file which is given as an Input File
* and a "result.txt" file is generated as an output.
* The requried fields are given as a User Input
*/
import java.io.*;
import java.util.StringTokenizer;
public class Selection
{
static int[] fields;
static int count=-1;
public static void main(String[] args) throws IOException
{
int flag=0;
FileInputStream fis=null;
File input=null;
String str;
BufferedReader br=null;
PrintStream ps=System.out;
StringTokenizer st;
//getting filename until file already exist
while(flag==0)
{
System.out.println("Enter the File Name (.DATA): ");
br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
if((input=new File(str)).exists())
flag=1;
}
// required fields are given as a user Input
ps.println("Enter the Fields to be Extracted (nos: 1 to 42):");
str=br.readLine();
st=new StringTokenizer(str," ");
fields=new int[st.countTokens()];
ps.println(st.countTokens());
while(st.hasMoreTokens())
{
count++;
fields[count]=Integer.parseInt(st.nextToken());
}
/*for(int i=0;i<=count;i++)
ps.println(fields[i]);*/
//Generating the output file
br=new BufferedReader(new InputStreamReader(new FileInputStream(input)));
File fout=new File("result.txt");
fout.createNewFile();
PrintStream out=new PrintStream(new FileOutputStream(fout));
int cnt=0;
while((str=br.readLine())!=null) // each record
{ st=new StringTokenizer(str,"," );
count=0;
cnt=0;
//ps.println(st.countTokens());
while(st.hasMoreTokens()) //each fields in a single record
{
try
{
if(fields[cnt]==(count+1))
{
if(count==41)
out.print(st.nextToken().replace("."," "));
else
out.print(st.nextToken());
out.print(" ");
// ps.println("hello Yogesh");
if((fields.length-1)!=cnt)
cnt++;
}
else
st.nextToken();
}
catch(ArrayIndexOutOfBoundsException ae)
{
ps.println(ae.getStackTrace());
}
count++;
}
out.print("\n");
}
ps.println("Output File Generated Sucessfully");
}
}
class SeleksiIf {
public static void main(String[] args) {
int a,b;
a = 20;
b = a/2;
if(b>5){
System.out.println("Pernyataan1 Test Seleksi If dieksekusi");
}
System.out.println("Pernyataan2 Test Seleksi If dieksekusi");
}
}
class SeleksiIfElse {
public static void main(String[] args) {
int x;
x = 10;
if(x>5) {
System.out.println("Pernyataan1a Test Seleksi IfElse dieksekusi");
System.out.println("Pernyataan1b Test Seleksi IfElse dieksekusi");
}
else {
System.out.println("Pernyataan2a Test Seleksi IfElse dieksekusi");
System.out.println("Pernyataan2b Test Seleksi IfElse dieksekusi");
}
}
}
class SeleksiIfElseIf{
public static void main(String[] args) {
int bulan = 12;
if(bulan<=3)
System.out.println("Kuartal 1 Test Seleksi IfElseIf");
else if(bulan<=6)
System.out.println("Kuartal 2 Test Seleksi IfElseIf");
else if(bulan<=9)
System.out.println("Kuartal 3 Test Seleksi IfElseIf");
else
System.out.println("Kuartal 4 Test Seleksi IfElseIf");
}
}
class SeleksiSwitch {
public static void main(String[] args) {
int bulan, year;
bulan = 1;
year = 2005;
switch(bulan) {
case 1: switch(year) {
case 2004 : System.out.println("Bulan 1 tahun 2004");
break;
case 2005 : System.out.println("Bulan 1 tahun 2005");
break;
}
break;
case 2: switch(year) {
case 2004 : System.out.println("Bulan 2 tahun 2004");
break;
case 2005 : System.out.println("Bulan 2 tahun 2005");
break;
}
break;
case 3: switch(year) {
case 2004 : System.out.println("Bulan 3 tahun 2004");
break;
case 2005 : System.out.println("Bulan 3 tahun 2005");
break;
}
break;
default:
System.out.println("Bulan dan Tahun yang dicari tidak ada pada pilihan");
break;
}
System.out.println("Sudah keluar dari switch");
}
}
import java.net.*;
import java.io.*;
class server
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static void Myserver() throws Exception
{
int pos=0;
while(true)
{
int c=System.in.read();
switch(c)
{
case 1:
System.out.println("Server Quits");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),777));
pos=0;
break;
default:
buffer[pos++]=(byte)c;
}
}
}
public static void main(String args[])throws Exception
{
System.out.println("Serverv ready....\n please type here");
ds=new DatagramSocket(886);
Myserver();
}
}import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ServerSocketGUI extends Frame implements ActionListener
{
Label l1,l2;
TextField t1;
Button b1;
TextArea ta;
ServerSocket ss;
Socket s;
DataInputStream remote;
PrintStream ps;
public ServerSocketGUI()
{
l1=new Label("Enter message");
l2=new Label("Message received");
t1=new TextField(50);
ta=new TextArea();
b1=new Button("Send");
b1.addActionListener(this);
Panel p1=new Panel();
p1.add(l1);
p1.add(t1);
p1.add(b1);
Panel p2=new Panel();
p2.add(l2);
p2.add(ta);
Panel mainPanel=new Panel();
mainPanel.add(p1);
mainPanel.add(p2);
add(mainPanel);
setTitle("Server");
setSize(600,400);
setVisible(true);
try
{
ss=new ServerSocket(2000);
s=ss.accept();
remote=new DataInputStream(s.getInputStream());
ps=new PrintStream(s.getOutputStream());
}catch(Exception e)
{
System.out.println("Error in server side"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
String localdata=t1.getText();
ps.println(localdata);
String remotedata=remote.readLine();
ta.append(remotedata+"\n");
}catch(Exception e)
{
System.out.println("Error in server side"+e);
}
}
public static void main(String arg[])
{
new ServerSocketGUI();
}
}
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ServerSocketGUI2 extends Frame implements ActionListener,Runnable
{
Label l1,l2;
TextField t1;
Button b1;
TextArea ta;
ServerSocket ss;
Socket s;
DataInputStream remote;
PrintStream ps;
Thread th;
public ServerSocketGUI2()
{
l1=new Label("Enter message");
l2=new Label("Message received");
t1=new TextField(50);
ta=new TextArea();
b1=new Button("Send");
b1.addActionListener(this);
Panel p1=new Panel();
p1.add(l1);
p1.add(t1);
p1.add(b1);
Panel p2=new Panel();
p2.add(l2);
p2.add(ta);
Panel mainPanel=new Panel();
mainPanel.add(p1);
mainPanel.add(p2);
add(mainPanel);
setTitle("Server");
setSize(600,400);
setVisible(true);
try
{
ss=new ServerSocket(2000);
s=ss.accept();
remote=new DataInputStream(s.getInputStream());
ps=new PrintStream(s.getOutputStream());
th=new Thread(this);
th.start();
}catch(Exception e)
{
System.out.println("Error in server side"+e);
}
}
public void run()
{
try{
while(true)
{
String remotedata=remote.readLine();
ta.append(remotedata+"\n");
}
}catch(Exception e)
{
System.out.println("Error in server side"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
String localdata=t1.getText();
ps.println(localdata);
}catch(Exception e)
{
System.out.println("Error in server side"+e);
}
}
public static void main(String arg[])
{
new ServerSocketGUI2();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author 3mcac05
*/
@WebServlet(name="ServletCookies", urlPatterns={"/ServletCookies"})
public class ServletCookies extends HttpServlet {
/**
* Processes requests for both HTTP
GET
and POST
methods.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//
/**
* Handles the HTTP
GET
method.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* Handles the HTTP
POST
method.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out=response.getWriter();
Cookie[] ck=request.getCookies();
if(ck!=null)
{
for(int i=0;i
String name1=(String)ck[i].getName();
String value1=(String)ck[i].getValue();
out.println("
COOKIE NAME:" +name1+ "
");
out.println("
COOKIE VALUE:" +value1+ "
");
}
}
else
{
out.println("NO COOKIES ARE FOUND");
}
String name=request.getParameter("name1");
if(name!=null && name.length()>0);
{
String value=request.getParameter("value1");
Cookie c=new Cookie(name,value);
response.addCookie(c);
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.print.DocFlavor.STRING;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
/**
*
* @author 3mcac05
*/
@WebServlet(name="session", urlPatterns={"/session"})
public class session extends HttpServlet {
/**
* Processes requests for both HTTP
GET
and POST
methods.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("");
out.println("");
out.println("
out.println("
"); out.println("");
out.println("
Servlet session at " + request.getContextPath () + "
");out.println("
"); out.println("
"); */
} finally {
out.close();
}
}
//
/**
* Handles the HTTP
GET
method.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* Handles the HTTP
POST
method.* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name=request.getParameter("uname");
PrintWriter out=response.getWriter();
HttpSession ses=request.getSession(true);
ses.setAttribute("uname",name);
out.println("
");
ses.getAttribute("uname");
String name1=(String)ses.getAttribute("uname");
out.println("your user name retrived from the session is "+name1);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import util.HTMLFilter;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson
*/
public class SessionExample extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("");
String title = rb.getString("sessions.title");
out.println("
out.println("
"); out.println("");
// img stuff not req'd for source code html showing
// relative links everywhere!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("");
out.println(" "width=24 align=right border=0 alt=\"view code\">
"); out.println("");
out.println(" "width=24 align=right border=0 alt=\"return\">
");
out.println("
" + title + "
");HttpSession session = request.getSession(true);
out.println(rb.getString("sessions.id") + " " + session.getId());
out.println("
");
out.println(rb.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "
");
out.println(rb.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()));
String dataName = request.getParameter("dataname");
String dataValue = request.getParameter("datavalue");
if (dataName != null && dataValue != null) {
session.setAttribute(dataName, dataValue);
}
out.println("");
out.println(rb.getString("sessions.data") + "
");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
out.println(HTMLFilter.filter(name) + " = "
+ HTMLFilter.filter(value) + "
");
}
out.println("");
out.print("");
out.println("GET based form:
");
out.print("");
out.print(" out.print(response.encodeURL("SessionExample?dataname=foo&datavalue=bar"));
out.println("\" >URL encoded ");
out.println("
"); out.println("
");
out.println("
"); out.println("
"); }
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Example listener for context-related application events, which were
* introduced in the 2.3 version of the Servlet API. This listener
* merely documents the occurrence of such events in the application log
* associated with our servlet context.
*
* @author Craig R. McClanahan
* @version $Revision$ $Date$
*/
public final class SessionListener
implements ServletContextListener,
HttpSessionAttributeListener, HttpSessionListener {
// ----------------------------------------------------- Instance Variables
/**
* The servlet context with which we are associated.
*/
private ServletContext context = null;
// --------------------------------------------------------- Public Methods
/**
* Record the fact that a servlet context attribute was added.
*
* @param event The session attribute event
*/
public void attributeAdded(HttpSessionBindingEvent event) {
log("attributeAdded('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that a servlet context attribute was removed.
*
* @param event The session attribute event
*/
public void attributeRemoved(HttpSessionBindingEvent event) {
log("attributeRemoved('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that a servlet context attribute was replaced.
*
* @param event The session attribute event
*/
public void attributeReplaced(HttpSessionBindingEvent event) {
log("attributeReplaced('" + event.getSession().getId() + "', '" +
event.getName() + "', '" + event.getValue() + "')");
}
/**
* Record the fact that this web application has been destroyed.
*
* @param event The servlet context event
*/
public void contextDestroyed(ServletContextEvent event) {
log("contextDestroyed()");
this.context = null;
}
/**
* Record the fact that this web application has been initialized.
*
* @param event The servlet context event
*/
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
log("contextInitialized()");
}
/**
* Record the fact that a session has been created.
*
* @param event The session event
*/
public void sessionCreated(HttpSessionEvent event) {
log("sessionCreated('" + event.getSession().getId() + "')");
}
/**
* Record the fact that a session has been destroyed.
*
* @param event The session event
*/
public void sessionDestroyed(HttpSessionEvent event) {
log("sessionDestroyed('" + event.getSession().getId() + "')");
}
// -------------------------------------------------------- Private Methods
/**
* Log a message to the servlet context application log.
*
* @param message Message to be logged
*/
private void log(String message) {
if (context != null)
context.log("SessionListener: " + message);
else
System.out.println("SessionListener: " + message);
}
/**
* Log a message and associated exception to the servlet context
* application log.
*
* @param message Message to be logged
* @param throwable Exception to be logged
*/
private void log(String message, Throwable throwable) {
if (context != null)
context.log("SessionListener: " + message, throwable);
else {
System.out.println("SessionListener: " + message);
throwable.printStackTrace(System.out);
}
}
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
/**
* Example filter that sets the character encoding to be used in parsing the
* incoming request, either unconditionally or only if the client did not
* specify a character encoding. Configuration of this filter is based on
* the following initialization parameters:
*
*
* for this request, either conditionally or unconditionally based on
* the
ignore
initialization parameter. This parameter* is required, so there is no default.
*
* specified by the client is ignored, and the value returned by the
*
selectEncoding()
method is set. If set to "false,*
selectEncoding()
is called only if the* client has not already specified an encoding. By default, this
* parameter is set to "true".
*
*
* Although this filter can be used unchanged, it is also easy to
* subclass it and make the
selectEncoding()
method more* intelligent about what encoding to choose, based on characteristics of
* the incoming request (such as the values of the
Accept-Language
* and
User-Agent
headers, or a value stashed in the current* user's session.
*
* @author Craig McClanahan
* @version $Revision$ $Date$
*/
public class SetCharacterEncodingFilter implements Filter {
// ----------------------------------------------------- Instance Variables
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
// --------------------------------------------------------- Public Methods
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
// ------------------------------------------------------ Protected Methods
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
*
null
.*
* The default implementation unconditionally returns the value configured
* by the encoding initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
import java.io.*;
interface display1
{
String mark[]={"first","second","third"};
String ph[] = {"132","342","323"};
}
class shoe implements display1
{
void gd(int x)
{
System.out.println(mark[x]);
System.out.println(ph[x]);
}
}
class store extends shoe
{
void pd(int y)
{
gd(y);
}
}
class sh
{
public static void main(String args[])throws IOException
{
DataInputStream in = new DataInputStream(System.in);
store S = new store();
int z = Integer.parseInt(in.readLine());
S.pd(z);
}} // PROGRAM FOR SHAPES USING APPLETS GRAPHICS.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//
public class shapes extends Applet {
public void init()
{
repaint();
}
public void paint(Graphics g){
/* Circle inside a square */
g.drawOval(25,75,40,40);
g.drawRect(20,70,50,50);
/* square inside a circle */
g.drawOval(80,70,50,50);
g.drawRect(90,80,30,30);
/*Cube */
g.drawRect(50,150,70,70);
g.drawRect(20,180,70,70);
g.drawLine(20,180,50,150);
g.drawLine(20+70,180,50+70,150);
g.drawLine(20,180+70,50,150+70);
g.drawLine(20+70,180+70,50+70,150+70);
/* cone */
g.drawOval(150,75,50,20);
g.drawLine(150,85,175,125);
g.drawLine(175,125,200,85);
/* cylinder */
g.drawOval(160,160,50,20);
g.drawOval(160,220,50,20);
g.drawLine(160,170,160,230);
g.drawLine(210,170,210,230);
}
}
import java.net.*;
import java.io.*;
class simpleclient
{
public static void main(String args[]) throws Exception
{
Socket s1=new Socket("localhost",12);
InputStream slin=s1.getInputStream();
DataInputStream dis=new DataInputStream(slin);
String st=new String(dis.readUTF());
System.out.println(st);
dis.close();
slin.close();
s1.close();
}
}import java.net.*;
import java.io.*;
class simpleserver
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(12);
System.out.println("waiting for client request");
Socket s1=s.accept();
OutputStream slout=s1.getOutputStream();
DataOutputStream dos=new DataOutputStream(slout);
dos.writeUTF("hi there");
dos.close();
slout.close();
s1.close();
}
}class Test1
{
int x,y;
void getData(int x1,int y1)
{
x=x1;
y=y1;
}
void add()
{
int z=x+y;
System.out.println("Addtion of "+x+"and"+y+"is="+z);
}
}
class SingleInherit extends Test1
{
void sub()
{
int z=x-y;
System.out.println("Substraction of "+x+"and"+y+"is="+z);
}
}
class Multi extends SingleInherit
{
void div()
{
int z=x/y;
System.out.println("Division of "+x+"and"+y+"is="+z);
}
public static void main(String arg[])
{
Multi s=new Multi();
s.getData(10,20);
s.add();
s.sub();
s.div();
}
}
// Program for slink Clustering
import java.util.*;
import java.io.*;
public class singlink {
private File namefile = null;
private File datafile = null;
private int k=-1;
private ArrayList clusterlist = new ArrayList(); // to store the clusters. Each cluster is a list of IDs of the tuples
private ArrayList attrlist = new ArrayList(); // to store the attributes
private ArrayList valuelist = new ArrayList(); // to store all the tuples (cases). Each tuple is a list of attrvalues.
private ArrayList origvalues=new ArrayList();
public singlink() {
}
public static void main(String[] args)throws Exception {
try {
// load the file specified by filename.
System.out.print("Enter the input file name: ");
BufferedReader lineReader = new BufferedReader(new InputStreamReader(
System.in));
String fileitemname = lineReader.readLine();
singlink sl = new singlink();
if (sl.loadFiles(fileitemname) == false) {
return;
}
// handle the inputted 'K'.
while (true) {
System.out.print("Input 'K' (int): ");
try {
int k = Integer.parseInt(lineReader.readLine());
sl.setK(k);
break;
}
catch (NumberFormatException ee) {
System.out.println("Format error! Please input an integer!!!");
}
}
// handle the method of choosing seeds.
sl.clustering();
String outputFilename = "";
do {
System.out.print("Please specify the output filename: ");
outputFilename = lineReader.readLine();
}
while (!sl.output(outputFilename));
}
catch (Exception e) {
e.printStackTrace();
}
}
//To check filename and load data from file
public boolean loadFiles(String fileitemname) {
// validate if the files exist.
this.namefile = new File("./" + fileitemname + ".names");
if (!this.namefile.exists()) {
System.out.println("The file .names doesn't exist!");
return false;
}
this.datafile = new File("./" + fileitemname + ".data");
if (!this.datafile.exists()) {
System.out.println("The file .data doesn't exist!");
return false;
}
this.loadName();
this.loadData();
return true;
}
// Load attr from the '.names' file.
protected boolean loadName() {
try {
BufferedReader reader = new BufferedReader(new FileReader(this.namefile));
String line = "";
int ind = 0;
while ( (line = reader.readLine()) != null) {
ind = line.indexOf('|');
if (ind >= 0) {
line = line.trim().substring(0, ind).trim();
}
if (line.equals("")) {
continue;
}
ind = line.indexOf(':');
if (ind >= 0) {
// read attribute names into the "attrlist".
String name = line.substring(0, ind);
this.attrlist.add(name);
}
} // while readLine()
return true;
}
catch (IOException ex) {
System.out.println("File I/O error. Please verify the .names file");
return false;
}
}
// Load data from the '.data' file.
protected void loadData() {
try {
BufferedReader reader = new BufferedReader(new FileReader(this.datafile));
String line = "";
int ind = 0;
while ( (line = reader.readLine()) != null) {
// remove the annotation
// ind = line.indexOf('|');
// if (ind >= 0) {
// line = line.trim().substring(0, ind).trim();
// }
if (line.equals("")) {
continue;
}
ArrayList tuple = new ArrayList();
ind = line.indexOf(',');
while (ind > 0) {
String attrvalue = line.substring(0, ind);
tuple.add(new Double(attrvalue));
line = line.substring(ind + 1).trim();
ind = line.indexOf(',');
} // while
this.valuelist.add(tuple);
this.origvalues.add(tuple);
} // while readLine()
}
catch (Exception ex) {
System.out.println("File I/O error. Please verify the .data file");
}
}
public void setK(int k) {
this.k = k;
}
// To cluster the whole data
public void clustering() {
try
{
System.out.println("Clustering .............."+this.k);
// initialize the clusters in the cluster list
int q;
int r;
double minDistance=0.0;
this.clusterlist.clear();
//this.scluster.clear();
for(int l=0;l
t.add(new Integer(l));
this.clusterlist.add(t);
//this.scluster.add(t);
}
//System.out.println("initial clusterlist " + this.clusterlist);
//System.in.read();
int tk1=0;
int tk2=0;
double tvalue1,tvalue2;
l1: while(true)
{
// h++;
int h=-1;
loop: for (int i = 0; i < this.valuelist.size(); i++)
{
ArrayList temp1 = new ArrayList();
temp1 = (ArrayList)this.valuelist.get(i);
//System.out.println( "i is "+i+ " "+temp1);
//System.in.read();
tvalue1 = ((Double) temp1.get(0)).doubleValue();
if (tvalue1 == 99.0 )
continue loop;
for (int j = 0; j < this.valuelist.size(); j++)
// computer the Euclidean distance between the tuple and the centroid.
{
ArrayList temp2 = new ArrayList();
temp2 = (ArrayList)this.valuelist.get(j);
//System.out.println("j is "+j+ " "+temp2 );
//System.in.read();
tvalue2 = ((Double)temp2.get(0)).doubleValue();
if ((i!=j) && (tvalue2!=99.0))
{
//System.out.println("inside j" );
double distance = euDistance(temp1,temp2);
h++;
// if((i==0) &&(j==0))
if(h ==0)
minDistance = distance;
else
if (distance <= minDistance)
{
minDistance = distance;
tk1 = i;
tk2 = j;
//System.out.println("mindist "+minDistance+" "+tk1+" "+tk2);
}
}
} // for j
} // for i
//System.out.println("inside do "+tk1+" "+tk2);
ArrayList temp3 = new ArrayList();
ArrayList temp4 = new ArrayList();
temp3 = (ArrayList)this.valuelist.get(tk1);
temp4 = (ArrayList)this.valuelist.get(tk2);
//System.out.println(temp3);
//System.out.println(temp4);
ArrayList temp5 = new ArrayList();
for(int p=0;p
double value1 = ( (Double) temp3.get(p)).doubleValue();
double value2 = ( (Double) temp4.get(p)).doubleValue();
if ( value1 < value2 )
temp5.add(new Double(value1));
else
temp5.add(new Double(value2));
}
//System.out.println(temp5);
this.valuelist.set(tk1,temp5);
//System.out.println(this.valuelist.get(tk1));
//this.valuelist.remove(tk2);
ArrayList temp6 = new ArrayList();
temp6.add(new Double(99.0));
this.valuelist.set(tk2,temp6);
//System.out.println(this.valuelist.size());
//System.out.println(this.clusterlist.size());
//System.out.println("h is " + h);
// To merge clusters
int y1=0;
int y2=0;
int f1=0;
int f2= 0;
for (int x=0;x
ArrayList cluster = (ArrayList)this.clusterlist.get(x);
for(int z= 0; z
int s = ((Integer)cluster.get(z)).intValue();
if ( s==tk1)
y1 = x;
if(s==tk2)
y2 =x;
}
} //for x
//System.out.println("y1 "+y1+ "y2 " + y2);
ArrayList cluster1 = new ArrayList();
ArrayList temp7 = (ArrayList)this.clusterlist.get(y1);
//System.out.println("get y1 " +temp7);
int size = temp7.size();
//System.out.println("size is " + size);
for(int s=0;s
int v1 = ((Integer)temp7.get(s)).intValue();
//System.out.println(" v1 is " + v1);
cluster1.add(new Integer(v1));
}
//System.out.println("cluster is "+cluster1);
temp7 = (ArrayList)this.clusterlist.get(y2);
for(int y=0;y
int v2= ((Integer)temp7.get(y)).intValue();
cluster1.add(new Integer(v2));
}
//System.out.println(cluster1);
this.clusterlist.set(y1, cluster1);
this.clusterlist.remove(y2);
q = this.clusterlist.size();
r = this.k;
//System.out.println("q is "+q + " "+r);
if( q == r)
break l1;
}
//System.out.println("cluster nos "+ this.clusterlist.size());
/*ArrayList t1= new ArrayList();
t1= (ArrayList)this.clusterlist.get(0);
System.out.println(t1.size());
ArrayList t2= new ArrayList();
t2= (ArrayList)this.clusterlist.get(1);
System.out.println(t2.size());
ArrayList t3= new ArrayList();
t3= (ArrayList)this.clusterlist.get(2);
System.out.println(t3.size());*/
}
catch(Exception e)
{ }
}
// Compute the Euclidean Distance between two tuples.
protected double euDistance(ArrayList tuple1, ArrayList tuple2) {
double sum = 0;
for (int i = 0; i < tuple1.size(); i++) {
double value1 = ( (Double) tuple1.get(i)).doubleValue();
double value2 = ( (Double) tuple2.get(i)).doubleValue();
sum += Math.pow( (value1 - value2), 2);
}
return Math.sqrt(sum);
}
/**
* Output the clustering results.
*/
public boolean output(String filename) {
try {
// check if any of the possible output files exists.
boolean fileExist = false;
System.out.println("clusterlist size " + this.clusterlist.size());
for (int i = 0; i < this.clusterlist.size(); i++) {
File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
if (outputFile.exists()) {
fileExist = true;
break;
}
}
if (fileExist) {
BufferedReader lineReader = new BufferedReader(new InputStreamReader(
System.in));
while (true) {
System.out.print("The filename has existed. Overwrite? (Y/N)");
String st = lineReader.readLine();
if (st.equals("Y")) {
break;
}
else if (st.equals("N")) {
return false;
}
}
} // if
// Output: 1. Print the centriod and the number of data points in each cluster.
// 2. Store the actual data points of each cluster in a separate file.
for (int i = 0; i < this.clusterlist.size(); i++) {
// ArrayList centroid = (ArrayList)this.centroidlist.get(i);
ArrayList cluster = (ArrayList)this.clusterlist.get(i);
// 1. Print the centriod and the number of data points in each cluster.
int size = cluster.size();
System.out.println("-------- Cluster " + (i + 1) + " (" + size +
" data) --------");
// System.out.print(" Centroid: (");
//for (int j = 0; j < this.attrlist.size(); j++) {
// double value = ( (Double) centroid.get(j)).doubleValue();
// if (j == this.attrlist.size() - 1) {
// System.out.println(this.double2string(value, 2) + ")\n"); // last attribute.
// }
// else {
// System.out.print(this.double2string(value, 2) + ", ");
// }
// }
// 2. Store the actual data points of each cluster in a separate file.
File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
StringBuffer buf = new StringBuffer();
for (int m = 0; m < cluster.size(); m++) {
ArrayList tuple = (ArrayList)this.origvalues.get( ( (Integer) cluster.
get(m)).intValue());
System.out.println(tuple);
for (int j = 0; j < this.attrlist.size(); j++) {
double value = ( (Double) tuple.get(j)).doubleValue();
if (j == this.attrlist.size()-1 ) {
buf.append(this.double2string(value, 2) +"\n"); // last attribute.
}
else {
buf.append(this.double2string(value, 2) + ", "); // last attribute.
}
}
}
writer.write(buf.toString());
writer.close();
} // for
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private String double2string(double d, int decimal) {
String str = Double.toString(d);
int length = str.indexOf('.') + decimal + 1;
if (str.length() < length) {
length = str.length();
}
return str.substring(0, length);
}
}// Fig. 22.12: SliderDemo.java
// Testing SliderFrame.
import javax.swing.JFrame;
public class SliderDemo
{
public static void main( String args[] )
{
SliderFrame sliderFrame = new SliderFrame();
sliderFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
sliderFrame.setSize( 220, 270 ); // set frame size
sliderFrame.setVisible( true ); // display frame
} // end main
} // end class SliderDemo
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/// Fig. 22.11: SliderFrame.java
// Using JSliders to size an oval.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class SliderFrame extends JFrame
{
private JSlider diameterJSlider; // slider to select diameter
private OvalPanel myPanel; // panel to draw circle
// no-argument constructor
public SliderFrame()
{
super( "Slider Demo" );
myPanel = new OvalPanel(); // create panel to draw circle
myPanel.setBackground( Color.YELLOW ); // set background to yellow
// set up JSlider to control diameter value
diameterJSlider =
new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 );
diameterJSlider.setMajorTickSpacing( 10 ); // create tick every 10
diameterJSlider.setPaintTicks( true ); // paint ticks on slider
// register JSlider event listener
diameterJSlider.addChangeListener(
new ChangeListener() // anonymous inner class
{
// handle change in slider value
public void stateChanged( ChangeEvent e )
{
myPanel.setDiameter( diameterJSlider.getValue() );
} // end method stateChanged
} // end anonymous inner class
); // end call to addChangeListener
add( diameterJSlider, BorderLayout.SOUTH ); // add slider to frame
add( myPanel, BorderLayout.CENTER ); // add panel to frame
} // end SliderFrame constructor
} // end class SliderFrame
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************///Demonstrate Sockets.
import java.net.*;
import java.io.*;
class sock {
public static void main(String args[]) throws Exception {
int c;
Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str = (args.length == 0 ? "osborne.com" : args[0]) + "\n";
byte buf[] = str.getBytes();
out.write(buf);
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
s.close();
}
}
// Fig. 19.8: Sort1.java
// Using algorithm sort.
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
public class Sort1
{
private static final String suits[] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
// display array elements
public void printElements()
{
List< String > list = Arrays.asList( suits ); // create List
// output list
System.out.printf( "Unsorted array elements:\n%s\n", list );
Collections.sort( list ); // sort ArrayList
// output list
System.out.printf( "Sorted array elements:\n%s\n", list );
} // end method printElements
public static void main( String args[] )
{
Sort1 sort1 = new Sort1();
sort1.printElements();
} // end main
} // end class Sort1
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
/*
- This program will sort all the list of numbers that you have entered in either ascending or descending order
- The following are the steps for sorting a list in ascending or descending order
*/
import java.io.*;
class sortInSequence
{
public String sTotalInputs;
public int iTotalInputs = 0;
public int[] inputElement = new int[50];
public BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void takeInput()
{
try
{
System.out.print("Enter the total no. of elements you want: ");
sTotalInputs = br.readLine();
iTotalInputs = Integer.parseInt(sTotalInputs);
for(int i=1; i<=iTotalInputs; i++)
{
inputElement[i] = Integer.parseInt(br.readLine());
}
}
catch(IOException ioe)
{
System.out.println("ERROR!!!");
System.exit(1);
}
}
public void giveOutput()
{
for(int i=1; i<=iTotalInputs; i++)
{
System.out.println(i + ". " + inputElement[i]);
}
}
void ascending()
{
int newArray[]= new int[iTotalInputs];
for(int i=1; i<=iTotalInputs; i++)
{
int position = i;
for(int j=1; j<=iTotalInputs; j++)
{
if(inputElement[i] > inputElement[j])
{
position++;
}
else
{
j++;
newArray[position] = inputElement[i];
}
}
}
}
void descending(int[] n)
{
}
public static void main(String[] args)
{
sortInSequence s1 = new sortInSequence();
s1.takeInput();
s1.giveOutput();
}
}import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SoundApplet extends JApplet
implements ActionListener,
ItemListener {
AppletSoundList soundList;
String auFile = "spacemusic.au";
String aiffFile = "flute+hrn+mrmba.aif";
String midiFile = "trippygaia1.mid";
String rmfFile = "jungle.rmf";
String wavFile = "bottle-open.wav";
String chosenFile;
AudioClip onceClip, loopClip;
JComboBox formats;
JButton playButton, loopButton, stopButton;
boolean looping = false;
public void init() {
String [] fileTypes = {auFile,
aiffFile,
midiFile,
rmfFile,
wavFile};
formats = new JComboBox(fileTypes);
formats.setSelectedIndex(0);
chosenFile = (String)formats.getSelectedItem();
formats.addItemListener(this);
playButton = new JButton("Play");
playButton.addActionListener(this);
loopButton = new JButton("Loop");
loopButton.addActionListener(this);
stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setEnabled(false);
JPanel controlPanel = new JPanel();
controlPanel.add(formats);
controlPanel.add(playButton);
controlPanel.add(loopButton);
controlPanel.add(stopButton);
getContentPane().add(controlPanel);
startLoadingSounds();
}
public void itemStateChanged(ItemEvent e) {
chosenFile = (String)formats.getSelectedItem();
soundList.startLoading(chosenFile);
}
void startLoadingSounds() {
//Start asynchronous sound loading.
soundList = new AppletSoundList(this, getCodeBase());
soundList.startLoading(auFile);
soundList.startLoading(aiffFile);
soundList.startLoading(midiFile);
soundList.startLoading(rmfFile);
soundList.startLoading(wavFile);
}
public void stop() {
onceClip.stop(); //Cut short the one-time sound.
if (looping) {
loopClip.stop(); //Stop the sound loop.
}
}
public void start() {
if (looping) {
loopClip.loop(); //Restart the sound loop.
}
}
public void actionPerformed(ActionEvent event) {
//PLAY BUTTON
Object source = event.getSource();
if (source == playButton) {
//Try to get the AudioClip.
onceClip = soundList.getClip(chosenFile);
onceClip.play(); //Play it once.
stopButton.setEnabled(true);
showStatus("Playing sound " + chosenFile + ".");
if (onceClip == null) {
showStatus("Sound " + chosenFile + " not loaded yet.");
}
return;
}
//START LOOP BUTTON
if (source == loopButton) {
loopClip = soundList.getClip(chosenFile);
looping = true;
loopClip.loop(); //Start the sound loop.
loopButton.setEnabled(false); //Disable loop button.
stopButton.setEnabled(true);
showStatus("Playing sound " + chosenFile + " continuously.");
if (loopClip == null) {
showStatus("Sound " + chosenFile + " not loaded yet.");
}
return;
}
//STOP LOOP BUTTON
if (source == stopButton) {
if (looping) {
looping = false;
loopClip.stop(); //Stop the sound loop.
loopButton.setEnabled(true); //Enable start button.
}
else if (onceClip != null) {
onceClip.stop();
}
stopButton.setEnabled(false);
showStatus("Stopped playing " + chosenFile + ".");
return;
}
}
}
package sports;
public interface spo
{
public int s=5;
} import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class srvr
{
public static void main(String args[])
{
ServerSocket acceptSock; // Declare the ServerSocket
// Instantiate a ServerSocket using constructor that takes only the port number
try {
acceptSock = new ServerSocket(1024);
}
catch(IOException ioe) {
System.out.println("Error opening server socket: " + ioe.getMessage());
return;}
Socket sock = null; // Declare a socket to represent the connection to a
// specific client, i.e. the socket client and server will
// communicate over
// Call accept() on the ServerSocket to receive client connections,
// when a connection is received a new socket is returned over which
// the client and server will communicate
System.out.println(" Server is in listen mode " );
while(true) {
try {
sock = acceptSock.accept();
}
catch(IOException ioe) {
System.out.println("accept error: " + ioe.getMessage());
break;
}
/* ... Process client connection ... */
// Only break out of while loop if there was an error
try{
// Instantiate an input stream tied directly to the socket
DataInputStream iStream = new DataInputStream(sock.getInputStream());
// Read a string and an int from the input stream, i.e from the socket
String helloString = iStream.readUTF();
int three = iStream.readInt();
System.out.println(helloString +" "+ three);
}
catch(IOException ioe) {
System.out.println("Read error: " + ioe.getMessage());
}
}
}
}
import java.io.*;
import java.lang.*;
//import 1.*;
import testclass.*;
class result extends test
{
int total;
void get()throws IOException
{
DataInputStream in = new DataInputStream(System.in);
sub1 = Integer.parseInt(in.readLine());
sub2 = Integer.parseInt(in.readLine());
}
void cal()
{
total = sub1+sub2;
System.out.println("total :"+total);
}
}
class ss
{
public static void main(String args[])throws IOException
{
result R = new result();
R.get();
R.cal();
}
}import java.io.*;
import java.lang.*;
import testclass.*;
/*interface student
{
int sports = 5;
}*/
class result extends test
{
int total;
void get()throws IOException
{
DataInputStream in = new DataInputStream(System.in);
sub1 = Integer.parseInt(in.readLine());
sub2 = Integer.parseInt(in.readLine());
}
void cal()
{
total = sub1+sub2;
//+sports;
System.out.println("total :"+total);
}
}
class sstudent
{
public static void main(String args[])throws IOException
{
result R = new result();
R.get();
R.cal();
}
}
import java.io.*;
//stack capable to store 4 elements
class Stack
{
int max,top;
int no[];
public Stack()
{
no=new int[5];
top=-1;
max=5;
}
public void push(int n)
{
if(top
no[++top]=n;
}
else
System.out.println("Stack full..");
}
public int pop()
{
int val;
if(top==-1)
{
System.out.println("Stack is Empty...");
return -1;
}
else
{
val=no[top--];
}
return val;
}
public void print()
{
System.out.println("Stack elements are..");
for(int i=0;i
}
}
class StackTest
{
public static void main(String arg[]) throws IOException
{
Stack s=new Stack();
s.push(11);
s.push(12);
s.push(13);
s.push(14);
s.push(15);
s.push(16);
s.print();
System.out.println("Pop ival="+s.pop());
s.print();
System.out.println("Pop ival="+s.pop());
s.print();
}
}
/*
This class describes the use of static variables
*/
import java.io.*;
public class staticVariable
{
//Delcare a static variable
static int instanceNo = 0;
public staticVariable()
{
instanceNo++;
}
public static void main(String[] args)
{
//Create 1st object
staticVariable sv1 = new staticVariable();
System.out.println("Instance for Sv1: " + sv1.instanceNo);
//Create 2nd object
staticVariable sv2 = new staticVariable();
System.out.println("Instance for sv1: " + sv1.instanceNo);
System.out.println("Instance for sv2: " + sv2.instanceNo);
//Note: Here sv1.instanceNo will be equal to sv2.instanceNo but both would have their own copy
staticVariable sv3 = new staticVariable();
System.out.println("Instance for sv1: " + sv1.instanceNo);
System.out.println("Instance for sv2: " + sv2.instanceNo);
System.out.println("Instance for sv3: " + sv3.instanceNo);
}
}
import java.io.*;
import java.util.*;
class stoken
{
public static void main(String arg[]) throws IOException
{
int sm=0,no;
String s;
DataInputStream in=new DataInputStream(System.in);
System.out.print("Enter numbers ?");
s=in.readLine();
StringTokenizer token =new StringTokenizer(s);
while(token.hasMoreTokens())
{
no=Integer.parseInt(token.nextToken());
sm+=no;
System.out.println(no);
}
System.out.println("Sum : "+sm);
}
}
class StrBuffDemo
{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer();
System.out.println("sb="+sb);
System.out.println("lngth="+sb.length());
System.out.println("capacity="+sb.capacity());
sb.append("hello friend");
sb.append(145);
System.out.println("now sb="+sb);
System.out.println("capacity="+sb.capacity());
System.out.println("lenth ="+sb.length());
System.out.println("sb.substring="+sb.substring(5));
sb.insert(5,"nice");
System.out.println("sb="+sb);
System.out.println("sb in reverse "+sb.reverse());
}
}
class StrConstructor
{
public static void main(String arg[])
{
String s1=new String();
System.out.println("S1 ="+s1);
byte []b={65,66,67,68,55,56,57};
char []ch={'a','b','c','d','e','2'};
String s2=new String(b);
System.out.println("S2="+s2);
String s3=new String(b,0,3);
System.out.println("S3="+s3);
String s4=new String(ch);
System.out.println("S4="+s4);
String s5=new String(ch,2,2);
System.out.println("S5="+s5);
String s6=new String(s4);
System.out.println("S6="+s6);
}
}class StrContruction
{
public static void main(String s[])
{
String s1=new String();
System.out.println("S1="+s1);
byte b[]={97,98,99,100,101,102};
char ch[]={'r','a','h','u','l'};
String s2=new String(b);
System.out.println("S2="+s2);
String s3=new String(b,1,5);
System.out.println("S3="+s3);
String s4=new String(ch);
System.out.println("S4="+s4);
String s5=new String(ch,2,3);
System.out.println("S5="+s5);
String s6=new String(s2);
System.out.println("S6="+s6);
String s7="Hell0 Deepak";
System.out.println("S7="+s7);
}
}class LatihanString{
public static void main(String[] args) {
String str="Selamat Datang di Program Studi Ilmu Komputer";
System.out.println("Variabel Str : " + str);
}
}class StringArray{
public static void main(String[] args) {
char[] arraystr={'I','L','M','U',' ','K','O','M','P','U','T','E','R'};
System.out.println("Array Char ");
for (int i=0; i
}
System.out.println("String Baru : ");
String str=String.copyValueOf(arraystr);
System.out.println(str);
}
}class StringBufferku{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
String kata="ILMU KOMPUTER";
sb.append("PRODI ").append(kata).append(" UGM");
System.out.println(sb.toString());
System.out.println(sb);
}
}class MenggabungString {
public static void main(String[] args) {
String str;
str="Selamat Datang "+" Mahasiswa Ilmu Komputer";
System.out.println(str);
str +="\nUniversitas Gadjah Mada";
System.out.println(str);
}
}class MembandingkanString {
public static void main(String[] args) {
String str1 = "Ilmu";
String str2 = "Komputer";
String str3 = "IlmuKomputer";
System.out.println("String 1:"+str1);
System.out.println("String 2:"+str2);
System.out.println("String 3:"+str3);
System.out.println("String 1 = String 3 ==> "+str1.equals(str3));
System.out.println("String 2 = String 3 ==> "+str2.equals(str3));
System.out.println("String 1 + String 2 = String 3 ==> "+(str1+str2).equals(str3));
String str4 = "Universitas Gadjah Mada";
String str5 = "universitas gadjah mada";
System.out.println("String 4:"+str4);
System.out.println("String 5:"+str5);
System.out.println("Perintah Pembandingan dibawah mengabaikan antara huruf besar dengan huruf kecil");
System.out.println("String 4 = String 5 ==> " +str4.equalsIgnoreCase(str5));
System.out.println("String 4 + String 5 = String 5 + String 4 ==> " +(str4+str5).equalsIgnoreCase(str5+str4));
String str6 = "MIPA";
String str7 = new String(str6);
String str8 = "mipa";
String str9 = "MIPA";
System.out.println("String 6:"+str6);
System.out.println("String 7:"+str7);
System.out.println("String 8:"+str8);
System.out.println("String 9:"+str9);
System.out.println("Perintah Pembandingan dengan ==");
System.out.println("String 6 = String 7 ==> "+ (str6==str7));
System.out.println("String 6 = String 8 ==> "+ (str6==str8));
System.out.println("String 6 = String 9 ==> "+ (str6==str9));
}
}class AwalAkhirString{
public static void main(String[] args) {
String str1 = "Ilmu Komputer Matematika dan Ilmu Pengetahuan Alam Universitas Gadjah Mada";
System.out.println(str1.startsWith("Ilmu"));
System.out.println(str1.endsWith("Ilmu"));
System.out.println(str1.startsWith("lmu",1));
System.out.println(str1.startsWith("lmu",2));
System.out.println(str1.startsWith("lmu",3));
System.out.println(str1.startsWith("Komp",7));
System.out.println(str1.startsWith("Komp",6));
System.out.println(str1.startsWith("Komp",5));
System.out.println(str1.endsWith("Mada"));
System.out.println(str1.startsWith("Mada"));
}
}class UrutanString{
public static void main(String[] args) {
String [] nama={"Mangga","Anggur","Apel","Jeruk","Nanas","Pepaya"};
String temp;
System.out.println("Nama - Nama Buah Sebelum Diurutkan");
for (int i=0; i
}
//Mengurutkan nama buah
System.out.println("==================================");
System.out.println("Nama - Nama Buah Setelah Diurutkan");
for (int i=0; i<(nama.length-1); i++){
for (int j=0; j<(nama.length-1); j++){
if (nama[j].compareTo(nama[j+1])>0){
temp=nama[j+1];
nama[j+1]=nama[j];
nama[j]=temp;
}
}
}
for (int i=0; i
}
}
}class PanjangString {
public static void main(String[] args) {
String str="Selamat Datang di Ilmu Komputer UGM";
int panjang;
panjang = "Selamat Datang di Ilmu Komputer".length();
System.out.println("Variabel Str : " + str);
System.out.println("Panjang Variabel Str : " + str.length());
System.out.println("Panjang Variabel Panjang : " + panjang);
}
}class PosisiKarakter {
public static void main(String[] args) {
String str1 = "Ilmu Komputer Matematika dan Ilmu Pengetahuan Alam Universitas Gadjah Mada";
System.out.println(str1.indexOf("Komputer"));
System.out.println(str1.indexOf("Komputer",10));
System.out.println(str1.lastIndexOf("Matematika"));
System.out.println(str1.lastIndexOf("Matematika",10));
System.out.println(str1.lastIndexOf("Matematika",20));
System.out.println(str1.indexOf(97));
System.out.println(str1.indexOf(97,7));
System.out.println(str1.lastIndexOf(97));
System.out.println(str1.lastIndexOf(97,7));
}
}class MendapatkanSubString {
public static void main(String[] args) {
String str="Ilmu Komputer Matematika dan Ilmu Pengetahuan Alam Universitas Gadjah Mada";
System.out.println("String : " +str);
System.out.println("Ditampilkan string dari posisi 5");
String sub1=str.subString(6);
System.out.println("String :" +sub1);
System.out.println("Ditampilkan string dari posisi 5 sampai 14");
String sub2=str.subString(6,14);
System.out.println("String :" +sub2);
}
}class ArrayKarakter{
public static void main(String[] args) {
String str="Ilmu Komputer UGM";
char[] arraystr=str.toCharArray();
System.out.println("String : " +str);
System.out.println("String Baru [toCharArray]: ");
for (int i=0; i
}
System.out.println("String Baru [getChars]: ");
char[] getstr=new char[10];
str.getChars(5,13,getstr,0);
for (int i=0; i
}
}
}// Fig. 29.3: StringCompare.java
// String methods equals, equalsIgnoreCase, compareTo and regionMatches.
public class StringCompare
{
public static void main( String args[] )
{
String s1 = new String( "hello" ); // s1 is a copy of "hello"
String s2 = "goodbye";
String s3 = "Happy Birthday";
String s4 = "happy birthday";
System.out.printf(
"s1 = %s\ns2 = %s\ns3 = %s\ns4 = %s\n\n", s1, s2, s3, s4 );
// test for equality
if ( s1.equals( "hello" ) ) // true
System.out.println( "s1 equals \"hello\"" );
else
System.out.println( "s1 does not equal \"hello\"" );
// test for equality with ==
if ( s1 == "hello" ) // false; they are not the same object
System.out.println( "s1 is the same object as \"hello\"" );
else
System.out.println( "s1 is not the same object as \"hello\"" );
// test for equality (ignore case)
if ( s3.equalsIgnoreCase( s4 ) ) // true
System.out.printf( "%s equals %s with case ignored\n", s3, s4 );
else
System.out.println( "s3 does not equal s4" );
// test compareTo
System.out.printf(
"\ns1.compareTo( s2 ) is %d", s1.compareTo( s2 ) );
System.out.printf(
"\ns2.compareTo( s1 ) is %d", s2.compareTo( s1 ) );
System.out.printf(
"\ns1.compareTo( s1 ) is %d", s1.compareTo( s1 ) );
System.out.printf(
"\ns3.compareTo( s4 ) is %d", s3.compareTo( s4 ) );
System.out.printf(
"\ns4.compareTo( s3 ) is %d\n\n", s4.compareTo( s3 ) );
// test regionMatches (case sensitive)
if ( s3.regionMatches( 0, s4, 0, 5 ) )
System.out.println( "First 5 characters of s3 and s4 match" );
else
System.out.println(
"First 5 characters of s3 and s4 do not match" );
// test regionMatches (ignore case)
if ( s3.regionMatches( true, 0, s4, 0, 5 ) )
System.out.println( "First 5 characters of s3 and s4 match" );
else
System.out.println(
"First 5 characters of s3 and s4 do not match" );
} // end main
} // end class StringCompare
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
/*
- This program explains everything about Strings
*/
import java.io.*;
class strings
{
public static void main(String[] args)
{
String t = null;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text: ");
t = br.readLine();
while(t.length() < 3)
{
t=br.readLine();
}
System.out.println("This is a string " + t);
System.out.println("Its Length = " + t.length());
System.out.println("Substring is = " + t.substring(0, 3));
//Display the true length, i.e. the code length
System.out.println("Code Length = " + t.codePointCount(0, t.length()));
//Display the character at a particular position
System.out.println("Character at 3 = " + t.charAt(2));
//Concatinates 2 strings
String temp = "Hi" + t;
System.out.println("Concatination of 2 strings = " + temp);
}
catch(IOException ioe)
{
System.out.print("Error!!!");
System.exit(1);
}
}
}class StrMethod
{
static String str="abc";
public static void main(String s[])
{
String str1="hello friend";
String str2="hello friend";
str= str.toUpperCase();
System.out.println("str="+str);
System.out.println("str1"+str1);
System.out.println("str2"+str2);
System.out.println("Str1 in uppercase="+str1.toUpperCase());
System.out.println("Str1 in lowercase="+str1.toLowerCase());
System.out.println("Str1.equals(str2)="+str1.equals(str2));
System.out.println("Str1.equalsIgnoreCase"+str1.equalsIgnoreCase(str2));
System.out.println("Length of str1"+str1.length());
System.out.println("CharAt(3)="+str1.charAt(3));
System.out.println("str1.substring(2)="+str1.substring(2));
System.out.println("str1.substring(0,3)"+str1.substring(0,3));
System.out.println(str1.startsWith("He")?"str1 start with He":"str1 not start with He");
}
}
import java.io.*;
class strsort
{
public static void main(String arg[]) throws IOException
{
int i,j,len;
String s[]=new String[5],swp;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter 5 strings ?");
for(i=0;i<=4;i++)
s[i]=in.readLine();
for(i=0;i<=3;i++)
{
for(j=i+1;j<=4;j++)
if(s[i].compareTo(s[j])>0)
{
swp=s[i];
s[i]=s[j];
s[j]=swp;
}
}
System.out.println("After sort....");
for(i=0;i<=4;i++)
System.out.println(s[i]);
}
}
package stud;
public class student
{
public int rollno,sub1,sub2;
}interface SuperInterface
{
void add(int a,int b);
}
public interface SubInterface extends SuperInterface
{
void sub(int x,int y);
}
interface SuperInterface
{
void add(int a,int b);
}
public interface SubInterface extends SuperInterface
{
void sub(int x,int y);
}
import javax.swing.JOptionPane;
public class SumOfAll10Numbers
{
public static void main(String[] args)
{
int num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,total;
num1=Integer.parseInt(JOptionPane.showInputDialog("Enter 1st Number "));
num2=Integer.parseInt(JOptionPane.showInputDialog("Enter 2nd Number "));
num3=Integer.parseInt(JOptionPane.showInputDialog("Enter 3rd Number "));
num4=Integer.parseInt(JOptionPane.showInputDialog("Enter 4th Number "));
num5=Integer.parseInt(JOptionPane.showInputDialog("Enter 5th Number "));
num6=Integer.parseInt(JOptionPane.showInputDialog("Enter 6th Number "));
num7=Integer.parseInt(JOptionPane.showInputDialog("Enter 7th Number "));
num8=Integer.parseInt(JOptionPane.showInputDialog("Enter 8th Number "));
num9=Integer.parseInt(JOptionPane.showInputDialog("Enter 9th Number "));
num10=Integer.parseInt(JOptionPane.showInputDialog("Enter 10th Number "));
total= num1+num2+num3+num4+num5+num6+num7+num8+num9+num10;
JOptionPane.showMessageDialog(null,"The Sum of the 10 Numbers is "+total);
}
}
class VarTest
{
void d()
{
System.out.println("Addtion of and");
}
}
class SuperMethod extends VarTest
{
void d()
{
System.out.println("Addtion of ");
super.d();
}
public static void main(String arg[])
{
SuperMethod sv =new SuperMethod ();
sv.d();
}
}interface SuperInterface1
{
void mul(int m,int n);
}class VarTest
{
void d()
{
System.out.println("Addtion of and");
}
}
class SuperMethod extends VarTest
{
void d()
{
System.out.println("Addtion of ");
super.d();
}
public static void main(String arg[])
{
SuperMethod sv =new SuperMethod ();
sv.d();
}
}class SuperDemo
{
int x;
SuperDemo()
{
System.out.println("Default constructor of super class x="+x);
}
SuperDemo(int x1)
{
x=x1;
System.out.println("parameterized constructor of super class x="+x);
}
}
class SuperTest extends SuperDemo
{
SuperTest()
{
super();
System.out.println("default constructor of super class x="+x);
}
SuperTest(int x1)
{
super();
x=x1;
System.out.println("parameterized constructor of super class x="+x);
}
public static void main(String arg[])
{
SuperTest s1=new SuperTest();
SuperTest s2=new SuperTest(20);
}
}class VarTest
{
int x=10;
}
class SuperVar extends VarTest
{
int x=20;
void add()
{
int z=x+super.x;
System.out.println("Addtion of "+x+"and"+ super.x +"is="+z);
}
public static void main(String arg[])
{
SuperVar sv =new SuperVar ();
sv.add();
}
}import java.io.*;
class Table
{
public static void main(String arg[])
{
try
{
InputStreamReader ir=new InputStreamReader(system.in);
Buffered Reader br=new BufferedReader(ir);
System.out.println("Enter the num1:");
int
/*
- This program would take inputs from user and display it.
*/
import java.io.*;
class takingInputs
{
public static void main(String[] args)
{
System.out.print("Enter a text: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = null;
try
{
text = br.readLine();
}
catch(IOException ioe)
{
System.out.println("Error in text");
System.exit(1);
}
System.out.println("You entered: " + text);
}
}package test1;
class test
{
int sub1,sub2;
}class Test2
{
int x,y;
void getData(int x1,int y1)
{
x=x1;
y=y1;
}
}
class SingleInherit1 extends Test1
{
void add()
{
int z=x+y;
System.out.println("Addtion of "+x+"and"+y+"is="+z);
}
}
class SingleInherit extends Test1
{
void sub()
{
int z=x-y;
System.out.println("Substraction of "+x+"and"+y+"is="+z);
}
}
class Multi
{
public static void main(String arg[]);
{
SingleInherit1 s1 =new SingleInherit1 ();
SingleInherit s2 =new SingleInherit ();
s1.getData(20,10);
s1.add();
s2.sub();
}
}
import java.io.*;
class TestException
{
void Demo()
{
throw new ArithmeticException();
}
public static void main(String s[])
{
TestException obj=new TestException();
try
{
obj.Demo();
System.out.println("A");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("b");
}
finally
{
System.out.println("c");
}
System.out.println("D");
}
}
package mypackage.subpackage;
public class TestSub
{
public void cube(int n)
{
int c=n*n*n;
System.out.println("Cube of "+n+"is="+c);
}
}
//to create a TextField
/* Compiled from TextField.java
public class java.awt.TextField extends java.awt.TextComponent
public java.awt.TextField();
public java.awt.TextField(int);
public java.awt.TextField(java.lang.String);
public java.awt.TextField(java.lang.String,int);
to see other methods c:>javap java.awt.TextField */
import java.awt.* ;
import java.applet.* ;
//
public class textfield extends Applet {
public void init() {
TextField name =new TextField("NAME:",20);
TextField log=new TextField(8);
TextField pass=new TextField(8);
pass.setEchoCharacter('*');
Label llog=new Label("LOGIN");
Label lpass=new Label("PASSWD");
add(name); add(llog); add(log); add(lpass); add(pass);
}
}
class throwdemo
{
void sqr(int num)
{
if(num<0 p=""> {
throw new NullPointerException();
}
else
{
int s=num*num;
System.out.println("Square of num="+s);
}
}
public static void main(String arg[])
{
throwdemo td=new throwdemo();
td.sqr(9);
td.sqr(-6);
}
}
class throwsdemo
{
void sqr(int num)throws Exception
{
if(num<0 p=""> {
throw new NullPointerException();
}
else
{
int s=num*num;
System.out.println("Square of num="+s);
}
}
public static void main(String arg[])
{
try{
throwsdemo td=new throwsdemo();
td.sqr(9);
td.sqr(-6);
}catch(Exception e)
{
System.out.println("Error is=== "+e);
e.printStackTrace();
}
}
}
class TipeData {
public static void main(String[] args) {
// Tipe data primitif
long data1 = 226531;
int data2 = 2235641;
short data3 = 714;
byte data4 = 34;
float data6 = (float) 1.733; // tipe data pecahan
double data5 = 4.967; // tipe data pecahan
char data7 = 'C';
boolean data8 = true;
System.out.println("Nilai Long : "+ data1);
System.out.println("Nilai Int : "+ data2);
System.out.println("Nilai Short : "+ data3);
System.out.println("Nilai Byte : "+ data4);
System.out.println("Nilai Double : "+ data5);
System.out.println("Nilai Float : "+ data6);
System.out.println("Nilai Char : "+ data7);
System.out.println("Nilai Boolean : "+ data8);
}
}
import java.io.*;
class TryCatch {
public static void main(String[] args) {
try{
System.out.println("Masuk 1 dari try catch");
File test = new File("c:\test.txt");
System.out.println("Masuk 2 dari try catch");
test.createNewFile();
System.out.println("Masuk 3 dari try catch");
}catch(java.io.IOException e) {
//code untuk menangani ekpsesi
System.out.println("Keluar dari try catch");
}
}
}class TryCatchFinally {
public static void methodLain(int i)
throws java.io.CharConversionException {
System.out.println("Buka file");
try{
System.out.println("Proses file");
System.out.println(i);
if(i==0)
{
System.out.println("True 1");
throw new java.io.CharConversionException("Test Eksepsi");
//System.out.println("True 2"); error
}
else
System.out.println("False");
}catch(java.io.CharConversionException e) {
System.out.println("Penanganan Eksepsi dalam method methodLain()");
throw e; //Eksepsi dilempar ke luar method
}
System.out.println("Tutup file");
}
public static void main(String[] args) {
try{
System.out.println(args.length);
methodLain(args.length);
}catch(java.io.CharConversionException e) {
System.out.println("Penanganan Eksepsi dalam method main()");
}
}
}import java.io.*;
import java.lang.*;
class one extends Thread
{
public void run()
{
for(int i=0;i<6 i="" p="">{
System.out.println("\t class :i"+i);
}
}
}
class second extends Thread
{
public void run()
{
for(int j=0;j<6 j="" p=""> {
System.out.println("\t class :j"+j);
if(j==2)
{
try
{
sleep(1);
}
catch(Exception e){}
}
}
}
}
class tstart
{
public static void main(String args[])
{
one X = new one();
second Y = new second();
X.start();
Y.start();
/*for(int i=0;i<5 i="" p="">{
if (i==2)
Y.suspend();
if(i==4)
Y.resume();
}
Y.suspend();
X.suspend();
for(int i=0;i<5 i="" p="">System.out.println(i);
Y.resume();
Y.stop();*/
}
}
import helloclass.*;
public class two {
public static void main (String args[])
{
a=10;
System.out.println(a);
}
} import java.net.*;
import java.io.*;
public class udpr
{
public static void main(String args[]) throws IOException
{
DatagramSocket sock; // Declare a Datagram socket
try {
sock = new DatagramSocket(8000); // Bind to local UDP port 8000
}
catch(IOException ioe) {
System.out.println("Error creating socket: " + ioe.getMessage());
return;
}
try
{
// Build structures to hold incoming information
byte[] dataBytes = new byte[255];
DatagramPacket pack = new DatagramPacket(dataBytes, dataBytes.length);
// Recieve the incoming packet
sock.receive(pack); // Sender information available in
// pack.getAddress() and pack.getPort()
System.out.println("Receive ");
// Unpackage the DataGramPacket
ByteArrayInputStream biStream = new ByteArrayInputStream(pack.getData());
DataInputStream iStream = new DataInputStream(biStream);
String helloString = iStream.readUTF();
int three = iStream.readInt();
System.out.println(helloString +" "+ three);
}
catch(Exception ioe) {
System.out.println("Receive error: " + ioe.getMessage());
}
try{
sock.close();
}
catch(Exception ioe) {
System.out.println("Close error: " + ioe.getMessage());
}
}
}
// Again, close() needs to be called on both applications, and an
// application receives no indication that a remote application has
// closed its UDP socket.
import java.net.*;
import java.io.*;
public class udps
{
public static void main(String args[]) throws IOException
{
DatagramSocket sock; // Declare a Datagram socket
try {
sock = new DatagramSocket(6000); // Bind to local UDP port 6000
}
catch(IOException ioe) {
System.out.println("Error creating socket: " + ioe.getMessage());
return;
}
try{
// Build the IP address and port
InetAddress destAddr = InetAddress.getByName("localhost");
int destPort = 8000;
// Configure the data stream
ByteArrayOutputStream boStream = new ByteArrayOutputStream();
DataOutputStream oStream = new DataOutputStream(boStream);
oStream.writeUTF("Hello!"); // write data to the stream
oStream.writeInt(3);
byte[] dataBytes = boStream.toByteArray(); // Convert stream to byte array
DatagramPacket pack = // Construct the DataGramPacket
new DatagramPacket(dataBytes, dataBytes.length, destAddr, destPort);
sock.send(pack);
}
catch(IOException ioe) {
System.out.println("Send error: " + ioe.getMessage());
}
}}
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("http://www.java.sun.com:80/docs/index#down");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
class UserDefineException
{
void cube(int c) throws MyException
{
if(c<0 p=""> {
throw new MyException(c);
}
else
{
int r=c*c*c;
System.out.println("Cube of "+c+" is "+r);
}
}
public static void main(String s[]) throws MyException
{
UserDefineException e=new UserDefineException();
e.cube(3);
e.cube(-3);
}
}class Variabel {
static int a;
public static void main(String[] args) {
int x; // variabel x ini dikenal di seluruh method main()
x = 10;
a = 2; //variabel a juga dikenal di sini
System.out.println("Nilai a : " + a);
{ //awal dari blok baru
int y; // variabel ini hanya dikenal di dalam blok code ini saja
y = 5;
System.out.println("Nilai x : " + x); //variabel x dikenal di sini
System.out.println("Nilai a : " + a); //variabel a juga dikenal di sini
{ //nested blok
int z;// variabel ini hanya dikenal di dalam nested blok ini saja
z = 20;
// variabel x,y dan a dikenal di dalam nested blok ini
System.out.println("Nilai x + y + z + a : " + (x + y + z + a));
} //akhir dari nested blok
//z = 11; // variabel z tidak lagi dikenal di sini
//variabel y masih dikenal di sini karena masih dalam blok
//code tempat ia dideklarasikan
System.out.println("Nilai y : " + y);
} //akhir dari blok baru
//y = 12; // variabel y tidak dikenal di sini
//variabel x masih dikenal di sini karena masih dalam blok
//code tempat ia dideklarasikan
System.out.println("Nilai x : " + x);
}
}
class Viji
{
public static void main (String args[])
{
System.out.println("Hello") ;
}
}class While {
public static void main(String[] args) {
int a = 10 ;
System.out.println("Sebelum while");
while(a>=10) {
System.out.println("Nilai a : "+a);
a--;
}
System.out.println("Setelah while");
}
}
import java.awt.*;
import java.awt.event.*;
public class WindowAdp1 extends Frame
{
public WindowAdp1()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent me)
{
System.exit(0);
}
}
);
setSize(1024,768);
setTitle("Adapter");
setVisible(true);
}
public static void main(String args[])
{
new WindowAdp1();
}
} class DataDemo
{
public void demo(String msg)
{
System.out.println("["+msg);
try{
Thread.sleep(2000);
}catch(Exception e)
{
System.out.println("Error is "+e);
}
System.out.println("]");
}
}
class DataImpl implements Runnable
{
Thread t;
DataDemo d;
String msg;
DataImpl(DataDemo d,String msg)
{
t=new Thread(this);
t.start();
this.d=d;
this.msg=msg;
}
public void run()
{
d.demo(msg);
}
}
public class WithoutSynch
{
public static void main(String arg[])
{
DataDemo d=new DataDemo();
DataImpl obj1=new DataImpl(d,"Hello");
DataImpl obj2=new DataImpl(d,"Friends");
DataImpl obj3=new DataImpl(d,"GOODLUCK");
}
}/*Using With 'this' Keyword*/
class Withoutthis
{
int x;
Withoutthis(int x)
{
this.x=x;
}
void Square()
{
int z=x*x;
System.out.println("Square of "+x+"is"+z);
}
public static void main(String arg[])
{
Withoutthis obj1=new Withoutthis(10);
obj1.Square();
}
}
class DataDemo
{
public void demo(String msg)
{
System.out.println("["+msg);
try{
Thread.sleep(2000);
}catch(Exception e)
{
System.out.println("Error is "+e);
}
System.out.println("]");
}
}
class DataImpl implements Runnable
{
Thread t;
DataDemo d;
String msg;
DataImpl(DataDemo d,String msg)
{
t=new Thread(this);
t.start();
this.d=d;
this.msg=msg;
}
public void run()
{
synchronized(d)
{
d.demo(msg);
}
}
}
public class WithSynch
{
public static void main(String arg[])
{
DataDemo d=new DataDemo();
DataImpl obj1=new DataImpl(d,"Hello");
DataImpl obj2=new DataImpl(d,"Friends");
DataImpl obj3=new DataImpl(d,"GOODLUCK");
}
}
import java.io.*;
import java.util.*;
class wordcount
{
public static void main(String arg[]) throws IOException
{
int ctr=0;
String s,s1,s2;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter a string with words ?");
s=in.readLine();
StringTokenizer token1 =new StringTokenizer(s);
StringTokenizer token2 ;
while(token1.hasMoreTokens())
{
token2=new StringTokenizer(s);
s1=token1.nextToken();
ctr=0;
while(token2.hasMoreTokens())
{
s2=token2.nextToken();
if(s1.equals(s2))
ctr++;
}
System.out.println("'"+s1+"' Frequency "+ctr+" Times");
}
}
}
/*Using Without 'this' Keyword*/
class Wot
{
int x;
Wot(int x)
{
x=x;
}
void Square()
{
int z=x*x;
System.out.println("Square of "+x+"is"+z);
}
public static void main(String arg[])
{
Wot obj1=new Wot(10);
obj1.Square();
}
}
// Fig. 14.27: WriteRandomFileTest.java
// This program tests class WriteRandomFile.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class WriteRandomFileTest
{
public static void main( String args[] )
{
WriteRandomFile application = new WriteRandomFile();
application.openFile();
application.addRecords();
application.closeFile();
} // end main
} // end class WriteRandomFileTest
No comments:
Post a Comment