8/3/2019 All Java
1/21
JAVA
SDK files :
docs JDK documentation in html
bin Java compiler and tools
demo Sample Java programs
include files for native methods
lib library files
src source files for some of java
Class
Think of this a blueprint for an object. There is no object unless you create it. It contains methods and
data.
Methods
Methods are functions that are only defined in classes. Java uses a strong object oriented approach.
Data
Arrays, numbers, other objects,
If you have a class called Molecule, then to create an instance of a Molecule, then you would do:
Molecule oxygen = new Molecule();
now you can do something with the object oxygen
If your class Molecule has data named mass, then you could find the mass of your new molecule
via the dot notation:
oxygen.mass
If your Molecule class has a move method, then you can move your molecule via:
oxygen.move()
The parentheses are a strong reminder that move is a method not data.
8/3/2019 All Java
2/21
8/3/2019 All Java
3/21
8/3/2019 All Java
4/21
8/3/2019 All Java
5/21
// this is a comment, use lots of these
/* this is a
comment too */
/** this is used for documentation (javadoc) */
8/3/2019 All Java
6/21
VS.
8/3/2019 All Java
7/21
import javax.swing.JOptionPane; // this gives us some classes we can use
// for GUI's// javax.swing is a package
// JOptionPane is a class
// read in a number as a string, this method returns a string when it is called
stringnum1 = JOptionPane.showInputDialog(" Enter Pi ");
// convert number in string form to a floating point number
num1 = Double.parseDouble( stringnum1 );
JOptionPane.showMessageDialog( null, Amazing ! You are correct ! ");
JOptionPane.showMessageDialog( null, "Your Pi is wrong by : " + error + " Percent \n" +
"Pi is " + Math.PI );
8/3/2019 All Java
8/21
Java Data Types
Integers (bytes):
long (8), int (4), short (2), and byte (1)
these DO NOT depend on machine you are using!
Floating point (bytes):
double (8) and float (4)
Roughly 14 and 7 significant digits
float will use less memory and might run faster on 32-bit processors
Characters
char
Unicode (65,536) not ASCII (255)
single quotes are used
Boolean
false or true
Type Conversion
int x = (int)Math.PI;
int y = 5;
double z = (double)y;
int a = 3;
double b = 4.5;
double c;
c = a * b;
Operators
+ - * / ++ -- %
If x=12, then
x++ gives 13
a = 2 * x++ (a will be 24, x will be 13)
b = 2 * ++x (b will be 26, x will be 13)
The operator ++ is where C++ gets its name. Some people
joke that it should be ++C (we dont really want to use the
language until it is improved !). Some people say Java is
really ++C.
Relational: == >=
8/3/2019 All Java
9/21
Compiling vs. Interpretted
Usually java is run in interpretted mode, ie:
javac MyCode.java
java MyCode
The above is running the .class byte code
But you can also compile java into native machine code,
which should run much faster.
For example, there is the gcj compiler from gnu
Another good Java compiler is jikes from IBM
OTHER JAVA KEYWORDS
instanceof: A Java programming language keyword that takes two object references as
arguments and returns true if the type of its first argument is assignable to its second argument.
If ( apple instanceof Fruit ) {
System.out.println( apple is a fruit.);
Assert
It has two forms:
1st
:
assert Expression1 ;
where Expression1 is a boolean expression. When the system runs the assertion, it
evaluates Expression1 and if it is false throws an AssertionError with no detail
message.
2nd:
The second form of the assertion statement is:
assert Expression1 : Expression2 ;
where:
* Expression1 is a boolean expression.
8/3/2019 All Java
10/21
* Expression2 is an expression that has a value
transient
transient variables are always skipped when objects are serialized. an object is serialized when
you write all its data to a file. If you have data that would make no sense to have serialized,
then you can denote them as transient
volatile
The volatile keyword is used on variables that may be modified simultaneously by other threads.
This warns the compiler to fetch them fresh each time, rather than caching them in registers.
native
A java keyword that denotes a method implemented on the native system in another language.
Chapman Packages:
1. Io
FileIn: A convenience class to read numeric data from a formatted input file.
FileInLines: A convenience class to read lines of strings from a formatted input file.
FileOut: A class to write formatted numeric data or lines of strings to a formatted output file
StdIn: A class to read numeric data from the standard input stream.
StdinLines: A class to read lines of data from the standard input sream.
Fmt: A class to write formatted data to either standard output stream or a string.
2. Math1
Array: A class to do various array manipulations.
Complex: A class to do complex arithmetics.
Math1: A class that has math methods that are not included in the standard java package.
SigProc: A class to perform various signal processing functions
Statistics: A class to calculate statistics of a data set.
3. Graphics
Hist: A class to create a histogram of a set of data using the awt gui.
Jhist: A class to create a histogram of a set of data using the swing gui.
JCanvas: A class to create a blank swing (canvas) to draw graphics on.
Plot2d: A class to create line and bar plots using the awt gui.
Jplot2d: A class to create line and bar plots using the swing gui.
8/3/2019 All Java
11/21
Applet (NOT JAVA 2.0)
import java.awt.Graphics;
public class HelloWorld1 extends java.applet.Applet {
public void paint (Graphics g) {g.drawString("Hello World ! This is not Java 2.0", 10, 20);
}
}
Applet (JAVA 2.0)
import javax.swing.*;
import java.awt.Graphics;
public class HelloWorld6 extends JApplet {
public void paint (Graphics g) {
g.drawString("Hello World ! This IS Java 2.0", 10, 20);
}
}
JAVA selection structures:
Single: If
Double: If/else
Multiple: switch
JAVA repetition structures:
While
Do/while
For
NAMED BREAK
8/3/2019 All Java
12/21
SWITCH
8/3/2019 All Java
13/21
Arrays
8/3/2019 All Java
14/21
Multiple Dimension Arrays
int X[]; x = new int [10];int x[][]; x = new int [10][12];
int x[][][]; x = new int [10][20][10];
int b[][] = { { 1, 2, 3}, { 4, 6, 8}, { 9, 12, 10} }; 3 rows with 3 columns
b.length gives number of rows
b[1].length gives columns in 1st
row.
And so on..
Existing methods:
-Application: main,run
-Applets: init,start,stop,paint,destroy
Recursion: Methods can call themselves
8/3/2019 All Java
15/21
Eg:
public int fact ( int n ) {
if ( n >= 1 ) return n * fact(n-1);
else return 1;
}
Method Overloading:
Write a method twice, the only diff is that each has different variable type.
You can now call the method square and pass it an int or a double and it will use the correct
version of the method. It will not work if you pass it a float.
8/3/2019 All Java
16/21
Object Oriented Programming (OOP)
OOP encapsulates data (e.g. numbers and
objects) and methods (functions)
Information hiding is a key aspect of OOP
Implementation details are hidden from the
user (we can drive a car without knowing
how it is built)
C is action oriented (verbs)
Java is object oriented (nouns)
C++ can be in between....
OOP
Ket aspects of OOP are:
Encapsulation
Inheritance
Polymorphism
Classes are templates for objects
Benefits of OOP
Modifiability
Readability
Maintainability
Reliability
Reusability
Encapsulation
The grouping together of data and methods
(they are both encapsulated into objects)
This makes code more portable and
maintainable and ...
Also offers data hiding. Some data and
methods can be private
Constructors
Methods with the same name as the class
are constructors
-Constructors cannot return a value
Inheritance
Inheritance permits software reusability
New classes can be created from old classes
The data and methods of the old class are available to the new class
8/3/2019 All Java
17/21
Differences
Polymorphism
An objects ability to decide what method to apply to itself, depending on where it is in the
inheritance heirarchy, is usually called polymorphism.
OR
(while the message may be the same, objects may respond differently )
Benefits of polymorphism
Polymorphism allows you to avoid very complicated switch or if/else constructs that are
required in other languages to treat special cases
The same method name can be used in many different ways by different objects, this is
especially interesting for inherited objects
Like method overloading
Exception handling
An exception tells you that a problem occurred during your programs execution.
Eg. file not found, out of memory problem, URL not found
Try Catch
8/3/2019 All Java
18/21
try {
java code....
}
catch ( AnExceptionType except1)
{
exception handling code...
}
finally
{
java code...
}
Thread methods:
interrupt
interrupted (static)
isInterrupted
isAlive
yield
setName
getName
toString
currentThread (static)
join
setPriority ( int )
getPriority
Thread uses:
e.g. graphics, GUIs, robotics
AWT
Abstract windowing toolkit
Two principal types of graphics objects are:
Components and Containers
KEY GUI PIECES
JFrame: a window
JPanel: a piece of a window
JLabel: uneditable text
JTextField: a box that gets text from the keyboard
JButton: an area that triggers on mouse clicks
JCheckBox: an area that is either on or off
8/3/2019 All Java
19/21
JComboBox: a drop-down list of items
JList: a list of items is shown, the user can select more than one or double click on them.
abstractA Java keyword used in a class definition to specify that a class is not to be instantiated, but rather inheritedby other classes. An abstract class can have abstract methods that are not implemented in the abstractclass, but in subclasses.
booleanRefers to an expression or variable that can have only a true or false value. The Java programming
language provides the boolean type and the literal values true and false.break
A Java keyword used to resume program execution at the statement immediately following the currentstatement. If followed by a label, the program resumes execution at the labeled statement.
byteA sequence of eight bits. Java provides a corresponding byte type.
caseA Java keyword that defines a group of statements to begin executing if a value specified matches the valuedefined by a preceding switch keyword.
catchA Java keyword used to declare a block of statements to be executed in the event that a Java exception, orrun time error, occurs in a preceding try block.
charA Java keyword used to declare a variable of type character.
classIn the Java programming language, a type that defines the implementation of a particular kind of object. Aclass definition defines instance and class variables and methods, as well as specifying the interfaces theclass implements and the immediate superclass of the class. If the superclass is not explicitly specified, thesuperclass will implicitly be Object.
continueA Java keyword used to resume program execution at the end of the current loop. If followed by alabel, continue resumes execution where the label occurs.
defaultA Java keyword optionally used after all case conditions in a switch statement. If all case conditions are
not matched by the value of the switch variable, the default keyword will be executed.
doA Java keyword used to declare a loop that will iterate a block of statements. The loop's exit condition canbe specified with the while keyword.
double
A Java keyword used to define a variable of type double.else
A Java keyword used to execute a block of statements in the case that the test condition with the if keywordevaluates to false.
extendsClass X extends class Y to add functionality, either by adding fields or methods to class Y, or by overridingmethods of class Y. An interface extends another interface by adding methods. Class X is said to be asubclass of class Y. See also derived from.
final
8/3/2019 All Java
20/21
A Java keyword. You define an entity once and cannot change it or derive from it later. More specifically: afinal class cannot be subclassed, a final method cannot be overridden and a final variable cannot changefrom its initialized value.
finallyA Java keyword that executes a block of statements regardless of whether a Java Exception, or run timeerror, occurred in a block defined previously by the try keyword.
float
A Java keyword used to define a floating point number variable.forA Java keyword used to declare a loop that reiterates statements. The programmer can specify thestatements to be executed, exit conditions, and initialization variables for the loop.
ifA Java keyword used to conduct a conditional test and execute a block of statements if the test evaluates totrue.
implementsA Java keyword included in the class declaration to specify any interfaces that are implemented by thecurrent class.
importA Java keyword used at the beginning of a source file that can specify classes or entire packages to bereferred to later without including their package names in the reference.
instanceofA two-argument Java keyword that tests whether the runtime type of its first argument is assignment
compatible with its second argument.int
A Java keyword used to define a variable of type integer.interface
A Java keyword used to define a collection of method definitions and constant values. It can later beimplemented by classes that define this interface with the "implements" keyword.
longA Java keyword used to define a variable of type long.
nativeA Java keyword that is used in method declarations to specify that the method is not implemented in thesame Java source file, but rather in another language.
newA Java keyword used to create an instance of a class.
nullThe null type has one value, the null reference, represented by the literal null, which is formed from ASCII
characters. A null literal is always of the null type.package
A group of types. Packages are declared with the package keyword.private
A Java keyword used in a method or variable declaration. It signifies that the method or variable can only beaccessed by other elements of its class.
protectedA Java keyword used in a method or variable declaration. It signifies that the method or variable can only beaccessed by elements residing in its class, subclasses, or classes in the same package.
publicA Java keyword used in a method or variable declaration. It signifies that the method or variable can beaccessed by elements residing in other classes.
returnA Java keyword used to finish the execution of a method. It can be followed by a value required by themethod definition.
shortA Java keyword used to define a variable of type short.
staticA Java keyword used to define a variable as a class variable. Classes maintain one copy of class variablesregardless of how many instances exist of that class. static can also be used to define a method as a classmethod. Class methods are invoked by the class instead of a specific instance, and can only operate onclass variables.
superA Java keyword used to access members of a class inherited by the class in which it appears.
switch
8/3/2019 All Java
21/21
A Java keyword used to evaluate a variable that can later be matched with a value specified bythe case keyword in order to execute a group of statements.
synchronizedA keyword in the Java programming language that, when applied to a method or code block, guaranteesthat at most one thread at a time executes that code.
thisA Java keyword that can be used to represent an instance of the class in which it appears. this can be used
to access class variables and methods.throwA Java keyword that allows the user to throw an exception or any class that implements the "throwable"interface.
throwsA Java keyword used in method declarations that specify which exceptions are not handled within themethod but rather passed to the next higher level of the program.
transientA keyword in the Java programming language that indicates that a field is not part of the serialized form ofan object. When an object is serialized, the values of its transient fields are not included in the serialrepresentation, while the values of its non-transient fields are included.
tryA Java keyword that defines a block of statements that may throw a Java language exception. If anexception is thrown, an optional catch block can handle specific exceptions thrown within the try block. Also,an optional finally block will be executed regardless of whether an exception is thrown or not.
voidA Java keyword used in method declarations to specify that the method does not return any value. void canalso be used as a nonfunctional statement.
volatileA Java keyword used in variable declarations that specifies that the variable is modified asynchronously byconcurrently running threads.
whileA Java keyword used to declare a loop that iterates a block of statements. The loop's exit condition isspecified as part of the while statement.