Programming Reference Sheets: Java

Everyones Help Needed

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 4910 Views - Last Post: 19 August 2006 - 11:41 AM Rate Topic: -----

#1 skyhawk133   User is offline

  • Head DIC Head
  • member icon

Reputation: 1964
  • View blog
  • Posts: 20,421
  • Joined: 17-March 01

Programming Reference Sheets: Java

Posted 01 August 2006 - 03:12 PM

Alrighty, just like the C++ thread, I would like to assemble a "cheat sheet" or reference sheet with the most commonly used functions, operators, variables, etc.

These will be put together on an 8 1/2"x11" sheet so keep it short and sweet. Ready... go!
Is This A Good Question/Topic? 0
  • +

Replies To: Programming Reference Sheets: Java

#2 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 04:25 PM

Every application MUST have a main method:
public static void main(String[] args)
{
//Tell the program what to do....
}


Applets are different. You must include special packages, and there is no main method. You must override at least one of the following methods:
import java.awt.Graphics; //For graphics used in the paint method.
import javax.swing.JApplet;

public class AppletNameHere extends JApplet
{
	public void init()
	{
	 /*Usually includes things only done once (like initializing variables or placing GUI components)*/
	}
	public void start()
	{
	}
	public void paint(Graphics g)
	{
	super.paint(g);
	//Generally for creating output (often as a graphic display).
	}	
}


Additionally, to implement a Java Applet, use the following HTML code (in an HTML doc, of course - not in your program):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>BrowserTitleHere</title>
</head>
<body>
<object code="AppletName.class" width="x" height="y"></object>
</body>
</html>

Assuming you save the .class file in the same directory as the html file. x and y are integers for the height/width of the applet window.
Was This Post Helpful? 0
  • +
  • -

#3 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 06:40 PM

NOTE: All complete Java statements must be terminated by a semicolon ( ; ), just as all complete English statements must be terminated by periods.

