A java program is defined by a public class that takes the form:
public class program-name {
optional variable declarations and methods
public static void main(String[] args) {
statements
}
optional variable declarations and methods
}
Hello World Program
class HelloWorld {
public static void main (String args[]) {
System.out.println(”Hello World!”); //Displays the enclosed String on the Screen Console
}
}
Comments
/* text */
// Text
/** Documentation */
Data Types
byte – 8 bits
short – 16 bits
int – 32 bits
long – 64 bits
float – 32 bits
double – 64 bits
char
boolean
Examples
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
int x; // Declaration for x.
x = 100; // Initialization.
x = x + 12; // Using x in an assignment statement.
Arithmetic Operators
op1 + op2 op1 added to op2
op1 – op2 op2 subtracted from op1
op1 * op2 op1 multiplied with op2
op1 / op2 op1 divided by op2
op1 % op2 Computes the remainder of dividing op1 by op2
Assignment Operators
i += 2; // Same as “i = i + 2″
Increment and Decrement Operators
i=1; j=++i => j=2
i=1; j=i++ => j=1
Relational Operators
op1 > op2 op1 is greater than op2
op1 >= op2 op1 is greater than or equal to op2
op1 < op2 op1 is less than to op2
op1 <= op2 op1 is less than or equal to op2
op1 == op2 op1 and op2 are equal
op1 != op2 op1 and op2 are not equal
Boolean Operators
| the OR operator
& the AND operator
^ the XOR operator
! the NOT operator
|| the short-circuit OR operator
&& the short-circuit AND operator
== the EQUAL TO operator
!= the NOT EQUAL TO operator
A B A|B A&B A^B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false
Conditional Operators
if (a > b) {
max = a;
}
else {
max = b;
}
max = (a>b) ? a : b
Loops
for (i=0; i < args.length; i = i++) {
System.out.print(args[i]);
System.out.print(” “);
}
int i = 0;
while (i<=5) {
document.writeln(”#”+i);
i = i + 1;
};
Methods
class FactorialTest { //calculates the factorial of that number.
public static void main(String args[]) {
int n;
int i;
long result;
for (i=1; i <=10; i++) {
result = factorial(i);
System.out.println(result);
}
} // main ends here
static long factorial (int n) {
int i;
long result=1;
for (i=1; i <= n; i++) {
result *= i;
}
return result;
} // factorial ends here
}
Array
Define
int[] k;
float[] yt;
String[] names;
Declare
k = new int[3];
yt = new float[7];
names = new String[50];
Assign
k[0] = 2;
k[1] = 5;
Example
float[] squares = new float[101];
for (int i=0; i <= 500; i++) {
squares[i] = i*2;
}
Classes and Objects
Class Syntax
Use the following syntax to declare a class in Java:
//Contents of SomeClassName.java
[ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implements SomeInterfaces ]
{
// variables and methods are declared within the curly braces
}
* A class can have public or default (no modifier) visibility.
* It can be either abstract, final or concrete (no modifier).
* It must have the class keyword, and class must be followed by a legal identifier.
* It may optionally extend one parent class. By default, it will extend java.lang.Object.
* It may optionally implement any number of comma-separated interfaces.
* The class’s variables and methods are declared within a set of curly braces ‘{}’.
* Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
* Finally, the source file name must match the public class name and it must have a .java suffix.
Example
class simple {
// Constructor
simple(){
p = 1;
q = 2;
r = 3;
}
int p,q,r;
public int addNumbers(int var1, int var2, int var3)
{
return var1 + var2 + var3;
}
public void displayMessage()
{
System.out.println(”Display Message”);
}
}
class example1{
public static void main(String args[])
{
// To create a new instance class
Simple sim = new Simple();
// To show the result of the addNumbers
System.out.println(”The result is ” + Integer.toString(addNumbers(5,1,2)));
// To display message
sim.displayMessage();
}
}
Interface
An interface defines methods that a class implements. In other words it declares what certain classes do. However an interface itself does nothing. All the action at least, happens inside classes. A class may implement one or more interfaces. This means that the class subscribes to the promises made by those interfaces. Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface. The methods of an interface are abstract — they have no bodies. Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies — implementations — for its methods.
Example
interface Counting
{
abstract void increment();
abstract int getValue();
}
class ScoreCounter implements Counting {
….
}
Exception Handling
// This is the Hello program in Java
class ExceptionalHello {
public static void main (String args[]) {
/* Now let’s say hello */
try {
System.out.println(”Hello ” + args[0]);
}
catch (Exception e) {
System.out.println(”Hello whoever you are”);
}
System.out.println(”Bye”);
}
}
Out put when you run without arg
Hello whoever you are
Bye
File I/O and Stream
There are only three things necessary to write formatted output to a file rather than to the standard output:
1. Open a FileOutputStream using a line like
FileOutputStream fout = new FileOutputStream(”test.out”);
This line initializes the FileOutputStream with the name of the file you want to write into.
2. Convert the FileOutputStream into a PrintStream using a statement like
PrintStream myOutput = new PrintStream(fout);
The PrintStream is passed the FileOutputStream from step 1.
3. Instead of using System.out.println() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.
Example
import java.io.*;
class FileOutput
{
public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream connected to “myfile.txt”
out = new FileOutputStream(”myfile.txt”);
// Connect print stream to the output stream
p = new PrintStream( out );
p.println (”This is written to a file myFile.txt”);
p.close();
}
catch (Exception e)
{
System.err.println (”Error writing to the file myFile.txt”);
}
}
}
For reading file
import java.io.*;
class cat {
public static void main (String args[]) {
String thisLine;
//Loop across the arguments
for (int i=0; i < args.length; i++) {
//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args[i]);
// now turn the FileInputStream into a DataInputStream
try {
DataInputStream myInput = new DataInputStream(fin);
try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println(”Error: ” + e);
}
} // end try
catch (Exception e) {
System.out.println(”Error: ” + e);
}
} // end try
catch (Exception e) {
System.out.println(”failed to open file ” + args[i]);
System.out.println(”Error: ” + e);
}
} // for end here
} // main ends here
}