Print this page

Java



JAVA Quick Reference

 

Example

import java.awt.Graphics;

public class HelloWorldApplet extends java.applet.Applet {

  public void paint(Graphics graphicsIn)

  {

    graphicsIn.drawString("HelloWorldApplet.java",25,25);

  }

 

For Loop

For (int=1, i<=10; i++)

   Console.WriteLine(“The number is {0}”,i );

 

While Loop

While (x<100)

X++;

 

If…Then

If (nCount < nMax)

{

     nTotal += nCount;

     nCount++;

}

Else

{

     nTotal += nCount;

     nCount-;

}

 

Array

Int[] nums = new int[2];

nums[0] = 100;

nums[1] = 200;

char[ ] vowels = new char[ ] {'a','e','i','o','u'};

Console.WriteLine(vowels [1]);

int[,] array = {{1,2},{3,4}};

 

Struct

struct Point {

  public int x, y;

}

Point p1 = new Point(  );

Point p2;

p2.x = p2.y = 0;

Point[] points = new Point[3];

 

Function Method

public void Remove(int index)

  {

  if (index > Count - 1 || index < 0)

     {

        System.Windows.Forms.MessageBox.Show("Index not valid!");

     }

  else

     {

        List.RemoveAt(index);

     }

  }

 

Class

Public class Widget

   {

      public string Name;

      public Widget()

      {

      }

   }

 

Database

Import java.sql.*;

Connection conn=Drivermanager.getconnection(Local,User,pwd)

System.out.println(“creating Statement”);

Statement stmt =conn.createStatement();

ResultSet rs = stmt.executeQuery(“SECLECTED* from userdb where name=”ian””);

String name =  rs.getString(1); // Filed 1 is login name

//Password is filed 2 - do not display

String fullName = rs.getString(3);

System.out.println(“User”+name+”is named”+fullName);

 

Socket

Public class Listen{

       Public static final short PORT = 9999 

Public static void main (String[] argv) throws IOException {

      ServerSorket sock;       Socket clientSock;

      Try {   Sock = new ServerSocket(PORT) ;

                 While ((clientSock=sock.accept()) != null) {

                 process(clientSock) } }

      catch (IOException e) {System.err.println(e)}}

System.out.println(“Accept from client”+s.getInetAddress());

//the conversation would be here

s.close(); }}