Comments
Comments are wholly disregarded by the compiler - they only serve to help others understand your code. Java allows comments similar to C/C++ comments:
--In-line Comments --The compiler will disregard all the text after the comment slashes (//) until the next line.
--Multi-Line Comments --The compiler ignores all text between the two markers:
Start: /*
End: */
example: //Single line of comments....

/*A bunch
of
lines of comments */


Variables & Constants
Variables are declared in the following general form:
modifier(s) type VariableName1, VariableName2;
You can have any number separated by commas. Modifiers are reserved words like public, private, protected
You can also initialize them at the same time:
example: private int myVariable=0;
Primitives
There are a few types of basic (or primitive) variables that use basic operators.
  • integer - int - holds only integral values
  • character - char - holds values corresponding to a single character (UNICODE)
  • floating point - float - holds decimal numbers
  • double precision - double - holds a larger range of decimal values
Constants
If you want to define a variable for a known value and you know you'll never change that value, you should make a constant. Everywhere you put the constant name, the compiler will replace it with the number. You can define constants for any primitive data type using the final modifier in this general form:
final type ConstantName = value;
where "value" is value that corresponds with the data type ("type").
example: final double myConstant = 3.14159265; //myConstant is pi and always will be!

This post has been edited by SPlutard: 01 August 2006 - 07:20 PM

Was This Post Helpful? 0
  • +
  • -

#4 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 06:55 PM

Basic Form of an Application
Java is made up of classes. Each class has its own variables and methods to act on them. Classes can be complex creatures that extend and implement other classes, but in its most basic form, the Java application takes this general shape:

//import statements go here (if any)

public class ClassName //The start of the class. The modifier public can be changed.
{
	//declare constants and stream objects

		public static void main(String[] args) //The start of the main method. The public modifier can be changed.
	{
		//variable declaration
				//statements - perhaps calls to other methods too.
	}
}


It is also a good idea to include good, quality documentation that is descriptive, succinct, and allows others to understand why you did what you did. A good way to start is to include some basic information about the program (and perhaps its author). Generally, I like to fill out this general outline at the top of each of my apps:
/*
 *Program:
 *Author:
 *Date Created:
 *Description:
*/

You can include copyright info, if you're worried about such things.

This post has been edited by SPlutard: 01 August 2006 - 07:55 PM

Was This Post Helpful? 0
  • +
  • -

#5 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 07:15 PM

Escape Sequences
Escape sequences (or escape characters) allow the coder to manipulate Strings.
-- \n -- Newline character; starts a new line
-- \t -- Tab
-- \b -- Backspace
-- \r -- Return
-- \\ -- Backslash
-- \' -- Single Quote
-- \" -- Double Quote

Assignment
To change the value of a primitive variable, you "assign" a value to it. Assignment statements can take a few forms, based on the type of primitive and the desired action. Here, "expression" will mean any mathematic expression and/or variable(s).
Simple:
variable = expression;
//The expression is now stored in the variable.

Addition
variable += expression;
//Is the same as: variable = variable + expression;

Subtraction
variable -= expression;
//Is the same as variable - expression;

Multiplication
variable *= expression
//Is the same as variable = variable * expression;

Strings
String strVar;
strVar = "This is the assigned string.";

Note: Assignment is different for non-primitives, Strings being the exceptions (and wrapper classes).
Was This Post Helpful? 0
  • +
  • -

#6 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 07:53 PM

Type Casting
If you need to convert a value from one type to another (like from double to int), you need to type cast!
To cast, simply place the desired form in parentheses before the expression to be converted.
example:
int intVar;
intVar = (int) (2.6 * 11.294 + 12.0);


Note: The compiler will usually cast for you automatically when you are converting a less restrictive type (like double) to a more restrictive type (like int). However, it will throw errors your way if you try to go in the opposite direction. In that case, use implicit casts like above.

General Casting Guidelines
  • When converting to an integer, the decimal component(s) is/are truncated (chopped off) NOT rounded.
  • When converting an int to a decimal number, the compiler simply adds ".0".
  • The expression directly after the type cast operator is cast first, then evaluated with the other expressions, but parentheses always come first. example:(double) (15)/2 --> 7.5
    (double) (15/2) --> 7.0
**Be careful with your parenthses when casting!!
Was This Post Helpful? 0
  • +
  • -

#7 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 01 August 2006 - 08:28 PM

Naming Conventions
These define the rules regarding the composition of names for varaibles, classes, methods, etc. (called identifiers):
  • Identifiers may consist of: letters, numbers, underscores, and dollar signs, BUT CANNOT begin with a number.
  • No other symbols are permitted.
  • Reserved words cannot be used as identifiers.
  • Java is Case Sensitive - so "yes" is not "Yes", which is not "YES".
Reserved Words
The following words are reserved and connot be used as identifiers:
abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
("const" and "goto" are not currently used)

Special Symbols
+ - * / . ; ? , <= >= == !=

Logical Operators
> -- Greater than
< -- Less than
>= -- Greater than or equal to
<= -- Less than or equal to
!= -- Not equal to
== -- Equal to
&& -- And
|| -- Or

Switch
Used to select from a list of possible choices.
switch(LogicalExpression)
{
case value1: //Statements
				   break;
case value2: //Statements
				   break;
default: //Statements
}

You may have as many cases as necessary, but they MUST evaluate to integral values.

If/Else
if(LogicalExpression)
{
//Statements
}
else
{
//Statements
}

The first block will execute if "LogicalExpression" evaluates to "true". Otherwise, the "else" block will execute. The brackets are not necessary if there is only one statement.
Was This Post Helpful? 0
  • +
  • -

#8 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 02 August 2006 - 01:28 PM

Dialog Windows (With Swing)
Package: javax.swing
Class: JOptionPane
Methods: showInputDialog, showMessageDialog

Input:
StringVariable = JOptionPane.showInputDialog(strExpression);
--> creates a dialog box, data entered is returned as a string & assignmed to StringVariable
--> strExpression should be a string, it is the prompt for the box

Output
JOptionPane.showMessageDialog(parentComponent, messageStringExpression, boxTitleString, messageTypeConstant);
--> parentComponent: the parent of the dialog, usually null
--> messageStringExpression: Actual message for the box
--> boxTitleString: title of box
-->messageType: a constant specifying the type of message, changes the icon in the box
  • JOptionPane.ERROR_MESSAGE
  • JOptionPane.INFORMATION_MESSAGE
  • JOptionPane.PLAIN_MESSAGE
  • JOptionPane.QUESTION_MESSAGE
  • JOptionPane.WARNING_MESSAGE
example: JOptionPane.showMessageDialog(null, "Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);

NOTE: To properly terminate program execution, include: System.exit(); at end.

For Loop
Repeats a given number of times. **Don't forget to declare the variable (often "i") somewhere before the loop!
for(i=0; i<10; i++)
{
//Repeated statements. Example will loop 10 times.
}


While Loop
Repeats until condition is false (where "condition" is any logical expression).
while(condition)
{
//Repeated statements.
}

Was This Post Helpful? 0
  • +
  • -

#9 SPlutard   User is offline

  • code.ninja
  • member icon

Reputation: 18
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Re: Programming Reference Sheets: Java

Posted 02 August 2006 - 01:46 PM

What else are we looking for? I'm not sure what direction to head in... More specific or less? More basic or more advanced? I dunno..... :/
Was This Post Helpful? 0
  • +
  • -

#10 skyhawk133   User is offline

  • Head DIC Head
  • member icon

Reputation: 1964
  • View blog
  • Posts: 20,421
  • Joined: 17-March 01

Re: Programming Reference Sheets: Java

Posted 02 August 2006 - 01:51 PM

Give us a few days to knock out the C++ one and you can use it as a reference. Amadeus is going to help edit it tomorrow I think.
Was This Post Helpful? 0
  • +
  • -

#11 Jhin   User is offline

  • D.I.C Regular
  • member icon

Reputation: 9
  • View blog
  • Posts: 257
  • Joined: 06-July 05

Re: Programming Reference Sheets: Java

Posted 08 August 2006 - 08:09 PM

Here's some stuff I threw together after work...Some may already have been posted...

Java Extension Packages
import <class>

Common Extensions
java.awt
java.io
java.lang
java.util
javax.swing

Data Types
boolean
char
byte
short
int
long
float
double
string

Comments
// Single line Comment
/* Multiple line Comment */

Arithmetic Operators
Addition +
Subtraction -
Multiplication *
Division /
Modulus %

Equality Operators
== (Equal To)
!= (Not Equal To)

Relational Operator
> (Greater Than)
< (Less Than)
>= (Greater Than or Equal To)
<= (Less Than or Equal To)

In-/Decremental Operators
++x (Preincrement)
x++ (Postincrement)
--x (Predecriment)
x-- (Postdecriment)


Logical Operators
&& (logical AND)
& (boolean logical AND)
|| (logical OR)
| (boolean logical inclusive OR)
^ (boolean logical exclusive OR)
! (logical NOT)

Escape Sequences
\n (newline)
\t (horizontal tab)
\r (carriage return)
\\ (backslash)
\" (double quote)

Other
?: (Conditional)
= (Assignment)

If Else

if (<conditional>) {
<statement(s)>;
}
else{
<statement(s)>;
}

For Loop

for (<initial value>; <condition>; <in-/decrement>){
<statement(s)>;
}

While Loop
while( <condition> )
{ <statement(s)>; }

Do While Loop
do {
<statement(s)>;
} while (<condition>);

Switch Case

switch(<expression>){
case <option 1>:
<statement>;
break;
case <option 2>:
<statement>;
break;
[default:
<statement>;
]

}

Arrays
int c[] = new int[5]; //declare and allocate in one

//declare and allocate in two
int myArray[];
myArray = new int[5];

//initialize
myArray = {10,20,30,40,50}

//access 3rd Element
myArray[2] = var;


Method
<access modifier> <return data type> <function name> ( <parameters> )
{
<declarations>
<statements>
[return;]
[return <expression>;]

}

Class
<access modifier> <return data type> <class name> [extends <superclass name>][implements <interface name>]
{
<declarations>
<methods>
}

This post has been edited by Jhin: 14 August 2006 - 08:19 AM

Was This Post Helpful? 0
  • +
  • -

#12 skyhawk133   User is offline

  • Head DIC Head
  • member icon

Reputation: 1964
  • View blog
  • Posts: 20,421
  • Joined: 17-March 01

Re: Programming Reference Sheets: Java

Posted 08 August 2006 - 08:21 PM

Excellent!
Was This Post Helpful? 0
  • +
  • -

#13 William_Wilson   User is offline

  • lost in compilation
  • member icon

Reputation: 207
  • View blog
  • Posts: 4,812
  • Joined: 23-December 05

Re: Programming Reference Sheets: Java

Posted 09 August 2006 - 06:10 AM

Exception handling is very important in java:
somewhere there must exist a try catch block
try{
//code, can include method calls
}
catch(Exception e){ //Exception name can be more specific and multiple catches may be used
//what to do on error
}


Any method called within the try block may throw an error back as long as it is a subclass of at least one of the catch blocks. Instead of having it's own try catch block: as an example
if(var == NULL)
throw new Exception();


the class or method which does any throwing must declare it in it's header as:
public int method() throws Exception{ //.. }


Was This Post Helpful? 0
  • +
  • -

#14 Jhin   User is offline

  • D.I.C Regular
  • member icon

Reputation: 9
  • View blog
  • Posts: 257
  • Joined: 06-July 05

Re: Programming Reference Sheets: Java

Posted 09 August 2006 - 06:43 AM

IOStream
//reads keyboard input writes to screen

//declarations Input-/OutputStream Objects & int for storage of keypressed
InputStream istream;
OutputStream ostream;
int var;

//assignment
istream = system.in;
ostream = system.out;

//while input is not EOF (ctrl+z)
while((var = istream.read()) != -1)
{
//write variable to screen
ostream.write(var);
}
//close IOStreams
istream.close();
ostream.close();

Example with error handling:
import java.io.*;
public class ReadWrite
{
  public static void main(strings[] args) throws IOException
  {

	InputStream istream;
	OutputStream ostream;
	int c;

	istream = System.in;
	ostream = System.out;

	try
	{
	  while((c = istream.read()) != -1)
	  {
		ostream.write(c);
	  }
	}

	catch(IOException e)
	{
	  System.out.println("Error: " + e.getMessage());
	}
  
	finally
	{
	  istream.close();
	  ostream.close();
	}
  } 
}

Was This Post Helpful? 0
  • +
  • -

#15 skyhawk133   User is offline

  • Head DIC Head
  • member icon

Reputation: 1964
  • View blog
  • Posts: 20,421
  • Joined: 17-March 01

Re: Programming Reference Sheets: Java

Posted 14 August 2006 - 08:43 AM

Alrighty ladies and gentlemen. Here is Version 0.1 of the Java Reference Sheet. Please note the need for 1 or 2 more things in the right column as well as plenty of editing.

Attached is the .txt of what is in the .pdf and the .pdf itself. Please take a look and attach changes/suggestions. I'd like to get this published by Wednesday.

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2