Java BasicsThese are my personal notes that I use as a quick help in my work.
|
|
Three types of java programs: applets, applications, and servlets/JSP pages.
Programming environment
SET PATH=%PATH%;D:\j2sdk1.4.1_02\BIN
SET CLASSPATH=.; D:\j2sdk1.4.1_02\lib\tools.jar; D:\j2sdk1.4.1_02\lib\servlet.jar; %CLASSPATH%
SET JAVA_HOME=D:\j2sdk1.4.1_02
javac <options> <source-file>
(include .java
extension)java <class-name>
(without an extension
because it is the name of the class, and the class has to be in the file named "class-name.class
").
And this class has to have a "main
" method.<HTML><BODY> <APPLET CODE=class-file-name WIDTH=200 HEIGHT=100> </APPLET> </BODY></HTML>
Sample application:
class HelloWorldApp {
public static void main(String[] args){
System.out.println("Hello World!");
}
}Compile:
javac -verbose HelloWorldApp.java
Run:
java HelloWorldApp
The method "main" is the starting point.
To terminate (e.g. in windowClosing):dispose(); System.exit(0);
Memory allocation (default is 256MB):
java -Xmx1024MB HelloWorldApp
Sample windows bat file to compile
javac needs jdk
SET JAVA_HOME="C:\Program Files (x86)\Java\jdk1.8.0_141"
SET PATH=%PATH%;"%JAVA_HOME%\bin"
javac -verbose HelloWorldApp.javaSample windows bat file to run
java can use jre if the .class file is present. You can use the jdk as well to run.
SET JAVA_HOME="C:\Program Files (x86)\Java\jre1.8.0_141"
SET PATH=%PATH%;"%JAVA_HOME%\bin"
java HelloWorldApp
Sample applet:
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}Compile:
javac -verbose HelloWorld.java
Page to display applet (size is in pixels):
<HTML> <BODY>
<TITLE>Hello World!</TITLE>
<APPLET CODE=HelloWorld WIDTH=150 HEIGHT=40> </APPLET>
</BODY> </HTML>
Open the HTML page or run appletviewer the-html-page.html
Execution of an applet | |
---|---|
Constructor | |
public void init() {...} |
When applet is first loaded |
public void start () {...} |
When applet starts; when browser is deiconized; when browser returns to page (back from another URL). |
public void paint(Graphics g ){...} |
|
public void stop() {...} |
When browser is iconized; when browser enters another link. |
An identifier contains characters (Unicode UTF-16, not only a-z and A-Z),
digits (but not at beginning), '_' (underscore) and '$'.
Names are case sensitive. Starting with "$", and "_" is allowed but not good practice.
Variables start with lowercase and each word starts in upper case (nameWordWord). Constants are all uppercase with
underscores seperating the words (CONSTANT_WORD_WORD).
It is possible (since Java 7) to place underscores in between digits in a numerical litteral.
// comments
/* comments */
/** comments picked up by javadoc */
Visibility:
Specifier | visible in class | visible in package | visible in subclass | full access |
---|---|---|---|---|
private (members) |
X
|
|
|
|
default access (without "public", "private" or "protected") for members and classes |
X
|
X
|
|
|
protected (members) |
X
|
X
|
X
|
|
public (members and classes) |
X
|
X
|
X
|
X
|
private protected no longer used (java 1.0) |
-
|
-
|
-
|
-
|
Note that objects of the same type can see each others private members. The "privacy" is not at the object level but at the class level.
Generally, fields (variables) should be private: use methods to give or modify field values.
Restrict visibility of methods.
Static variables become class variables as opposed to instance variables.
If the static variable is public, it can be accessed without any instance of the class.
For clarity, access the static variables with the name of the class as opposed to the name of an instance.
The static variables are stored in one place in memory independently of instances.
Use static methods to handle static variables. An example could
be the count of instances created, with a counter increment in the constructor.
Final variables are constants (name in upper case by convention).
Transient variables cannot be serialized (for serialization).
Volitile variables cannot be optimized; this is rarely used.
Variables of primitive data types (byte, short, int, long, float, double, boolean,
and char) are not intialized.
boolean truth = true; |
True or false |
|
1 character, 0..216-1, unicode |
String a_string1; |
Use double quotes! |
Integral types:byte i = 1; // 8 bits, i.e. -128..127 |
Literals are generally int, long if followed by L two's complement 0nnn octal 0xnnn hexadecimal |
Floating point: |
Literal is float if followed by F or double if followed by D |
|
Aggregate data types Declaration does not assign space: use the constructor |
Number. |
Wrapper classes To each type corresponds a class |
Character aChar = new Character('a');
|
|
aString.length() / aStringBuffer.length() |
Number of characters Capacity is allocated length for string buffer Character at 0 .. length -1 |
aString.substring( 3 [,5] ) |
Sub string from 3 [to 5]; notice small "s". Count from 0 to len-1. The result goes from beginIndex to endIndex-1. aString = "Chris"; aString.substring(2,4) -- > "ri" |
|
|
aString.toCharArray() --> an array of characters |
|
aString.indexOf("looking for" [, int from]) |
"looking for" may be a character or a string Returns 0..length-1, or -1 if not found |
aStringBuffer.append(...) |
Automatic allocation of memory (but slow) |
String.valueOf(a number) --> string |
|
Void |
Wrapper for void |
Boolean |
Wrapper for boolean |
NumberFormat |
Class for formatting numbers according to locale |
enum anEnum { ABC, DEFG, TER }; |
Enumeration. The elements are constants, so put in upper case. All enums extend java.lang.Enum |
|
pattern: DecimalFormat is overloaded |
|
Declaration |
|
Instantiation and initialization (the constructor initializes the object) |
varable_name = null; |
Release memory |
|
Declares array. The two syntaxes are equivalent, although |
|
Declare the array |
for (int i=0; i < Date.length; i++) ... |
Elements 0 .. array_name.length-1 |
String names[] = {"Chris", "Vicky", ...}; |
Shorthand initialization (note curly brackets) Get length with names.length -1
|
char twoDim [][] = new char [5][7]; |
Shorthand rectangular array |
char twoDim [][] = new char [5][]; // but not [][5] |
Array need not be rectangular |
int ii[] = new int[8]; |
New assignement results in loss of previous array! |
int a[] = new int[4]; |
Special method of the Sytem class. |
|
Various methods of the java.util.Arrays class: index of a specific value are two arrays equal? fill array sorting (parallel sort in version 8) |
|
Declares array list. Name of underlying object between < and >. (called generics) It is possible to give a size at creation (here 100). It is a hint, and more elements can be created. |
|
Add an element, get an element, test if element is in the list, remove, get number of elements |
|
Loop through the class |
|
Sort using the collections class, which is also part of java.util |
|
Declares hash map. Put generics between < and >: the first is the key and the second is the value. It is possible to give the number of buckets at creation (here 40), and the load factor, which is the percentage of capacity at which new buckets are automatically created. |
|
Adds a key-value pair, get a value based on the key (returning null if not found), get a value or use default, test for existence of a key or a value, return the number of elements, returns set of entries (for loops, use Set class in java.util) . |
|
Adds a key-value pair, get a value based on the key (returning null if not found), get a value or use default, test for existence of a key or a value, return the number of elements, returns set of entries (for loops, use Set class in java.util) . |
|
|
Variables defined inside a method are automatic = local = temporary = stack. Destroyed at exit of method.
<< |
. |
For qualified names Use for arrays parameter list (java.sun.com puts the postfix ++ and -- here) |
<< |
++ -- |
a=5; x=a++; --> x==5, a==6
// postfix notation Sign (note that unary + has the effect of promoting a byte, short or char to type int) Not / bitwise complement use ( ) around expression for type cast: (int)(expression) |
>> |
new |
New object (java.sun.com puts the casting operator here) |
>> |
* / |
Multiplication and division modulo (integer remainder) 9 % 7 --> 2
|
>> |
+ |
+ also for concatenation (infix notation) |
>> |
<< |
|
>> |
< > <= >= |
|
>> |
== !=
|
Equal (note double sign), not equal |
>> |
& |
bitwise and; both operands are always evaluated |
>> |
^ |
bistwise xor (different) |
>> |
| |
bitwise or; both operands are always evaluated |
>> |
&& |
logical and; does not evaluate second operand if first is false |
>> |
|| |
logical or; does not evaluate second operand if first is true |
<< |
cond ? expr-for-true : expr-for-false
|
conditional |
<< |
= *= /= %= += -= |
Assignement |
Bitwise operations for using with flags:
int VISIBLE = 1;
int DRAGGABLE = 2;
int flags = 0;
flags = flags | VISIBLE; // set flag
flags = flags ^ VISIBLE; // flip flag
flags = flags & ~ VISIBLE; // reset flag
if ((flags & VISIBLE) == VISIBLE) { ... } // test flag
if (boolean expr) { |
"else" is optional |
switch (int expression) { |
Works with byte, short, char, int, enumerated types,
and with classes such as String, Character, Byte, Short, and Integer.
Remember the "break"! |
for (init, init; boolean expr; alter expr, alter expr) { ... } |
|
int[] iArray; |
With arrays and collections |
while (boolean expr) { |
|
|
|
break [label]; |
break ... out of loop continue ... at beginning of next iteration of loop the ingredient for spaghetti code! |
java.lang.Object
|
Throw --> catch if you can, otherwise the program terminates Error --> let program terminate Exception is in java.lang, therefore an import statement is not necessary |
|
Examples:
TheException and AnotherException are throwable objects Multiple exceptions separated by "|" (pipe) |
|
|
|
Rule "declare or handle": either use a "try{}catch(){}" block or put in declaration (as on left) so that calling method can handle. The compiler checks that some exceptions are handled: these are checked exceptions. Others are runtime exceptions and the compiler will not complain if there is no handler. |
passVarNumberOfArgs(type aParam, type... aVararg) |
varargs: For the last parameter, put the type, three dots (ellipsis), a space, and the parameter name. Allows zero or more parameters. Treat as an array. Get the number of parameters with aVararg.length. |
In java, threads are "pre-emptive", that is higher priority "pre-empts" a lower priority thread that is running. Runnable threads are placed in queues according to priority. Otherwise, execution passes from one thread to another when the previous thread stops (or sleeps). A stopped thread goes to the back of the queue.
A thread (small "t") has: | A Thread (big "T") is an instance of the class java.lang.Thread See example below. |
CPU | Thread t |
code | class 'instanceOfRunnable' |
data | instance 'r' of the class |
public class InstanceOfRunnable implements Runnable /* or extends Thread */ {
// Must have run() method
public void run() {
synchronized(this) {
while (cond-not-fulfilled) {
try {this.wait();} // wait for condition
catch (InterruptedException e) { }
}
...... // Here, do treatment that is protected by synchronized
this.notify(); // waiting threads can start
} // end synchronized
try {
Thread.sleep(10); } // Eventual pause
catch (InterruptedException e){
}
}
}
Runnable r = new InstanceOfRunnable();
Thread t = new Thread(r); // constructor for Thread takes an instance of Runnable
t.start(); // start the execution
t.sleep(n); // pause
minimum of n milliseconds, threads of lower priority may be executed
t.suspend() //
t.yield(); // only yield to threads of same priority level
t.stop(); // cannot be re-started
Thread.currentThread()
--> thread currently running
(use to get handle on itself);
not necessary if extending Thread
t.isAlive() --> thread is started and not stopped and has not reached the end of its "run()" method
Each object has two queues: queue for lock and queue for wait/notify.
Locking
Make code consistent in a class by holding a lock; locked threads join a sort of queue:
method a { synchronized (this) { /* statements that modify data */ } }
method b { synchronized (this) { /* statements that modify data */ } }
All of a method can be synchronized, but more danger of deadlocks:
sychronized void aMethod() {}
N.B. Protected data should be private
N.B. One strategy of prevent deadlocks is to take the locks always in the same order.
Thread interaction (wait / notify)
object.wait();
--> thread no longer runnable, on wait queue of object
object.notify();
--> first in queue is runnable
object.notifyAll();
--> all in queue are runnable
An InterruptedException also terminates the wait state
N.B. Putwait()
andnotifiy()
inside a synchronized block.
(See comment)
public class Date { |
Constructor method has exactly the same name as the class; it cannot return a value (do not put void). If the constructor is Overloading the constructor name is possible. Use "this" to refer to one of the constructor methods when within the class. Use super(...) in the constructor of a subclass |
public static void main() |
Starting point Static indicates no need for invoking an instance. A static method is a class method. |
<access level> [<modifiers>] <return_type> |
Method declaration: Arguments are always passed by value. For reference types, the reference cannot be modified, but the object's values can be (i.e. the values to which the reference points). Classes are reference type objects. If arguments have same name as the class's member variables, then they "hide" the member variables. Use "this." to refer to class members. Note that hiding is error-prone. |
|
A static method becomes a class method that can be called without creating an instance. However only static variables and the arguments can be used; "this" cannot be used. Other variables and methods are available "through" an instance of the class. By default, members are non-static. |
<access level> final |
A final class cannot have sub-classes. Final methods cannot be overridden (static or private methods are final anyway). A final variable acts as a constant. |
|
Abstract classes declares methods without bodies that must be implemented in sub-classes. Instantiate the subclass, not the abstract class (x = new SubClass();). |
<access level> native |
Method implemented in another language |
<access level> synchronized |
Method needs a monitor to run |
return [a_value]; |
Return a value (must be of return type); no value if void. For classes: an object of that class or a sub-class |
public void display(int i)
|
Overloading method names is creating several methods with the same name but with unambiguous differences in the argument lists. However, the type does not differentiate methods, just the argument list. |
|
MyClass inherits variables and methods (but not constructors) from StandardClass, which is the parent class. A class can only inherit from one parent class (except interfaces). Public and protected members are inherited, as well as package access members if in the same package as the superclass. |
|
Methods with the same name, return type and arguments override the methods of the parent class. The runtime type of the object determines which method is used. Note that subclass variables with the same name hide those of the superclass. Access hidden variable with "super.". Use " An overriding method cannot be less accessible that the parent's method e.g. a private method cannot override a public method. And an overriding method cannot throw more exceptions than the method that it overrides. Final methods cannot be overridden. Static methods can be hidden but not overridden. It is a good idea to always define a no-argument constructor |
class EnclosingClass { // also called "outer class" |
Nested classes see also private members of enclosing class. Two types: static nested class and inner class (non-static) |
|
An interface is an abstract class where no methods have bodies and where there are no member variables (just constants that are by definition public static final). Methods are by definition public and abstract. A class can inherit several interfaces (but only one class). Unrelated classes can inherit the same interface. The interface can be used as a type (for parameters). |
StandardClass anObject = new MyClass(); |
Polymorphism is referring to an object as if it is of a parent class. Objects have several forms. |
StandardClass anArray[] = new StandardClass[10];
|
A heterogenous collection contains objects with common ancestor. If the collection is of type java.lang.Object, then the collection can contain any type of object. |
MyClass myObject = new MyClass(); |
Subclassing Note cast "(Object)whateverObject" |
aStandardObject = myObject; |
Casting "up" is possible by simple assignment |
if (anObject instanceof MyClass) myObject = (MyClass)anObject; |
Casting "down" is allowed by compiler if the new cast is a subclass |
// myObject = (MyClass)objectOfMySecondClass; |
Casting "across" is not possible |
finalize { |
Override the finalize of the object class for any cleaup if necessary (usually not necessary). Call super.finalize as the last statement. |
import java.util.Enumeration;
| Simple display of all members of an enumeration. This may be out of date and remplaced by enum type (see above). |
Class description includes:
N.B.
"class StandardClass anObject extends Object"
is implicit). null
to variables that are no longer used so as to give more chances of freeing up memory.
import java.awt.*; |
Preceding each object's name with "java.awt." is not necessary. |
Button b;
b = new Button("OK");
|
|
Frame f; f = new Frame("Example"); |
BorderLayout by default. |
f.add("South", b); |
With Border (default) layout manager, use one of the five regions North, East, Center, West, South.Only one component per region. |
new BorderLayout() // default, 5 areas (N, S, E, W, center) |
|
Panel p = new Panel(); f.add(p); p.add(...); |
A panel has a layout manager and components |
public class ButtonHandler |
Handler method must be exactly as shown. The class must be an implementation of ActionListener. It can also extend ActionListener. Category is "Action" |
aLabel.setText("..."); |
Label |
new Checkbox("label", false); // label and default value |
See item category for events |
CheckboxGroup radio = new CheckboxGroup(); |
|
Choice c = new Choice(); |
See item category for events |
Canvas c |
|
.requestFocus method forces focus on canvas, label, ... |
|
TextArea t = new TextArea ("...", r, c); // rows and columns |
t.setEditable(boolean) Note that size may be ignored by layout manager.
Sub-class of TextComponent |
TextField f = new TextField("...", len); |
See action category for events (triggered by pressing enter) Use setEditable method to make read-only.
Note that size may be ignored by layout manager. Sub-class of TextComponent |
List l = new List ( h, true); |
h is preferred height in rows (may be overridden by layout manager) Allows multiple selections. |
Dialog d = new Dialog(f, "...", false); |
Separate dialog window Listen to windowClosing so as to hide the window. |
FileDialog d = new FileDialog ( f, "FileDialog");
|
|
ScrollPane sp = new ScrollPane();
|
|
MenuBar theMenuBar = new MenuBar(); // horizontal menu
Menu
theMenuFile = new Menu("File"); |
Use action category for the events on the menu items. Action events on menus are possible but unusual. Can only add a menubar to a frame |
CheckboxMenuItem aCheckboxMenuItem = new CheckboxMenuItem (".."); |
Use the ItemListener interface. |
PopupMenu aPopupMenu = new PopupMenu("Popup"); |
Show generally inside an event |
setForeground( new Color(r,g,b) ) |
See java.awt.Color class |
setFont("TimesRoman", Font.PLAIN, 14) |
See java.awt.Font class Dialog, Helvetica, TimesRoman, Courier Font.BOLD, Font.ITALIC, Font.PLAIN, Font.BOLD+Font.ITALIC |
Handler method: public void methodNameSeeBelow (java.awt.event.WindowEvent e) {
}
Category | Interface | Handler method |
|
---|---|---|---|
Action | ActionListener |
actionPerformed(ActionEvent e) |
e.getActionCommand() returns label by default.Change with e.setActionCommand()
|
Item | ItemListener |
itemStateChanged(ItemEvent e) |
e.getStateChange() returns ItemEvent.DESELECTED or ItemEvent.SELECTED
returns label
|
Mouse Motion | MouseMotionListener |
mouseDragged(MouseEvent e) |
e.getX() e.getY() returns position |
Mouse Button | MouseListener |
mousePressed(MouseEvent e) |
|
Key | KeyListener |
keyPressed(keyEvent e) |
e.getKeyChar() returns the character |
Focus | FocusListener | focusGained(Event e) |
|
Adjustment | AdjustmentListener | adjustmentValueChanged |
|
Component | ComponentListener | componentMoved(ComponentEvent e) |
|
Window | WindowListener | windowClosing(WindowEvent e) |
|
Container | ContainerListener | componentAdded(ContainerEvent e) |
|
Text | TextListener | textValueChanged(TextEvent e) |
Overwrite the event handler and return true so that the event is not propagated to the parent component.
|
x and y are baseline |
paint(Graphics g) |
Draw the display. Called to handle exposure. Eventually, use the clip rectangle. Exposure causes |
repaint() |
Ask the AWT to change the display by calling update |
update (Graphics g) |
Normally clears the display and calls the method paint |
g.drawImage ( anImage, x, y, image-observer) |
The image observer is the class with the paint method. |
Class hierarchy:
java.lang.object
java.awt.Component
java.awt.Button
....
java.awt.TextArea
java.awt.Container
java.awt.Frame
java.awt.Panel
java.applet.Applet
JavaTM Foundation Classes (JFC). Do not mix with AWT. Needs Java2.
Visual index to the Swing Components on Sun's site
|
|
import javax.swing.*; |
Minimal example v.1.3 Swing components often use AWT :
|
frame.addWindowListener(new WindowAdapter() { |
Listener to use in version prior to 1.3 |
try {
|
Define look and feelUIManager.getCrossPlatformLookAndFeelClassName()
|
JButton button = new JButton("...");
|
Button This is an anonymous event handler |
JLabel label = new JLabel("...");
|
Label |
pane.setBorder(BorderFactory.createEmptyBorder( t, l, b, r ); | Border (top, left, bottom, right) |
JTextField f = new JTextField(5);
|
Text box of width 5 String can be " <html>...</html> "
|
ImageIcon anIcon = new ImageIcon("xyz.gif",
"label"); aButton = new JButton(anIcon); |
Add an image to a button |
Note on threads: once a swing component has been realized (constructed and made visible), then all code should be in the event-dispatching thread. There are exceptions, like the methods repaint and revalidate (these methods do not paint but queue a request to paint).
Use the methods invokeLater (request code to be executed in event-dispatching thread) and invokeAndWait (waits for code to execute).
Have a look at this http://www.cafeaulait.org/books/javaio/ioexamples/
|
Two types of streams:
Character (char type / 16 bits) streams: Reader and Writer abstract classes Byte streams (int type / 8 bits), descendants of InputStream and OutputStream |
|||||||
int read() --> returns one by, -1 for EOF |
Input Streams | |||||||
write(int) --> write byte |
Output Streams | |||||||
void close() |
Should close after use | |||||||
InputStreamReader inputReader; |
Basic reading from the standard input channel. Some other encoding options are US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16 | |||||||
|
Class File (or class FileDescriptor) File streams: FileReader, FileWriter, FileInputStream, FileOutputStream For random access files, see [1] page 12-16 The file can be a directory too; see listing with listFiles() |
|||||||
|
try-with-resources statement ensures that the file is closed even in the case of an error |
|||||||
import java.io.*; |
Example |
|
|
java.net.URL.getDocumentBase() --> URL of current page |
|
java.net.URL.getImage(URL, filename) --> Image |
|
Server | Client | |
---|---|---|
|
import java.net.*; ; |
|
ServerSocket serverSocket; |
Register with service | |
Socket socket; |
Socket | Socket socket; |
OutputStream sOut; |
Streams | InputStream sIn; |
sOut = socket.getOutputStream(); |
Output and input stream | sIn = socket.getInputStream(); |
dataOut.close(); |
Close stream | dataIn.close(); |
socket.close();
|
Close socket | socket.close(); |
|
Formats are SHORT, MEDIUM, LONG, FULL The method format defines how to display the date. For parsing, see below. |
import java.text.DateFormat;
|
|
import java.text.DateFormat;
|
GG = era yyyy, M, MM, MMM, MMMM, d, dd h, hh, a (H, HH for 24 hr format), m, mm, s, ss, SSS (millisec) EEE, EEEE (day in week), D, DDD (day in year), w (week in year), z (timezone) '...' : literal text |
|
First step: install the driver. |
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
|
Load the driver |
String url = "jdbc:odbc:ODBC-data-source-name";
|
Establish the connection |
Statement stmt = c.createStatement();
|
Create update statement n is number of rows affected |
Statement stmt = c.createStatement();
|
getString can be used with all data types getByte, getShort, getInt, getLong |
PreparedStatement pStmt = c.prepareStatement(
"... WHERE A=?;"); |
Prepared statements, precompiled by DBMS |
c.setAutoCommit(false);
|
Transactions Evetually use setTransactionIsolation() method
|
c.setAutoCommit(false);
|
Rollback in catch, itself with another try/catch |
CallableStatement cs = c.prepareCall("{call PROC_NAME}");
|
Stored procedures using a callable statement. Use parameters are for prepared statements. |
SQLWarning warning = stmt.getWarnings(); |
SQLWarning is a sub-class of SQLException |
Working minimal example. It uses the default ODBC driver (windows). A data source "PRDT" should be defined.It assumes that a user SCOTT exists.
import java.sql.*; |
|
Compile Must have .java extension. |
|
Classes must be in files called class_name.class. |
javadoc |
Creates packages.html, tree.html, AllNames.html and classname.html |
appletviewer [-debug] urls | url must be an html document with <applet> tag |
jdb [options] | Debugger |
System.out.println ("...."); |
|
... = Integer.parseInt ( string expr ); |
Convert a literal string to integer |
Math.random() |
Random from 0 to 1 |
Math.sqrt(number) |
Square root |
Packages: lower.case Class, interface: NounsWithInitialUpperCase Methods: verbsWithMixedCaseExceptFirstLetter Variables: withMixedCaseExceptFirstLetter (like methods) Constants: ALL_UPPER_CASE |
Conventions |
... main ( String[] args) { |
Command line arguments: args[0] is first argument |
|
Passing parameters with an applet Null if empty. Not case sensitive. |
Generally one public class per .java file. Generally should contain in the following order:
// comments or whitespaces only
package what.ever; // package definition
// imports
// class and interface definitions
public class AclassThe class in the above file will be put in ${CLASSPATH}/what/ever/Aclass.class
The -d option of javac should refer to the same directory as CLASSPATH
The URLEncoder.encode() function works only for Java default encoding.
String unreserved = new String("/\\- _.!~*'()
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789");
StringBuffer out = new StringBuffer(url.length());
for (int i = 0; i < url.length(); i++)
{
int c = (int) url.charAt(i);
if (unreserved.indexOf(c) != -1) {
if (c == ' ') c = '+';
out.append((char)c);
continue;
}
byte [] ba;
try {
ba = url.substring(i, i+1).getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
ba = url.getBytes();
}
for (int j=0; j < ba.length; j++)
{
out.append("%" + Long.toHexString((long)(ba[j]&0xff)).toUpperCase());
}
}
String encodedUrl = out.toString();
(source Oracle)
Use executable in the bin directory:
native2ascii -encoding UTF-8 file1 > file2
Then run:
sed 's/[[:cntrl:]]//g' file2 > file3
Sources: