Java Notes for “Programming Languages” and -Comments //… or /*…*/ or /**…*/
“Advanced Programming” -Blocks {…}
-Methods
-main method (always public static void)
-Identifiers (UpperCase, LowerCase, _, $, Digits) cannot start with digit
case sensitive (TOTAL, Total, total)
-Consistency in naming (Beginning Lowercase => methods and identifiers
Beginning Uppercase => classes
Java Source All Uppercase => constants
Across the
Code (.java)
Internet -print and println methods
using
HTML
-command line arguments (main method)
-object oriented programming (classes, objects, inheritance, etc.)
Java
Java Bytecode
Compiler
(.class)
Web Browser //Turkey.java File
class Turkey
{
Java Bytecode Java
Interpreter Compiler
public static void main(String[] args)
Interpreter
{
System.out.print("The international "
(Applet) + "dialing code ");
Machine System.out.print("for Turkey is " + 90);
Code (.exe) }
}
//FrstProg.java file
//NameTag.java File
class FrstProg
class NameTag
{
{
/*This program just writes something to the console
public static void main(String[] args)
and will stop executing*/
{
public static void main(String[] args)
System.out.println("Hello! My name is " +
{
args[0]);
System.out.println("This is the first lesson");
}
//println is part of API
}
}
}
javac NameTag.java (compile)
HOW TO COMPILE AND RUN JAVA FILES: java NameTag XXX (run)
Hello! My name is XXX (output)
Java Compiler:
javac FrstProg.java (creates FrstProg.class) To import a package:
Java Interpreter:
java FrstProg (executes FrstProg.class) import package.class;
Or:
Output: import package.*;
This is the first lesson
-2- (Java Notes 2011 SSN )
JAVA API (Application Programming Interface) OPERATORS:
Unary: + -
View: http://java.sun.com/j2se/1.3/docs/api/ Binary: * / % Multiplication, division, remainder
Download: http://java.sun.com/j2se/1.3/docs.html + - Addition, subtraction
+ String concatenation
= Assignment
Packages += -= *= /= %=
java.applet creates programs (applets) that are easily transported across
the web. count++ return count and then add 1
java.awt (Abstract Windowing Toolkit) Draw graphics and create ++count add 1 and then return count
graphical user interfaces. count-- return count and then subtract 1
java.io perform a wide variety of I/O functions. --count subtract 1 and then return count
java.lang general support. It is automatically imported.
java.math for high precision calculations. ! Logical not ^ Bitwise xor == !=
java.net communicate across a network. && Logical and & Bitwise and > <
java.rmi (Remote Method Invocation) create programs that can be || Logical or | Bitwise or >= <=
distributed across multiple computers.
java.sql interact with databases.
java.text format text for output. CODITIONS AND LOOPS:
java.util general utilities. condition ? expression1 : expression2
example: int larger = (num1>num2) ? num1 : num2 ;
WRAPPER CLASSES:
Classes declared in package java.lang:
Byte Float Character Boolean Void
Short Double
Integer
Long
-3- (Java Notes 2011 SSN )
INSTANTIATION AND REFERENCES GARBAGE COLLECTION
class CarExample Objects are deleted when there are no more references to them. There is a possibility
{ to have the System run the garbage collector upon demand using the System.gc()
public static void main(String[] args) method.
{ Calling the gc() method suggests that the Java Virtual Machine expend effort toward
int total = 25; recycling unused objects in order to make the memory they currently occupy
int average; available
average = 20; for quick reuse. When control returns from the method call, the Java Virtual Machine
has made a best effort to reclaim space from all discarded objects.
//CarClass should be declared
CarClass myCar = new CarClass();
CarClass yourCar;
yourCar = new CarClass(); If we add the line:
//To call a method use "." CarClass momCar = myCar;
myCar.speed(50);
yourCar.speed(80);
we get the following drawing:
System.out.println("My car cost $" + myCar.cost());
}
}
CarClass() 2 1
{
_speed = 0;
_cost = 2500;
}
output: gfedcba
-5- (Java Notes 2011 SSN )
ARRAYS: MULTI DIMENSIONAL ARRAYS:
Class RandomAccessFile
Example:
+--java.io.RandomAccessFile
java.io.RandomAccessFile import java.io.*;
Since: out.writeUTF("end");
JDK1.0
in2.close();
out.close();
Constructor Summary }
}
RandomAccessFile(File file, String mode) Useful methods
Creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
readByte() / writeByte() seek(long pos)- set the file pointer offset.
readInt() / writeInt() length()- Return the length of the file.
RandomAccessFile(String name, String mode)
readDouble() / writeDouble() skipBytes(int n)
Creates a random access file stream to read from, and optionally to write to, a file readBoolean() /writeBoolean()
with the specified name.
-9- (Java Notes 2011 SSN )
EXCEPTION HANDLING:
public static void main (String[] args)
import java.io.*; {
import java.util.*; System.out.println("This is the Java IO Example");
IO test = new IO();
class IO DataInputStream file = null;
{ try
private String line; {
private StringTokenizer tokenizer; file = new DataInputStream(new
FileInputStream(“books.txt”));
public void newline(DataInputStream in) throws IOException }
{ catch (FileNotFoundException fnfe)
line = in.readLine(); {
if (line == null) System.out.println(“Could not find file. “
throw new EOFException(); + “Please place books.txt in main directory”);
tokenizer = new StringTokenizer(line); }
} try
{
public String readString(DataInputStream in) throws IOException while (true)
{ {
if (tokenizer == null) System.out.println(“Type: “ + test.readString(file));
newline(in); System.out.println(“Name: “ + test.readString(file));
while (true) System.out.println(“Cost1: “ + test.readDouble(file));
System.out.println(“Cost2: “ + test.readDouble(file));
{ }
try }
{ catch (EOFException exception)
return tokenizer.nextToken(); {
} //just exit the program
catch (NoSuchElementException exception) }
{ catch (IOException exception)
newline(in); {
} System.out.println(“Exception occurred: “
} + exception.getMessage());
}
}
public double readDouble(DataInputStream in) throws IOException finally
{ {
if (tokenizer == null) System.out.println(“This Line is printed anyhow.”);
newline(in); }
while (true) }
{ }
try
{
String str = tokenizer.nextToken();
return Double.valueOf(str.trim()).doubleValue();
}
catch (NoSuchElementException exception)
{
newline(in);
}
}
}
- 10 - (Java Notes 2011 SSN )
class PrivateCar extends Car
INHERITANCE: {
final int LEATHER = 1;
class Car final int STANDARD = 0;
{ float engine;
boolean auto; int seats = LEATHER;
int price;
int maxSpeed = 120; PrivateCar()
{
Car() auto = false;
{ price = 150000;
auto = true; }
price = 100000;
} PrivateCar(float engine, int seats)
{
Car (boolean auto, int price) super(); //must be first command
{ this.engine = engine;
this.auto = auto; this.seats = seats;
this.price = price; super.speed(100);
} }
public static void main(String[] args) protected- class is accessible jast for it’s subclasses and package members.
{ public - class is publicly accessible.
Car a = new Car(); abstract - class can’t be instantiated.
Car b = new Car(true, 120000); final - class can’t be subclassed.
b.speed(80);
int c = b.cost();
}
}
- 11 - (Java Notes 2011 SSN )
INTERFACES:
class AmericanDisk extends IsraelDisk
interface ProductsInterface {
{ public double m_DollarRate;
public String getName();
public int getAvailableCount(); public AmericanDisk(String name,
public String getKind(); int avail, double cost, double rate)
public double getCost(); {
} super(name, avail, cost);
m_DollarRate = rate;
class Book implements ProductsInterface }
{
public String m_Name; public String getKind() {return super.getKind() +"[A]";}
public int m_Available; public double getCost() {return m_Cost * m_DollarRate;}
public double m_Cost; }