SlideShare uma empresa Scribd logo
1 de 279
JAVA For Mainframers
BY RICH HELTON
July 2015
Benefits of Java
 Java provided a common framework as part of the language to
handle strings, networks, and extended functions.
 Java also handles its own garbage collection and cleanup.
 Java also can be cross-platform, depending on the frameworks
used, and code, to run on Linux, zOS, Windows and even Android.
 Java also provided Object Oriented Programming where the
framework and pieces were used as objects to abstract the details.
 The various pieces of objects could be combined into new
combinations, normally known as design patterns, to produce new
functionality.
 In the next slide, we will show what a Java program looks like, but it
is a just a glimpse, and this class will walk you through it.
My First Java Program…Java already
public class MyFirstJavaProgram {
// Start the program
public static void main(String[] args){
if(args.length >0){ // If argument print name
String myName = (String) args[0];
System.out.println("Hello " +myName);
}else{ // Else print
System.out.println("Hello there");
}
}
}
What is a JRE?
 To run a Java program, all that is needed is the Java Runtime
Environment (JRE).
 The JRE comes with the command line environment to compile
and run Java programs.
 To develop a Java program, a Java Development Kit (JDK) is used,
which is an extension of the JRE with additional Java Archive
(JAR) files for development.
 JAR files are additional classes and libraries to extend programs.
There are JAR files for network programming, web programming,
and much, much more. The JAR files are zipped up classes, which
are compiled Java programs.
 The JRE, which is the Standard Edition, can be downloaded from
http://www.oracle.com/technetwork/java/javase/downloads/index.html
.
To set up the JRE
 After downloading and installing the JRE program, we need to
ensure that the JRE is in the Path fo windows to be run.
 See
http://stackoverflow.com/questions/1672281/environment-variables-for-j
To set up the JRE
To set up the JRE
To set up the JRE
To set up the JRE
To set up the JRE
Seeing it at the command prompt…
 At the command prompt, notice the Java extension, we will walk
through all of the program as time progresses, the Java program :
Find the compiler…
 At the command prompt, check to make sure that the JDK is set for
compiling :
 At the command prompt, the JDK is set in the environment for
compiling :
Compile…
 At the command prompt, run the java compiler “javac”:
Run the program…
 At the command prompt, run the java program without the
argument, “java” runs the program:
Developing your environment
 Java can be compiled and ran from the command line as long as the
paths for JRE and JDK are set correctly.
 Java developers have multiple ways to develop Java code, there are
Integrated Development Environments (IDE), such as Eclipse and
NetBeans, and there are txt editors, such as UltraEdit, Jedit, Geany,
and more.
 An article describing the difference can be found at
http://java.about.com/od/gettingstarted/a/ideversuseditor.htm .
 An IDE will assist heavily in providing many tools to develop in, to
multiple frameworks to provide an extensive development
environment, the drawbacks is that the production environment
may be set up differently without some of these tools.
 A text editor will allow you edit the code directly out of the
environment, but you may have to memorize more Java syntax and
framework syntax’s.
Text Editors
 Text Editors do not normally offer code completion, in which you
can type in part of a word and it will complete it.
 However, you can edit Java code directly from an environment and
restart it quickly. Sometimes, a mixture of both text editor and
IDE’s are used.
 A good article on text editors fro Java programmers can be found at
http://stackoverflow.com/questions/3716482/what-text-editor-for-a-java-
Online compilers
 There are also Java online compilers to test small amounts of code,
such as http://ideone.com/ .
IDE’s
 A list of the best Java IDE’s can be found at
http://faq.programmerworld.net/programming/best-java-ide-review.html
. We can see in Eclipse as it gives code suggestions:
LET’S BREAK DOWN
THE PROGRAM
Java syntax
The first piece to understand is the Java syntax, which are the rules
for defining a Java program, see
https://en.wikipedia.org/wiki/Java_syntax
We will start with the basics;
Identifiers
Literals
Comments
Code Blocks
Keywords
Identifiers
Identifiers
Identifiers are the names of code elements in Java, which could name
of variables, methods, classes, packages and interfaces.
There are many naming rules normally used in Java;
A name cannot start with a digit or $, or be a reserved word.
No spaces can be used in the name.
Java is case-sensitive.
Normally classes start with a uppercase letter and define an object.
class FileReader{
Methods are verbs that start in lowercase letters.
void readFile ( ){
Variables are nouns that start in lowercase letters.
File tempFile = new File ….
See http://www.cwu.edu/~gellenbe/javastyle/naming.html
Comments
Comments
 Comments are used to communicate the purpose of parts of the
program in the code.
 It is not code that executes.
 Comments are not executed as part of the code and are ignored by
the compiler.
 Using the (//) double slashes will tell the compiler to ignore the
entire line.
 Using the (/*) slash star will start the compiler to ignore the
comment until it meets the ending slash star (*/).
Here are the two types of comments:
// Start the program, single line comment
/* Start the program,
multiple line comment
*/
Variables
Variables
 A variable is a value that can change.
 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
 A variable has a type, name and value.
 The type of the variable will define the criteria that the value must
meet. For example,
int age = 29;
Where the value is an integer of 29, and the name is age.
 Not only does the variable must match a specific type, normally
known as the the “Data Type”, but it must have scope and access.
 The scope of the variable defines where the variable lives in an
application, and the access will define what pieces of the program
can access the variable.
int cadence = 0;
Variable Scope
There are 4 main scopes of a variable:
1)Instance variables – are variables that live and die within a object,
for every object created, new variables are created, living in each new
instance of an object.
2)Class variables -- are static variables within a class, so for very
object created, there is only one variable created for all the objects.
3)Local variables -- are local to a method and are created in the
method call, and are no longer available after the method is
completed.
4)Parameters – are variables passed into methods, to be used by the
method as arguments.
int cadence = 0;
Naming
Naming a variable:
Are case-sensitive. Name is not name.
Cannot have white-spaces or special characters.
But can contain digits or underscores after letters, but cannot start
with digits.
Cannot match a Java keyword or reserved work.
Some valid examples, int is a keyword that we will discuss later:
int max_age =50;
int age2 = 50;
int cadence = 0;
Blocks
Statements
 A statement is roughly equivalent to a sentence in natural
languages.
 A statement forms a complete unit of execution followed by a semi-
colon.
 A statement is line for a singe unit of work.
 A line in Java is ended with ( ; ) semicolon.
 See
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.htm
Statement examples
ment aValue = 8933.234; // increment statement aValue++; // method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myB
Blocks
 A block is a group of zero or more statements between balanced
braces and can be used anywhere a single statement is allowed.
 A block is started with the ( { ) opening brace and ends with the ( } )
closing brace.
 Blocks are groups of individual statements.
Blocks -samples
public class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
Sample Block
Methods
Main method
 Every Java program must have a “main” method.
 There is only one “main” method in every Java file, but there can be
multiple Java files per project or JAR.
 Each Java program with a main, is enclosed with a public class
name that is the same name used as the filename.
 The “main” method is where the program starts it’s execution, and
the closing brace ( } ) of the “main” method is where the program
will end.
Main method
 In this example, we have a program called BlockDemo in a file
called BlockDemo.java.
 The names must match as the “public class BlockDemo”.
 The main method must be of the form “public static main(String[]
args)” in which we will cover the elements as keywords and later.
Main method args
 T he args parameters is a String array that contains any command-line
arguments used to run the application.
 See http://java.about.com/od/m/g/mainmethod.htm
The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application.
The args parameter is a String array that contains any command-line arguments used to run the application
Main method args example
import java.util.Arrays;
public class PrintArguments {
public static void main(String[] args) {
String commandlineArgs = Arrays.toString(args);
// The Arrays.toString function encases the Strings
// in the array with square brackets.
if (commandlineArgs.equals("[]")) {
System.out.println("There were no arguments.");
} else {
System.out.println("There command-line arguments
were: "
+ commandlineArgs + ".");
}
}
}
The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application.
The args parameter is a String array that contains any command-line arguments used to run the application
Example output
The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application.
The args parameter is a String array that contains any command-line arguments used to run the application
Continuing
We could go on about methods, classes and variables, but it will do
little good without knowing the keywords.
We will dive deeper into what we have learned so far after learning the
basic keywords for the Java syntax,
int cadence = 0;
Keywords
Keywords
Are words used in the Java language to develop in as part of the Java
syntax,
We will cover keywords later as well in other sections.
Sometimes keywords may be referred to as reserved words, reserved
words are words reserved by the Java language, keywords are words
reserved by the Java language to use as development. A variable has a
type, name and value. So all keywords are reserved words.
Keywords make up the Java language, so many people memorize
them when developing.
Knowing the keywords is the basis of all Java programming, the rest
is structure of the code, scope of the execution, and extending basic
features. So knowing the keywords provide the keys for knowing Java.
A good reference to start with is
http://www.dummies.com/how-to/content/java-keywords.html
int cadence = 0;
Keywords
int cadence = 0;
Keywords
Primitive data types
Primitive Data Types
 We will start with the keywords that are the 8 primitive data types.
As the name implies, these are the most basic data types used to
store values.
 A reference for the 8 primitive types can be found at
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
 A variable has a type, name and value.
 The type of the variable will define the criteria that the value must
meet. For example,
int age = 29;
Where the value is an integer of 29, and the name is age.
int cadence = 0;
Primitive Data Types
int cadence = 0;
Primitive Data Types
int cadence = 0;
Primitive Data Types Example
public class PrimitiveDataTypesExample {
public static void main(String[] args) {
// declaring primitive data types: 8 types
int intNumber = 1000000000;
short shortNumber = 32767;
long longNumber = 1000000000;
float floatNumber = 100.03244f;
double doubleNumber = 100000.33432;
char oneCharacter = 'A';
boolean flag = true;
byte byteNumber = 127;
// displaying primitive data types results
System.out.println("integer number is: " + intNumber);
System.out.println("short number is: " + shortNumber);
System.out.println("long number is: " + longNumber);
System.out.println("float number is: " + floatNumber);
System.out.println("double number is: " + doubleNumber);
System.out.println("charcter is: " + oneCharacter);
System.out.println("boolean flag is: " + flag);
System.out.println("byte is: " + byteNumber);}}
int cadence = 0;
Program output
integer number is: 1000000000
short number is: 32767
long number is: 1000000000
float number is: 100.03244
double number is: 100000.33432
charcter is: A
boolean flag is: true
byte is: 127
int cadence = 0;
Primitive Data Types
The 8 primitive types are :
We will start with the keywords that are the 8 primitive data types.
As the name implies, these are the most basic data types used to store
values.
A reference for the 8 primitive types can be found at
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
A variable has a type, name and value.
The type of the variable will define the criteria that the value must
meet. For example,
int age = 29;
Where the value is an integer of 29, and the name is age.
The int is the integer primitive data type.
int cadence = 0;
Primitive Wrapper Classes
The 8 primitive types have supporting classes for more features, such
as parsing :
See https://en.wikipedia.org/wiki/Primitive_wrapper_class
int cadence = 0;
Wrapping example code
public class WrappingUnwrapping {
public static void main(String args[]) {
// data types
byte grade = 2;
int marks = 50;
float price = 8.6f;
double rate = 50.5;
// data types to objects -- wrapping
Byte g1 = new Byte(grade);
Integer m1 = new Integer(marks);
Float f1 = new Float(price);
Double r1 = new Double(rate);
// let us print the values from objects
System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object g1: " + g1);
System.out.println("Integer object m1: " + m1);
System.out.println("Float object f1: " + f1);
System.out.println("Double object r1: " + r1);
int cadence = 0;
Wrapping example code
// objects to data types (retrieving data types from objects)
byte bv = g1.byteValue(); // unwrapping
int iv = m1.intValue();
float fv = f1.floatValue();
double dv = r1.doubleValue();
// let us print the values from data types
System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
}
}
int cadence = 0;
Output
Values of Wrapper objects (printing as objects)
Byte object g1: 2
Integer object m1: 50
Float object f1: 8.6
Double object r1: 50.5
Unwrapped values (printing as data types)
byte value, bv: 2
int value, iv: 50
float value, fv: 8.6
double value, dv: 50.5
int cadence = 0;
Keywords
Conditionals and loops
Next, we will approach conditionals and loops
int cadence = 0;
Conditional and loops
Conditional Statements and loops use some of he same logic inside
methods,
An if-else conditional statement will check a condition and if the
condition matches, it will execute a block of code.
A loop, be it for, do-while, or while will continually execute a block
of code while the condition is met.
int cadence = 0;
If - else
The if-else conditional statements will look for the true or false, also it
can be considered as a 1 or 0, to follow the statement if true, and skip
if false.
See http://www.wikijava.org/wiki/If_else_statements
int cadence = 0;
If – else example
public class IfElseDemo {
public static void main(String[] args) {
// set the grade
int testscore = 76;
char grade;
if (testscore >= 90) { // is 90 or above
grade = 'A';
} else if (testscore >= 80) { // is 80 or above
grade = 'B';
} else if (testscore >= 70) { // is 70 or above
grade = 'C';
} else if (testscore >= 60) { // is 60 or above
grade = 'D';
} else { // if none of the above
grade = 'F';
}
System.out.println("Grade = " + grade);}}
int cadence = 0;
If – else example output
Grade = C
int cadence = 0;
Switch statement
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
int cadence = 0;
Switch statement
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);}}
OUTPUT
August
int cadence = 0;
Switch statement example
Using too many if-else conditionals can become unreadable.
The switch establishes many if-else’s to be put into a block of code
where it checks for constants sequentially.
The switch statement it limited to constants, exact values, as keys.
See https://en.wikipedia.org/wiki/Switch_statement
int cadence = 0;
Loops -- For
The for loop is the most basic of loops,
A loop is like a conditional, except instead of executing only one
statement, it executes the statements a given number of times, or
based on a condition’s change.
See http://www.tutorialspoint.com/java/java_loop_control.htm
int cadence = 0;
For loop syntax
int cadence = 0;
For loop example
public class ForDemo {
public static void main(String args[]) {
for (int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + x);
System.out.print("n");
}
}
}
int cadence = 0;
For loop example output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
int cadence = 0;
Loops – For Each
The for loop has been extended in Java 5 to automatically go through
the number of iterations available.
Iterations and Collections will be addresses in a latter section as this
section is only about the keywords themselves.
int cadence = 0;
Loops – For Each
int cadence = 0;
For Each example
public class ForEachDemo {
public static void main(String args[]) {
int[] numbers = { 10, 20, 30, 40, 50 };
for (int x : numbers) {
System.out.print(x);
System.out.print(",");
}
System.out.print("n");
String[] names = { "James", "Larry", "Tom", "Lacy" };
for (String name : names) {
System.out.print(name);
System.out.print(",");
} } }
OUTPUT
10,20,30,40,50,
James,Larry,Tom,Lacy,
int cadence = 0;
While Loop
The while loop will continually execute its block of code while a
particular condition is true.
See
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
The syntax is as follows:
int cadence = 0;
The while statement continually executes a block of statements while a particular condition is true.
The while statement continually executes a block of statements while a particular condition is true.
While Loop example
public class WhileDemo {
public static void main(String[] args) {
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
OUTPUT
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
int cadence = 0;
The while statement continually executes a block of statements while a particular condition is true.
The while statement continually executes a block of statements while a particular condition is true.
Do-while Loop
The do-while loop, except that it’s expression is evaluated after the
execution instead of before the execution of statements, so that the
statements are executed at least once.
The syntax is as follows:
int cadence = 0;
The while statement continually executes a block of statements while a particular condition is true.
The while statement continually executes a block of statements while a particular condition is true.he Java programming language also provides a do-while statement, which can be expressed as follows:
statement(s) } while (expression);
he difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed
Do-While Loop example
public class DoWhileDemo {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
OUTPUT
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
int cadence = 0;
The while statement continually executes a block of statements while a particular condition is true.
The while statement continually executes a block of statements while a particular condition is true.
Break and continue
The break statement is used to break out of loop.
The continue statement skips the rest of the statements in the
current iteration of the loop.
int cadence = 0;
Continue and Break example
public class ContinueBreakDemo {
public static void main(String[] args) {
System.out.println("starting loop:");
for (int n = 0; n < 7; ++n) {
System.out.println("in loop: " + n);
if (n == 2) {
continue;
}
System.out.println(" survived first guard");
if (n == 4) {
break;
}
System.out.println(" survived second guard");
// continue at head of loop
}
// break out of loop
System.out.println("end of loop or exit via break");
}
}
int cadence = 0;
Continue and Break output
starting loop:
in loop: 0
survived first guard
survived second guard
in loop: 1
survived first guard
survived second guard
in loop: 2
in loop: 3
survived first guard
survived second guard
in loop: 4
survived first guard
end of loop or exit via break
int cadence = 0;
We will discuss the modifiers next
int cadence = 0;
Keywords
Exception handling
Exception Handling
Exception Handling is handling anything that happens abnormally in
the program. Normally a program may operate fine, but when a file
that is needed is removed, or memory is too low, something needs to
be done to compensate for normal operation.
When the program tries to account for the abnormal condition, it is
called “Exception Handling”.
See https://en.wikipedia.org/wiki/Exception_handling
int cadence = 0;
Exception Handling keywords
int cadence = 0;
The try keyword
 The first step in constructing an exception handler is to enclosed
the code that might throw an exception with the try block.
 This is to check to see if the code will try to throw the exception
enclosed in a block of code.
 See http://
docs.oracle.com/javase/tutorial/essential/exceptions/try.html
 The syntax will look like the following:
int cadence = 0;
The catch keyword
 When a program will try to look for an exception, it can either
catch the exception or try to re-throw the exception.
 The exception is a object containing all of the stack trace,
message information, and other parts that tell what happened. It is
like a wrapper to an abend in other languages.
 See http://
docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
 The syntax will look like the following:
int cadence = 0;
The try-catch example
import java.io.*;
import org.apache.commons.io.FileUtils;
public class TryCatchDemo {
public static void main(String[] args) throws IOException {
try {
// constructor may throw FileNotFoundException
String contents = FileUtils.readFileToString(new
File("somefile.txt"));
System.out.println("--- File End ---");
} catch (FileNotFoundException ex1) {
//Create the file since it didn't exist
System.out.println(ex1.getMessage());
File f=new File("somefile.txt");
f.createNewFile();
}
}
}
int cadence = 0;
The try-catch example output
File 'somefile.txt' does not exist
Please note that the file was created because it didn’t exist.
int cadence = 0;
The finally keyword
The finally block always executes when the try bock exists.
This includes rather a catch block is called or even exists.
A catch block does not have to exist with a try block.
The finally block is used to close files, and any other cleanup that
needs to occur, just in case a catch block is called.
See http://
docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The finally example
public class TryCatchFinallyDemo {
public static void main(String[] args) throws IOException {
FileReader reader = null;
try {
reader = new FileReader("someFile.txt");
int i = 0;
while (i != -1) {
i = reader.read();
System.out.println((char) i);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
System.out.println("--- File End ---"); } } }
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The finally example -output
someFile.txt (The system cannot find the file specified)
--- File End ---
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The throw keyword
 We were able to catch the exception, because another program or
library threw the exception with the throw keyword.
 Because the file was not found, in a previous example, the file
library created a throw object to send to our catch block.
 We will cover more in later sections if it seems complicated.
 See http://
docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
int cadence = 0;
The throw example
public class ThrowDemo {
public static void main(String[] args) throws IOException
{
try {
File f = new File("somefile.txt");
if(!f.exists()) // if file doesn't exist
throw new
FileNotFoundException("Richs' file not found");
System.out.println("--- File End ---");
} catch (FileNotFoundException ex1) {
System.out.println(ex1.getMessage());
}
}
}
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The throw example-output
Richs' file not found
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The throws keyword
The throws keyword is used at the method’s signature, and must be
declared when the method itself does not catch the specific exception.
In our examples, we have seen this with “throws IOException” as it
could be caught from the try, but we were not catch’ing it:
int cadence = 0;
The throws example
public class ThrowsDemo {
public static void main(String[] args) throws
FileNotFoundException {
try {
File f = new File("somefile.txt");
if(!f.exists()) // if file doesn't exist
throw new FileNotFoundException("Richs' file
not found");
} finally {
System.out.println("--- File End ---");
}
}
}
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
The throws example -output
Exception in thread "main" --- File End ---
java.io.FileNotFoundException: Richs' file not found
at ThrowsDemo.main(ThrowsDemo.java:10)
int cadence = 0;
p in constructing an exception handler is to enclose the code that might throw an exception w
Keywords
Modifiers
Modifiers
 There are many types of modifiers in Java.
 There are class modifiers that modify the behavior of Java classes.
 There are method modifiers that modify the behavior of Java
methods.
 There a variable modifiers that modify the behavior of Java
variables.
 Of these modifiers, there are access modifiers that modify the
access to classes, methods and variables.
 There are non-access modifiers that change the behavior of these
elements, but not the level of access.
Keywords
Access Modifiers
Access Modifiers
 Access modifiers define what level of visibility and access that a
class, method or variable to other classes and methods.
 This piece will be further explained in the section that discusses
Object-Oriented Design (OOD) with examples, this section is just to
provide a definition of the keywords themselves.
 There are 4 access levels for these keywords:
Access Modifiers
Public, Protected and Private
 When the “public” access modifier, or keyword, is placed in front of
classes or methods, it gives all other pieces of the program access to
the method or classes.
 When the “protected” access modifier, or keyword, is placed in
front of classes or methods, it gives the child class access to that
class or method but no one else.
 When the “private” access modifier, or keyword, is placed in front
of classes or methods , it means that no other class may have access
to that class or method.
 If no access modifier is defined, the default is used, which states
that it can be used in the same class and package.
A simple table to see the access modifier
Keywords
Non-Access Modifiers
Non-Access Modifiers
 There are many types of modifiers in Java.
 There are class modifiers that modify the behavior of Java classes.
 There are method modifiers that modify the behavior of Java
methods.
 There a variable modifiers that modify the behavior of Java
variables.
 Of these modifiers, there are non-access modifiers that modify the
lifetime behavior of classes, methods and variables.
 See http://javabeginnerstutorial.com/core-java-tutorial/non-
access-modifiers-in-java/
Non-Access Modifiers
Modifiers
Modifiers are in classes, variables and
methods
Class Modifiers
 Non-Access Modifiers will define the behavior of classes.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/reflect/class/classModifiers.html
abstract types
 An abstract class can have abstract methods. It is a class that
contains abstract methods, but the class can be declared abstract
without abstract methods.
 Abstract methods contain the signature of the method, the
declaration that a subclass must use, but not the body. The body is
defined in the subclass.
 As a reference, please see
https://en.wikipedia.org/wiki/Abstract_type and
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
abstract example
//abstract class
abstract class Sum{
//abstract methods
public abstract int SumOfTwo(int n1, int n2);
public abstract int SumOfThree(int n1, int n2, int n3);
//Regular method
public void disp(){
System.out.println("Method of class Sum");
}
}
class AbstractDemo extends Sum{
public int SumOfTwo(int num1, int num2){
return num1+num2;
}
public int SumOfThree(int num1, int num2, int num3){
return num1+num2+num3;
}
public static void main(String args[]){
AbstractDemo obj = new AbstractDemo();
System.out.println(obj.SumOfTwo(3, 7));
System.out.println(obj.SumOfThree(4, 3, 19));
obj.disp();}}
abstract example - output
10
26
Method of class Sum
final types
 final – declares a a variable cannot be changed, a class cannot be
extended, or a method cannot be overwritten. It cannot change. As
a reference, please see
https://en.wikipedia.org/wiki/Final_%28Java%29
 The final class can be inherited, as well as the method, and the
variable re-used, however, the class, method and variable cannot be
changed, meaning that it cannot be overwritten. See
http://javarevisited.blogspot.com/2011/12/final-variable-method-class-jav
Final variable example
public class FinalVariableExample {
public static void main(String[] args) {
/*
* Final variables can be declared using final keyword. Once created
and
* initialized, its value can not be changed.
*/
final int hoursInDay = 24;
// This statement will not compile. Value can't be changed.
// hoursInDay=12;
System.out.println("Hours in 5 days = " + hoursInDay * 5);
}
}
}
OUTPUT
Hours in 5 days = 120
static type
 static – declares that methods and variables belong to a class and
not of an instance, meaning that there is only one variable or
method for all the objects of that class to use. It is different than
final, as final cannot be changed, but a static variable can be
changed, but there only one instance, and not multiple instances.
 As a reference, please see
https://en.wikibooks.org/wiki/Java_Programming/Keywords/static
static variable example
public class StaticDemo {
static int count = 0;
public void increment() {
count++;
}
public static void main(String args[]) {
// Multiple objects, but only one count
StaticDemo obj1 = new StaticDemo();
StaticDemo obj2 = new StaticDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is=" + obj1.count);
System.out.println("Obj2: count is=" + obj2.count);
}
}
OUTPUT
Obj1: count is=2
Obj2: count is=2
transient type
 transient – declares that specific variables should not be
serialized when variables are serialized.
 For instance, an object can be saved into a file or database, the
transient keyword tells the program not save the variable.
 As a reference, please see
https://en.wikibooks.org/wiki/Java_Programming/Keywords#transient
native type
 native – declares an implementation coming from a native
programming language such as C.
 This is only used if programming using native methods used in the
Java Native Interface.
 As a reference, please see
https://en.wikibooks.org/wiki/Java_Programming/Keywords/native
strictfp type
 strictfp – used to restrict the precision and rounding of floating
point calculations to ensure portability.
 As a reference, please see
http://www.javatpoint.com/strictfp-keyword
synchronized type
 synchronized – used to declare a method or code block to be
thread safe, only allowing one thread to access the code at a time.
 This is used when creating mult-threaded java programs.
 As a reference, please see
https://en.wikipedia.org/wiki/Java_concurrency
volatile type
 Used to declare that a variable can be changed in different threads
or when serialized.
 This is the opposite of synchronized when creating Java multi-
threaded programs.
 As a reference, please see
http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example
and http://javamex.com/tutorials/synchronization_volatile.shtml
Keywords
Class Declaration and
reference
Class keywords
There are still many keywords used in the declaration and references
of classes. These are non-modifiers, as they are used to reference the
object or declare a new one without any modifications to the existing
one. Most of this will be covered in more detail in the OOD portion of
the class.
class – declares a class type.
extends – is a class that will extend a parent or abstract.
implements – declares that a class will implement a interface,
which is a class that declares how is class it be formed without any of
the implementation.
import– declares what functionality from other classes can be
imported into the current classes in the file.
instanceof -- tests to see whether a certain object comes from a
certain class.
int cadence = 0;
On more keywords
 interface – declares a class to contain the rules, methods and
variables, for other classes to implement, without actually
implementing the pieces itself.
 new – creates a new object from a class.
 package – declares, in the first line of code in a class file, that this
class file will now be declared to be part of a package of code, a
package name is normally the reverse of a company URL, such as
“com.cdle.Parser”.
 super – used to access methods and variables of the parent object.
 this –used to access methods and variables of the current object.
int cadence = 0;
Class keywords
int cadence = 0;
Package and import
 The package is the first line declared in a Java file, if used.
 The package is a means to group Java programs to avoid conflicts
with other Java programs.
 For example, I could have 2 programs that create files with the
createfile(File) function. So which one do we call.
 The package identifier is used to identify which package that the
file was created in, and import function is used to identify which
package to retrieve the function from.
 See
http://javaworkshop.sourceforge.net/chapter3.html#What+is+a+
Package%3F
int cadence = 0;
Package and import
 The package declaration will be in the first line, and now the file
must be stored in the “com.coworkforce” subdirectory to create a
path for the package of Java files will be stored:
int cadence = 0;
Package and import
 If we want to import, or get the functionality from the
ThisDemo.java file, we have to import the file from its package
area:
int cadence = 0;
class
 The Java class will declare a class which will be covered in ythe
OOD piece of the course.
 A class is the blueprints of an object. It defines it.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/java/concepts/class.html
new
 The Java new keyword will create the instance of a class.
 The class is the definition of the object, the new is the declaration
of the class into an instance of an object.
 Again, it will be covered again in greater depth later. This is just to
familiarize oneself with the keywords.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreatio
n.html
Class example
public class ArrayObjDemo {
public static void main(String args[]) {
System.out.println("Hello, World!");
// step1 : first create array of 10 elements that holds object
// addresses.
Emp[] employees = new Emp[10];
// step2 : now create objects in a loop.
for (int i = 0; i < employees.length; i++) {
employees[i] = new Emp(i + 1);// this will call constructor.
}
}
}
class Emp {
int eno;
public Emp(int no) {
eno = no;
System.out.println("emp constructor called..eno is.." + eno);
}
}
Class example
What we just did was create 10 objects of an Emp class in the following
output, new was used to create the 10 objects, of the only one class called
Emp:
Hello, World!
emp constructor called..eno is..1
emp constructor called..eno is..2
emp constructor called..eno is..3
emp constructor called..eno is..4
emp constructor called..eno is..5
emp constructor called..eno is..6
emp constructor called..eno is..7
emp constructor called..eno is..8
emp constructor called..eno is..9
emp constructor called..eno is..10
this
 The this object reference is used to access methods and variables of
the current object.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
This example
package com.coworkforce;
public class ThisDemo {
int id;
String name;
public ThisDemo(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
ThisDemo s1 = new ThisDemo(111, "Karan");
ThisDemo s2 = new ThisDemo(222, "Aryan");
s1.display();
s2.display();
}}
This example --output
In the “this” example, we simply attached the variable to the current
variable of the same name in the current object using:
this.id = id;
this.name = name;
We can see the output as:
111 Karan
222 Aryan
Super object reference type
 The super keyword is used to access methods and variables of the
parent object.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
super example
class Vehicle {
Vehicle() {
System.out.println("Vehicle is created");
}
}
class Bike extends Vehicle {
Bike() {
super();// will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]) {
Bike b = new Bike();
}
}
super example --output
The super keyword will invoke the Vehicle constructor.
We can see the output as:
Vehicle is created
Bike is created
instanceof
 The instanceof keyword will return true if an object was created
from a specific class.
 It checks if an object reference is an instance of a type, and returns
a boolean value
 As a reference, please see
https://en.wikibooks.org/wiki/Java_Programming/Keywords/inst
anceof
instanceof example
extends
 The extends keyword will extend a parent class into a subclass, or
child class.
 The extends can only be used once in the declaration, so a child
class has only one parent, thus why super( ) will call the one and
only parent.
 As a reference, please see
https://en.wikibooks.org/wiki/Java_Programming/Keywords/inst
anceof
extends example
class Parent {
int x;
void setIt (int n) { x=n;}
void increase () { x=x+1;}
void triple () {x=x*3;};
int returnIt () {return x;}
}
extends example
interface and implement type
 The interface keyword declares that a class is not a concrete class,
but an interface.
 An interface is similar to an abstract class, except that all methods
are not defined, but are used as declarations that must be
implements.
 The implement keyword will declare that the class must
implement the interface functionality.
 As a reference, please see
http://docs.oracle.com/javase/tutorial/java/concepts/interface.ht
ml and https://en.wikipedia.org/wiki/Interface_%28Java%29
interface example
interface IntExample {
public void sayHello();
}
/*
* Classes are extended while interfaces are
implemented. To implement an
* interface use implements keyword. IMPORTANT : A class
can extend only one
* other class, while it can implement n number of
interfaces.
*/
public class InterfaceDemo implements IntExample {
/*
* We have to define the method declared in implemented
interface, or else
* we have to declare the implementing class as abstract
class.
*/
interface example
interface IntExample {
public void sayHello();
}
public class InterfaceDemo implements IntExample {
public void sayHello() {
System.out.println("Hello Visitor !");
}
public static void main(String args[]) {
// create object of the class
InterfaceDemo demo = new InterfaceDemo();
// invoke sayHello(), declared in IntExample interface,
but defined in
// InterfaceDemo.
demo.sayHello();
}
} Output is “Hello Visitor !”
extends example
Keywords
What’s Left,
Assert and Enum
More keywords
We have not yet covered the keywords that we have used in the main
method, such as void and return.
void – designates that a method will not return a value.
return – designates the return values from the method.
We have also not covered the assert keyword.
assert – tests that a condition is true/false, and if false throws an
exception.
We have also not covered the enum keyword.
return – designates the return values from the method.
int cadence = 0;
More keywords
int cadence = 0;
Assert
 The assert keyword tests that a condition is true/false, and if false
throws an exception.
 It must be ran with the “-ea” argument to use the assert function.
 See https://en.wikipedia.org/wiki/Assertion_
%28software_development%29
int cadence = 0;
Assert example
public class AssertDemo {
public static void main(String args[]) {
boolean assertTest = true;
assert assertTest;
assertTest = false;
assert assertTest;
}
}
int cadence = 0;
enum
 An enum type is a special data type that enables for a variable to
be a set of predefined constants.
 See
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
int cadence = 0;
enum example
public class EnumDemo {
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Day day;
public EnumDemo(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;}}
int cadence = 0;
enum example
public static void main(String[] args) {
EnumDemo firstDay = new EnumDemo(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumDemo thirdDay = new EnumDemo(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumDemo fifthDay = new EnumDemo(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumDemo sixthDay = new EnumDemo(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumDemo seventhDay = new EnumDemo(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
The OUTPUT:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
int cadence = 0;
void and return
 In many cases, a value has to be returned from a function using
the return statement, if no value is to be returned, then we must
use the void statement on the method.
 See
http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.h
tml
int cadence = 0;
Return example
public class ReturnDemo {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if (t)
return; // return to caller
System.out.println("This won't execute.");
}
}
The OUTPUT:
Before the return.
int cadence = 0;
Keyword conclusion
Knowing the Java keywords provides the keys for knowing Java,.
There are more areas to cover to truly know Java, Object-Oriented
Design (OOD), Operations on variables, Arrays, Collections, more on
exception handling and loops. However, these are all extensions on
what has been covered.
Know the previous slides, and with further details, the rest of the
chapters will reference the keywords.
int cadence = 0;
Operators
Operators
 Operators are special symbols that perform specific operations on
one, two, or three operands, and then return a result.
 See
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operator
s.html and
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsum
mary.html
 We have been using the equal operator all along:
int age = 50;
Operators
Arithmetic operators
Perform arithmetic functions:
Arithmetic operators example
public class ArithmeticOperatorDemo {
// Demonstrate the basic arithmetic operators.
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int i = 1 + 1;
int n = i * 3;
int m = n / 4;
int p = m - i;
int q = -p;
System.out.println("i = " + i);
System.out.println("n = " + n);
System.out.println("m = " + m);
System.out.println("p = " + p);
System.out.println("q = " + q);
Arithmetic operators example
// arithmetic using doubles
System.out.println("nFloating Point Arithmetic");
double a = 1 + 1;
double b = a * 3;
double c = b / 4;
double d = c - a;
double e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}
Arithmetic operators example - output
Integer Arithmetic
i = 2
n = 6
m = 1
p = -1
q = 1
Floating Point Arithmetic
a = 2.0
b = 6.0
c = 1.5
d = -0.5
e = 0.5
Unary operators
Unary means that there is only one operand, functions:
Unary example
public class UnaryDemo {
public static void main(String[] args) {
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}
Unary example -- output
1
0
1
-1
false
true
Bitwise operators
Bitwise operators change the bits inside a number:
Bitwise operators example
public class BitwiseDemo {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c);
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c);
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c);
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c);
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c);
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c);
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c);}}
Bitwise operators example - output
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
Conditional Operators
Conditional operators are used to evaluate a condition that is applied
to one or two boolean expressions:
Conditional operators example
public class ConditionalDemo {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
int c = 20;
int d = 21;
int max;
System.out.println("a && b = " + (a && b));
System.out.println("a || b = " + (a || b));
System.out.println("!(a && b) = " + !(a && b));
if (c > d) {
max = c;
}
else {
max = d;
}
System.out.println("max with if = " + max);
max = (c > d) ? c : d;
System.out.println("max with ternary = " + max);}}
Conditional operators example - output
a && b = false
a || b = true
!(a && b) = true
max with if = 21
max with ternary = 21
Equality and Relational Operators
Will test the relationship and equality from one operand to another:
Equality operators example
public class EqualityDemo {
public static void main(String[] args) {
int x = 5;
int y = 10;
if (x == y)
System.out.println("value of x is equal to the value of y");
if (x != y)
System.out.println("value of x is not equal to the value of y");
if (x > y)
System.out.println("value of x is greater then the value of y");
if (x < y)
System.out.println("value of x is less then the value of y");
if (x >= y)
System.out
.println("value of x is greater then or equal to the value of y");
if (x <= y)
System.out
.println("value of x is less then or equal to the value of y");
}
}
Equality operators example - output
value of x is not equal to the value of y
value of x is less then the value of y
value of x is less then or equal to the value of y
Assignment operators
A BRIEF INTRODUCTION
INTO OBJECT ORIENTED
PROGRAMMING (OOP)
A brief introduction to OOP
 Learning Object Oriented Programming is as easy as PIE.
 PIE stands for Polymorphism, Inheritance and Encapsulation.
 These PIE characteristics provide common properties like re-use of
pieces, hiding of internal data, and propagating characteristics of
objects into other objects.
 Don’t think that these code pieces are static in nature because the
Business Objects can morph into new types of Business Objects as
long as their constructs are defined.
 Using this fluid style of programming, relational tables can be
defined and created by simply defining the initial Business Object.
 These concepts are expanded to create morphing viruses where a
virus changes itself every time it hits a new machine so that it is a
completely different characteristics after multiple propagations.
Polymorphism
 Polymorphism started a term in biology for how different types of
species have the same generic traits.
 It states that the same species may morph, having different
qualities, in the same habitat.
 For instance, the lady bug may morph into red spots or black spots
in the same environment.
 The commonality is that the two bugs are still lady bugs, but have
different traits like spot colors.
 Even though it has different spot colors, it is still lady bug, and flies
like a lady bug, eats like a lady bug and does what lady bugs do.
 When it no longer does the things a lady bug does, it is a different
bug. That is when the bug morphs outside its common species
definition.
Polymorphism
 In OOP, polymorphism is the ability of different objects, that are
created by the same generic class, or traits, to be used the same
across the same generic interface but still have different, or
morphed, properties.
 Let’s use an example, if we have a “Toyota” truck and “Ford” truck
created with it’s parent class “Truck”.
Polymorphism, continuing…
 Now, let’s create a program called “Midas Touch” that handles the
Truck objects and rotates their tires.
class public MidasTouch{
Truck myTruck = new (Truck) Toyota ();
}
 The program “Midas Touch” can rotate the tires, regardless if it is a
Toyota or Ford Truck object. The factory “Midas Touch” works with
trucks but doesn’t have a preference over what type of truck it
works on. Even though the Toyota or Ford Truck might have some
different techniques for rotating tires, the factory will accept and
work on any Truck object.
… rotateTires(myTruck);
Overriding methods
Method overriding is a term in OOD that means that a child’s method
will over write the parents method, both methods being exact in
signature, method name, parameters and return type.
See https://en.wikipedia.org/wiki/Method_overriding
Overloading methods
Method overloading is a term in OOD that means that a child’s
method will be used over the parents when the child’s method
signature does change.
See https://en.wikipedia.org/wiki/Function_overloading
Inheritance
 Inheritance has to do more with genealogy and parentage.
 This concept is to understand an objects behavior and traits by its
inherited lineage.
 A “child” class has a “parent” class that gave it many default
properties. In Java only one parent.
 For example, my parents gave me “brown hair” because they had
brown hair, so I, the “child” class inherited my hair color from my
“parent” class.
 However, after being executed in the program, the program may
change the hair color of the “child” class if the protection of the
class allows it. For example, if I am indifferent to my hair color in
real life, I could dye it if someone prompted me, but regardless, my
hair started out brown and may return to its brown state.
Inheritance
 In the picture:
 The Toyota and Ford are derived, or child classes, from their parent
“Truck”
 Because the “Toyota” object and “Ford” object inherited properties
from its parent, we know that some traits are given to the child
classes when they are created.
 These Truck parent may have passed on to Toyota and Ford that
they had an engine, 4 tires, a windshield, gas tank, brakes, etc.
Inheritance, continuing…
 Now, let’s use create a class from the parent class.
class public Truck {
Brakes myBrakes;
Engine myEngine;
Windsheild myWindSheild;
}
class public Toyota extends Truck{
// Already has myBrakes, myEngine, myWindsheild defined.
}

Encapsulation
 Encapsulation is also referred to as data hiding or information
hiding.
 Even though you may see the business object and its methods, you
may not call or manipulate the inside data directly, or at all, unless
you call a specific method.
 Many objects may use a constructor to pass information into the
object that it cannot retrieve without using a “getter( )” method.
 For example, I could create a “Ford Truck” object, and it will have
many properties like color, bed type, bin number, etc.
 It will also have embedded objects like tires, windshields, radio,
seats, etc.
 In order to get data from the “Ford Truck” object, I need to call an
getter method that it shows me like “getTirePressure( )” to return
an integer of 35 for 35 psi.
Putting it all together
OOP introduced a new way of developing programs.
See http://www.westga.edu/~bquest/1997/object.html
Some of the benefits are:
Better mapping of the problem domain, can treat objects as cars, car
services, etc.
Faster development as pieces can be modularized, farmed out
separately and re-used.
Modular Architecture and design, to assign some pieces for
frameworks, other architects and other groups to develop.
2nd
Java Sample Program with an object
 Let’s create an class from the first program, and call it MyFirstObject:
public class MyFirstObject{
private String myName; //Must go through function to change
MyFirstObject(){// Constructor
myName = "there";
}
//Setter
public void setName(String myName){
this.myName = myName;
}
//Getter
public String getName(){
return this.myName;
}
}
Some new terms
 There are various terms that this program will add to our
vocabulary, there are “setters”, functions that set variables, and
“getters”, functions that get variables.
 The Constructor is the method used to create the object. There
could be multiple constructors, taking in different arguments as
they “overload” their methods.
 Overloading is when a method with the same name, but a different
argument, is called based in it’s argument.
 Also, introduced is the “this” pointer, or keyword, used in Java
reflection.
 “this” allows an object to look into the current instance of itself.
 In other words, when the class becomes a object, I has state,
variables, methods and information about itself, by using “this”, the
class can manipulate its current data.
2nd
Java Program object creation
 In the code, there must always be one and only one “main” method
that starts the execution.
 The “main” method is static, which means that it is the only one.
The execution of the program will load objects, and the “new”
keyword will create our first object, “myObj”, from the
“MyFirstObject” class.
 After the “myObj” is created, we set the name if there is one passed
through the argument, otherwise, it will return the default name
“there”.
Note: Even if a Constructor is not defined in code, a default one is
always defined by the compiler. The “new” keyword must call a
constructor to create an object from a class.
2nd
Java Program object creation
 Always remember that an object is never created, or instantiated,
unless the “new” keyword is used. Let’s create the object:
public class MySecondJavaProgram {
public static void main(String[] args){
MyFirstObject myObj = new MyFirstObject();
if(args.length >0){ // If argument print name
myObj.setName(args[0]);
}
System.out.println("Hello " + myObj.getName());
} // End Main
}
What happened
 From this program, “MySecondJavaProgram”, we were able to
create an object with the “new” keyword.
 The object didn’t add much functionality than the first program,
however, we can use the object across many programs, and start
creating a framework of libraries.
 A main purpose of OOP is reusability.
 Another concept is also cleaner code construction. Because of the
movement of the functionality of the program into a separate
object, the code becomes compartmentalized.
Extending functionality
 Let’s extend the functionality of the first object, with the “extend” keyword, and
create a child class:
class MySecondObject extends MyFirstObject{
String myComment;
// Constructor
MySecondObject(){
myComment = "No Argument";
}
//Setter
void setComment(String myComment){
this.myComment = myComment;
}
//Getter
String getComment(){
return this.myComment;
}
}
Extending functionality
 The program will create 2 objects now, the child object
“MySecondObject” will create a “MyFirstObject” when created and use
it’s functionality:
public class MyThirdJavaProgram {
public static void main(String[] args){
MySecondObject myObj = new MySecondObject();
if(args.length >0){ // If argument print name
// From parent
myObj.setName(args[0]);
// From child
myObj.setComment("Argument found");
}
System.out.println("Hello " + myObj.getName());
} // End Main
}
Extending functionality
 By extending functionality in a new object, I was able to add
methods and variables without changing the initial code and how it
works.
 This becomes monumental when creating frameworks because now
libraries can be extended without changing original functionality.
 A new concept that can be introduced here is called “Overrriding”.
 Overriding methods occurs when the method of the child class is
used instead of the parent.
 Since the parent, or super class, had a “setName” method, and the
child did not, the parent’s method was used.
 The child could “override” the parent’s “setName” method by
simply having its own.
SUPER
 So far, we have discussed that when a child object is created, the
parent object is also created and the child inherits their attributes.
 The child object can also get data directly from their parent class
using the “super” keyword. Here’s an example where the child
object can get the “myName” information directly from their
parent:
//Print the name
void printName(){
System.out.println("MyFirstObject's name " +
super.myName);
}
Reflection
 The “this” keyword has been briefly discussed. It is an important
concept for an object to look at itself in introspection and examine
what type of object it is, what state it is in, its current variables, and
even its current properties. It is examining its own metadata.
 Reflection comes in handy when serializing objects (saving to disk)
and writing the objects variables and methods into XML.
 The Simple API for XML (SAX) parser using reflection to develop
its data definitions and types.
Let’s start the code:
import java.lang.reflect.*;
public class Reflection1{
public static void main(String[] args) {
WhoAmI whoami = new WhoAmI();
whoami.WhoAreYou(); } }
Reflection (finding my fields/methods)
class WhoAmI{
String test1 ="I think";
String test2 = "Therefore I am";
void CanYouSeeMe(){}
void WhoAreYou(){
System.out.println("WhoAmI:" +this.getClass().getName());
Method [] methods = this.getClass().getDeclaredMethods();
Field [] fields = this.getClass().getDeclaredFields();
for(int i =0; i < methods.length;i++)
System.out.println("Method:" +methods[i].getName());
for(int i =0; i < fields.length;i++)
System.out.println("Field:" +fields[i].getName());
}
Reflection
 The code produced its fields and methods.
 After collecting this information, it could easily be placed on the
network, through XML or serialized to show what is available.
 The output:
WhoAmI:WhoAmI
Method:WhoAreYou
Method:CanYouSeeMe
Field:test1
Field:test2
Abstract (Must Do)
 Not only can a child inherit from their parent, but a child can also
be told the interface that they must produce.
 This technique is an “interface” which is basically a parent that can
“Do as I say and not as I do”.
 Here’s an example interface that will force the child class to create
the “setName” and “getName” methods:
interface MustDo{
public abstract void setComment(String myComment);
abstract String getComment();
}
class MySecondObject extends MyFirstObject implements MustDo{
 The second object will inherit from the first, but it “has to” create
the functionality of the “MustDo” class.
Final (Don’t Change)
 In some instances of programming, a constant class, method or
variable needs to be defined.
 These are variables that do not change once they are set.
 A class and method can be declared that a child class can not over
write or perform overriding.
 One example of a variable used in this way:
final boolean DEBUG = false;
 In this example, a developer may want a “DEBUG” variable that will
be used in the class to decide to perform debug traces or not. In
this case you want to force the variable to not be changeable.
 During the instance of an object, the static variable can also be
added to only allow the creation of the globally:
static final boolean DEBUG = false;
Import
 The theme of Java has been abstraction, re-use, and frameworks.
 It becomes a daunting task that there are so many frameworks to
chose from and many are free.
 By default, the “import” keyword is used to pull in other objects and
packages into the file. For instance, the “import java.io.*;”
statement at the top of the file will give scope to all classes in that
the Java IO framework.
 Pulling in the entire package does create some overhead on what is
being exactly used and what is not, so a more precise definition of
the package being used can be given in this example as the “Java IO
File” class being referenced by “import java.io.File;”
JAR
 There are many frameworks, usually called packages, that come
standard with Java.
 These frameworks evolve to the Java standard over time.
 For instance, the Java Cryptography Extensions (JCE) used to be
Java Specification Request (JSR) 27 for some time. This is the
framework for encrypting data with Triple-DES, RSA, and multiple
algorithms.
 During this period, a programmer who wanted to use the JCE.JAR
had to download it separately. The package now comes with the
J2SE.
 The Java Archive (JAR ) file can be used by the program if both the
file is associated through a “classpath” and its associated “import”
is included.
 The “classpath” is a property of the program that contains the paths
of all classes.
JAR Example
Java Properties
 The program can determine it’s current environmental propeerties
by using “System.getProperty()” and set them by
“System.setProperty();”.
 Here’s some sample code:
public class JavaProperty {
public static void main(String[] args) {
System.out.println("Classpath:" + System.getProperty("java.class.path"));
System.out.println("Java Version:" + System.getProperty("java.version"));
System.out.println("Java Home:" + System.getProperty("java.home"));
System.out.println("Operating System:" + System.getProperty("os.name"));
System.out.println("User's Home:" + System.getProperty("user.home"));
System.setProperty("user.home", "C:Documents and Settings");
System.out.println("User's Home:" + System.getProperty("user.home"));
}
}
Java Properties
 Notice that the “user.home” was changed by the program:
Java Version:1.6.0_07
Java Home:C:Program FilesJavajre1.6.0_07
Operating System:Windows XP
User's Home:C:Documents and Settingsqnwa08
User's Home:C:Documents and Settings
Packages
 As we discussed the “import” keyword, it is important to note that
this statement defines the class and directory hierarchy in the JAR
or file structure. See the JAR picture.
 For instance, the JAR has the class “Cipher.class” file in the
“javax/crypto/” subdirectory. The import statement will say
“import javax.crypto.Cipher” on the calling file.
 Part of the import statement tells which subdirectory to find the file
starting from the JAR or classpath.
 Subsequently, the file had to define this path and subsequent
“import” statement by using the “package” keyword:
package javax.crypto;
public class Cipher { }
 This is very important when creating packages or your own
frameworks and to organize them in a directory structure.
Strings
Strings
 Strings are Java data objects that contain a sequence of
characters.
 The java platform provides the String class to create and
manipulate Strings.
 See http://docs.oracle.com/javase/tutorial/java/data/strings.html
 Creating Strings:
String greeting = “Hello World”;
String greeting = "Hello world!";
String methods
String greeting = "Hello world!";
Split example
public class StringSplitDemo {
public static void main(String a[]) {
String str = "This program splits a string based on
space";
String[] tokens = str.split(" ");
for (String s : tokens) {
System.out.println(s);
}
str = "This program splits a string based on
space";
tokens = str.split("s+");
}
}
String greeting = "Hello world!";
Split example -output
This
program
splits
a
string
based
on
space
String greeting = "Hello world!";
Compare example
public class CompareString {
public static void main(String[] args) {
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
/* compare two strings, case sensitive */
System.out.println( str.compareTo(anotherString) );
/* compare two strings, ignores character case */
System.out.println( str.compareToIgnoreCase(anotherStr
ing) );
/* compare string with object */
System.out.println(str.equals(objStr) );}}
OUTPUT
-32
0
true
String greeting = "Hello world!";
Concat example
public class ConcatDemo {
public static void main(String args[]) {
/*
* String concatenation can be done in several ways in
Java.
*/
String str1 = "Hello";
String str2 = " World";
// 1. Using + operator
String str3 = str1 + str2;
System.out.println("String concat using + operator : " +
str3);
String greeting = "Hello world!";
Concat example
/*
* Internally str1 + str 2 statement would be executed
as, new
* StringBuffer().append(str1).append(str2)
*
* String concatenation using + operator is not
recommended for large
* number of concatenation as the performance is not
good.
*/
// 2. Using String.concat() method
String str4 = str1.concat(str2);
System.out
.println("String concat using String concat method : " +
str4);
String greeting = "Hello world!";
Concat example
// 3. Using StringBuffer.append method
String str5 = new
StringBuffer().append(str1).append(str2).toString();
System.out.println("String concat using StringBuffer
append method : "
+ str5);
}
}
OUTPUT
String concat using + operator : Hello World
String concat using String concat method : Hello World
String concat using StringBuffer append method : Hello
World
String greeting = "Hello world!";
String Array To List example
import java.util.*;
public class StringArrayToListDemo {
public static void main(String args[]) {
// create String array
String[] numbers = new String[] { "one", "two", "three" };
/*
* To covert String array to java.util.List object, use List
* asList(String[] strArray) method of Arrays class.
*/
List list = (List) Arrays.asList(numbers);
// display elements of List
System.out.println("String array converted to List");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
String greeting = "Hello world!";
String Array To List example
}
/*
* Please note that list object created this way can not
be modified.
* Any attempt to call add or delete method would throw
* UnsupportedOperationException exception.
*
* If you want modifiable list object, then use
*
* ArrayList list = (ArrayList) Arrays.asList(numbers);
*/
/* Alternate Method to covert String array to List */
List anotherList = new ArrayList();
Collections.addAll(anotherList, numbers);
}
}
String greeting = "Hello world!";
String Array To List example -output
OUTPUT
String array converted to List
one
two
three
String greeting = "Hello world!";
Arrays
Arrays
 An array is a container object that holds a fixed number of values of
a single type.
 See
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.h
tml
Array example 1
import java.util.Arrays;
public class ArrayDemo2 {
public static void main(String[] args) throws Exception
{
int[] ary = { 1, 2, 3, 4, 5, 6 };
int[] ary1 = { 1, 2, 3, 4, 5, 6 };
int[] ary2 = { 1, 2, 3, 4 };
System.out.println("Is array 1 equal to array 2?? "
+ Arrays.equals(ary, ary1));
System.out.println("Is array 1 equal to array 3?? "
+ Arrays.equals(ary, ary2));}}
OUTPUT:
Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false
Array example 2
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayMergeDemo {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));}}
OUTPUT:
[A, E, I, O, U]
Array to List example
Collections
Collections
 Java collections are a set of frameworks for handling a collection of
objects and data types.
 By collection, it is a set, map, stack, queue and lists, that will
manage a group of types and objects.
 See https://en.wikipedia.org/wiki/Java_collections_framework
Choosing a Collection
 See
http://javamex.com/tutorials/collections/how_to_choose.shtml
Linked Lists
The problem with arrays is that they are created to a fix size. Linked
Lists are a Java collections that are meant to compensate for some of
the array limitations.
Linked Lists are data elements that are linked to each other and can
be used as a single list of elements.
See https://en.wikipedia.org/wiki/Linked_list
With a link list, we can add a data element into a list, remove it,
change position, and more.
Linked Lists Example
import java.util.LinkedList;
public class LinkedListDemo1 {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new
LinkedList<String>();
/*add(String Element) is used for adding
* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");
Linked Lists Example
/*Display Linked List Content*/
System.out.println("Linked List Content: "
+linkedlist);
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after
addition: " +linkedlist);
/*This is how to get and set Values*/
Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update
by set method: " +firstvar2);
Linked Lists Example
/*Remove first and last element*/
linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of
first and last element: " +linkedlist);
/* Add to a Position and remove from a
position*/
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: "
+linkedlist); }}
Linked Lists Example - output
/*Remove first and last element*/
linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of
first and last element: " +linkedlist);
/* Add to a Position and remove from a
position*/
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: "
+linkedlist); }}
Sets
The problem with linked lists is that they can have duplicate elements
added, for sets, not duplicate elements can be added, and no order in
which they are stored.
See
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.ht
ml
Set Example
import java.util.*;
public class TreeSetDemo {
public static void main(String[] args) {
// Set example with implement TreeSet
Set<String> s = new TreeSet<String>();
s.add("b");
s.add("a");
s.add("d");
s.add("c");
java.util.Iterator<String> it = s.iterator();
while (it.hasNext()) {
String value = (String) it.next();
System.out.println("Value :" + value);
}}}
Set Example -output
Value :a
Value :b
Value :c
Value :d
Maps
A map has a key and value, a key can be duplicated,
Each can only contain one value.
See
http://docs.oracle.com/javase/tutorial/collections/interfaces/map.ht
ml
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
Map Example
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> mp = new
HashMap<Integer,String>();
mp.put(new Integer(2), "Two");
mp.put(new Integer(1), "One");
mp.put(new Integer(3), "Three");
mp.put(new Integer(4), "Four");
Set<?> st = mp.entrySet();
Iterator<?> it = st.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
int key = (Integer) m.getKey();
String value = (String) m.getValue();
System.out.println("Key :" + key + "
Value :" + value);
}}}
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
Map Example -- output
Key :1 Value :One
Key :2 Value :Two
Key :3 Value :Three
Key :4 Value :Four
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
Similar to HashMaps are HashTables
HashTables also use a key-value pair like HashMaps, except some
differences given:
HashTable Example
import java.util.Enumeration;
import java.util.Hashtable;
public class HashtableDemo1 {
public static void main(String[] args) {
Hashtable<String, String> ht = new
Hashtable<String, String>();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration<String> e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());}}}
OUTPUT
3
2
1
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
Queues
Queues are to put data elements into a particular order, normally
First-In-First-Out (FIFO). There is no key needed.
See https://en.wikipedia.org/wiki/Queue_%28abstract_data_type
%29
Queue Example
import java.util.*;
public class QueueDemo1 {
private static Queue <String> queue;
public static void main(String[] args) {
queue = new PriorityQueue<String>();
queue.add("One");
queue.add("Two");
queue.add("Three");
Iterator<String> iterator = queue.iterator();
while(iterator.hasNext()){
String element = (String) iterator.next();
System.out.println(element);}}}
OUTPUT
One
Two
Three
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
Javabeans
JavaBeans
JavaBeans are classes that encapsulate many objects into a single
object (the bean). They are serializable, have a zero-argument
constructor, and allow access to properties using getter and setter
methods.
The name "Bean" was given to encompass this standard, which aims
to create reusable software components for Java.
See https://en.wikipedia.org/wiki/JavaBeans
JavaBean Example
public class JavabeanDemo implements
java.io.Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public JavabeanDemo() {
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
JavaBean Example
public String getName() {
return name;
}
public static void main(String args[]) {
JavabeanDemo e = new JavabeanDemo();// object is created
e.setName("JavaBean");// setting value to the object
System.out.println(e.getName());
}
}
OUTPUT
JavaBean
INPUT/OUTPUT (I/O)
Basic I/O
Basic I/O is a necessity in Java as Java is dependent on files and
directory structure.
The purpose of this section is to show the student some of the power
of Java when copying files and reading the directory structure.
See http://docs.oracle.com/javase/tutorial/essential/io/index.html
Strings
 A String is an immutable object that contains an array of bytes or
characters.
 By immutable, it is meant that you cannot modify the String object.
You can create new Strings from the object, and when a substring
or the String is modified, it is actually creating a new String()
object.
 A Sample String, “test” is created and then re-created again with a
different sequence of characters:
String test = "You cannot change";
test = test.toLowerCase();
System.out.println(test);
StringBuffer
 Re-creating objects can add a lot of overhead to a program. Every
time that a program is created, the program allocates the methods
and variables of that object in memory.
 A simpler method is to use the “StringBuffer” class.
 The “StringBuffer” class allows its contents to be modified without
creating a new class.
 Notice in the following that I did not have to create a new object,
the output was “egnahc tonnac uoY”:
StringBuffer test = new StringBuffer("You cannot change");
test.reverse();
System.out.println(test);
Strings
 Even though Strings may have some additional overhead, there is a
lot of manipulation that can be done with strings in string
arithmetic, observe some of the following:
String test ="You" + " cannot " + "change me";
int len = "You cannot change me".length();
test = " You ";
test += "cannot ";
test += "change me";
StringTokenizer
 The String class is great for a sequence of characters and the
StringBuffer class is great for appending and inserting the sequence
into the same class but what about tokens.
 Tokens are how humans have the tendency to break characters into
individual words, or tokens.
 The “StringTokenizer”, from the “java.util” package is a utility for
breaking down the words of a sentence. Here’s a snippet
String str = "Java,is,Cool";
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
System.out.print(st.nextToken()+ " ");
The Output is : Java is Cool
Files
 When programming Java, it is very important to understand file
Input/Output (I/O).
 The File class, java.io.File, is used for manipulating the file, while
classes like Scanner and FileInputStream manage the file’s data.
 The programs in Java have dependencies based on he file structure
and works well with manipulation of various files.
 While many languages like Perl and other scripting languages have
many utilities for parsing and Regex, Java’s strength rely in its
cross-platform GUI’s and data manipulation with the use of buffers
and files.
 Java, especially JEE, relies heavily on object serialization for when
an object is saved to file or a database. And is heavily dependent on
property files that define how the program is to run.
Create a File
import java.io.*;
public class CreateAFile {
public static void main(String[] argv) throws IOException {
// Ensure that a filename (or something) was given in argv[0]
if (argv.length == 0) {
System.err.println("Usage: CreateAFile filename");
System.exit(1);
}
// If arg is filled then create that file
for (int i = 0; i< argv.length; i++) {
new File(argv[i]).createNewFile( );
}
}
}
List a Directory with class “ls”
 The File class can also be used for directory calls:
// List the Directory "ls"
public class ls {
public static void main(String argh_my_aching_fingers[]) {
String[] dir = new java.io.File(".").list( ); // Get list of names
java.util.Arrays.sort(dir); // Sort it (see Recipe 7.8)
for (int i=0; i<dir.length; i++)
System.out.println(dir[i]); // Print the list
}
}
 Running “ls” will print the directory.
The Path
The directory path defines where files will go on the computer.
Being able to locate
See
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Open a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) {
try{
Scanner text = new Scanner( new File( "Test.txt" ) );
}catch(FileNotFoundException ex){
System.out.println("Error: " +ex.getMessage());
}
}
}
File I/O & Strings
import java.io.IOException;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import static java.nio.file.StandardCopyOption.*;
public class FileStringDemo {
public static void main(String[] args) {
Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd
line");
byte[] data = { 1, 2, 3, 4, 5 };
File I/O & Strings
File I/O & Strings
File I/O & Strings
File I/O & Strings -- output
Regular Expressions
 Regular expressions is the process of matching a pattern in a string.
 For example, the “.” matches any character, so the pattern “.at”
matches can be used to match any three character string ending
with "at", including "hat", "cat", and "bat".
 Regular expressions can also be used with the
“java.util.regex.Matcher” class, the Pattern class or even the string.
 By comparing the patterns in a string, input can be validated to
match proper input.
 See https://docs.oracle.com/javase/tutorial/essential/regex/
 The following code snippet shows how to check a zip string so that
it matches 5 digits, of course this string passes:
String zip = “80120”;
if(zip.matches("d{5}") == false)
System.out.println("Error: zip code");
Regex Example
import java.util.ArrayList;
import java.util.List;
public class ValidateDemo {
public static void main(String[] args) {
List<String> input = new ArrayList<String>();
input.add("123-45-6789");
input.add("9876-5-4321");
input.add("987-65-4321 (attack)");
input.add("987-65-4321 ");
input.add("192-83-7465");
for (String ssn : input) {
if (ssn.matches("^(d{3}-?d{2}-?d{4})$")) {
System.out.println("Found good SSN: " + ssn);}}}}
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: "
+linkedlist); }}
Regex Example -- output
Found good SSN: 123-45-6789
Found good SSN: 192-83-7465
Generics
Generics
Generics all programming to be developed generically for types, while
the types are specified at runtime.
This allows you to use the same code for different types.
See https://en.wikipedia.org/wiki/Generics_in_Java and
http://docs.oracle.com/javase/tutorial/java/generics/why.html
Generic Example
public static void main(String args[]) {
GenericDemo1 type = new GenericDemo1();
type.set("Type Set");
String str = (String) type.get(); // type casting, error
prone and can
// cause ClassCastException
}
}
Generic Example
public static void main(String args[]) {
GenericDemo1 type = new GenericDemo1();
type.set("Type Set");
String str = (String) type.get(); // type casting, error
prone and can
// cause ClassCastException
}
}
Generic Example -- output
Type Set
Design Patterns
Design Patterns
A reusable design, template or recipe to resolve a
repeatable software pattern.
These patterns are an abstract way to describe coding
techniques.
See
http://en.wikipedia.org/wiki/Software_design_pattern
Singleton
There can only be one instance of the object.
Common uses are logging, where a connection is
maintained to log data.
See http://en.wikipedia.org/wiki/Singleton_pattern
Singleton - example
public class Singleton {
private static ClassicSingleton instance;
public static void main(String[] args) {
// Will only retrieve a single instance of the class
setInstance(ClassicSingleton.getInstance());
setInstance(ClassicSingleton.getInstance());
}
public static ClassicSingleton getInstance() {
return instance;
}
Singleton - example
public static void setInstance(ClassicSingleton instance) {
Singleton.instance = instance;
}
}
class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if (instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Singleton - example
public static ClassicSingleton getInstance() {
if (instance == null) {
System.out.println("Create Instance");
instance = new ClassicSingleton();
}
return instance;
}
}
Singleton - example -- output
Create Instance

Mais conteúdo relacionado

Mais procurados

C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalRich Helton
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsSyed Shahul
 
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Hibernate complete notes_by_sekhar_sir_javabynatara_jHibernate complete notes_by_sekhar_sir_javabynatara_j
Hibernate complete notes_by_sekhar_sir_javabynatara_jSatya Johnny
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAjax Experience 2009
 
Spring core module
Spring core moduleSpring core module
Spring core moduleRaj Tomar
 
Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Lars Vogel
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introductionSagar Verma
 
Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4 Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4 Lars Vogel
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierHimel Nag Rana
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...Xamarin
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004Rich Helton
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
 

Mais procurados (20)

Spring aop
Spring aopSpring aop
Spring aop
 
C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 Final
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Hibernate complete notes_by_sekhar_sir_javabynatara_jHibernate complete notes_by_sekhar_sir_javabynatara_j
Hibernate complete notes_by_sekhar_sir_javabynatara_j
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
Apache ant
Apache antApache ant
Apache ant
 
Rest web service
Rest web serviceRest web service
Rest web service
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Spring core module
Spring core moduleSpring core module
Spring core module
 
Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010Eclipse e4 on Java Forum Stuttgart 2010
Eclipse e4 on Java Forum Stuttgart 2010
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
 
Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4 Eclipse 40 and Eclipse e4
Eclipse 40 and Eclipse e4
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 

Semelhante a Java for Mainframers

Semelhante a Java for Mainframers (20)

Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Introduction
IntroductionIntroduction
Introduction
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
Java
JavaJava
Java
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
Java introduction
Java introductionJava introduction
Java introduction
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
JAVA Program Examples
JAVA Program ExamplesJAVA Program Examples
JAVA Program Examples
 
Intro to programing with java-lecture 1
Intro to programing with java-lecture 1Intro to programing with java-lecture 1
Intro to programing with java-lecture 1
 
Java notes
Java notesJava notes
Java notes
 

Mais de Rich Helton

Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.Rich Helton
 
NServicebus WCF Integration 101
NServicebus WCF Integration 101NServicebus WCF Integration 101
NServicebus WCF Integration 101Rich Helton
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed introRich Helton
 
Salesforce Intro
Salesforce IntroSalesforce Intro
Salesforce IntroRich Helton
 
First Steps in Android
First Steps in AndroidFirst Steps in Android
First Steps in AndroidRich Helton
 
Python For Droid
Python For DroidPython For Droid
Python For DroidRich Helton
 
Spring Roo Rev005
Spring Roo Rev005Spring Roo Rev005
Spring Roo Rev005Rich Helton
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Rich Helton
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity FrameworksRich Helton
 
Web Application Firewall intro
Web Application Firewall introWeb Application Firewall intro
Web Application Firewall introRich Helton
 
Java Web Security Class
Java Web Security ClassJava Web Security Class
Java Web Security ClassRich Helton
 

Mais de Rich Helton (14)

Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.
 
NServicebus WCF Integration 101
NServicebus WCF Integration 101NServicebus WCF Integration 101
NServicebus WCF Integration 101
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed intro
 
Salesforce Intro
Salesforce IntroSalesforce Intro
Salesforce Intro
 
First Steps in Android
First Steps in AndroidFirst Steps in Android
First Steps in Android
 
NServiceBus
NServiceBusNServiceBus
NServiceBus
 
Python For Droid
Python For DroidPython For Droid
Python For Droid
 
Spring Roo Rev005
Spring Roo Rev005Spring Roo Rev005
Spring Roo Rev005
 
Python Final
Python FinalPython Final
Python Final
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Jira Rev002
Jira Rev002Jira Rev002
Jira Rev002
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
Web Application Firewall intro
Web Application Firewall introWeb Application Firewall intro
Web Application Firewall intro
 
Java Web Security Class
Java Web Security ClassJava Web Security Class
Java Web Security Class
 

Último

Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 

Último (20)

Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 

Java for Mainframers

  • 1. JAVA For Mainframers BY RICH HELTON July 2015
  • 2. Benefits of Java  Java provided a common framework as part of the language to handle strings, networks, and extended functions.  Java also handles its own garbage collection and cleanup.  Java also can be cross-platform, depending on the frameworks used, and code, to run on Linux, zOS, Windows and even Android.  Java also provided Object Oriented Programming where the framework and pieces were used as objects to abstract the details.  The various pieces of objects could be combined into new combinations, normally known as design patterns, to produce new functionality.  In the next slide, we will show what a Java program looks like, but it is a just a glimpse, and this class will walk you through it.
  • 3. My First Java Program…Java already public class MyFirstJavaProgram { // Start the program public static void main(String[] args){ if(args.length >0){ // If argument print name String myName = (String) args[0]; System.out.println("Hello " +myName); }else{ // Else print System.out.println("Hello there"); } } }
  • 4. What is a JRE?  To run a Java program, all that is needed is the Java Runtime Environment (JRE).  The JRE comes with the command line environment to compile and run Java programs.  To develop a Java program, a Java Development Kit (JDK) is used, which is an extension of the JRE with additional Java Archive (JAR) files for development.  JAR files are additional classes and libraries to extend programs. There are JAR files for network programming, web programming, and much, much more. The JAR files are zipped up classes, which are compiled Java programs.  The JRE, which is the Standard Edition, can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html .
  • 5. To set up the JRE  After downloading and installing the JRE program, we need to ensure that the JRE is in the Path fo windows to be run.  See http://stackoverflow.com/questions/1672281/environment-variables-for-j
  • 6. To set up the JRE
  • 7. To set up the JRE
  • 8. To set up the JRE
  • 9. To set up the JRE
  • 10. To set up the JRE
  • 11. Seeing it at the command prompt…  At the command prompt, notice the Java extension, we will walk through all of the program as time progresses, the Java program :
  • 12. Find the compiler…  At the command prompt, check to make sure that the JDK is set for compiling :  At the command prompt, the JDK is set in the environment for compiling :
  • 13. Compile…  At the command prompt, run the java compiler “javac”:
  • 14. Run the program…  At the command prompt, run the java program without the argument, “java” runs the program:
  • 15. Developing your environment  Java can be compiled and ran from the command line as long as the paths for JRE and JDK are set correctly.  Java developers have multiple ways to develop Java code, there are Integrated Development Environments (IDE), such as Eclipse and NetBeans, and there are txt editors, such as UltraEdit, Jedit, Geany, and more.  An article describing the difference can be found at http://java.about.com/od/gettingstarted/a/ideversuseditor.htm .  An IDE will assist heavily in providing many tools to develop in, to multiple frameworks to provide an extensive development environment, the drawbacks is that the production environment may be set up differently without some of these tools.  A text editor will allow you edit the code directly out of the environment, but you may have to memorize more Java syntax and framework syntax’s.
  • 16. Text Editors  Text Editors do not normally offer code completion, in which you can type in part of a word and it will complete it.  However, you can edit Java code directly from an environment and restart it quickly. Sometimes, a mixture of both text editor and IDE’s are used.  A good article on text editors fro Java programmers can be found at http://stackoverflow.com/questions/3716482/what-text-editor-for-a-java-
  • 17. Online compilers  There are also Java online compilers to test small amounts of code, such as http://ideone.com/ .
  • 18. IDE’s  A list of the best Java IDE’s can be found at http://faq.programmerworld.net/programming/best-java-ide-review.html . We can see in Eclipse as it gives code suggestions:
  • 20. Java syntax The first piece to understand is the Java syntax, which are the rules for defining a Java program, see https://en.wikipedia.org/wiki/Java_syntax We will start with the basics; Identifiers Literals Comments Code Blocks Keywords
  • 22. Identifiers Identifiers are the names of code elements in Java, which could name of variables, methods, classes, packages and interfaces. There are many naming rules normally used in Java; A name cannot start with a digit or $, or be a reserved word. No spaces can be used in the name. Java is case-sensitive. Normally classes start with a uppercase letter and define an object. class FileReader{ Methods are verbs that start in lowercase letters. void readFile ( ){ Variables are nouns that start in lowercase letters. File tempFile = new File …. See http://www.cwu.edu/~gellenbe/javastyle/naming.html
  • 24. Comments  Comments are used to communicate the purpose of parts of the program in the code.  It is not code that executes.  Comments are not executed as part of the code and are ignored by the compiler.  Using the (//) double slashes will tell the compiler to ignore the entire line.  Using the (/*) slash star will start the compiler to ignore the comment until it meets the ending slash star (*/). Here are the two types of comments: // Start the program, single line comment /* Start the program, multiple line comment */
  • 26. Variables  A variable is a value that can change.  http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html  A variable has a type, name and value.  The type of the variable will define the criteria that the value must meet. For example, int age = 29; Where the value is an integer of 29, and the name is age.  Not only does the variable must match a specific type, normally known as the the “Data Type”, but it must have scope and access.  The scope of the variable defines where the variable lives in an application, and the access will define what pieces of the program can access the variable. int cadence = 0;
  • 27. Variable Scope There are 4 main scopes of a variable: 1)Instance variables – are variables that live and die within a object, for every object created, new variables are created, living in each new instance of an object. 2)Class variables -- are static variables within a class, so for very object created, there is only one variable created for all the objects. 3)Local variables -- are local to a method and are created in the method call, and are no longer available after the method is completed. 4)Parameters – are variables passed into methods, to be used by the method as arguments. int cadence = 0;
  • 28. Naming Naming a variable: Are case-sensitive. Name is not name. Cannot have white-spaces or special characters. But can contain digits or underscores after letters, but cannot start with digits. Cannot match a Java keyword or reserved work. Some valid examples, int is a keyword that we will discuss later: int max_age =50; int age2 = 50; int cadence = 0;
  • 30. Statements  A statement is roughly equivalent to a sentence in natural languages.  A statement forms a complete unit of execution followed by a semi- colon.  A statement is line for a singe unit of work.  A line in Java is ended with ( ; ) semicolon.  See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.htm
  • 31. Statement examples ment aValue = 8933.234; // increment statement aValue++; // method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myB
  • 32. Blocks  A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.  A block is started with the ( { ) opening brace and ends with the ( } ) closing brace.  Blocks are groups of individual statements.
  • 33. Blocks -samples public class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } }
  • 36. Main method  Every Java program must have a “main” method.  There is only one “main” method in every Java file, but there can be multiple Java files per project or JAR.  Each Java program with a main, is enclosed with a public class name that is the same name used as the filename.  The “main” method is where the program starts it’s execution, and the closing brace ( } ) of the “main” method is where the program will end.
  • 37. Main method  In this example, we have a program called BlockDemo in a file called BlockDemo.java.  The names must match as the “public class BlockDemo”.  The main method must be of the form “public static main(String[] args)” in which we will cover the elements as keywords and later.
  • 38. Main method args  T he args parameters is a String array that contains any command-line arguments used to run the application.  See http://java.about.com/od/m/g/mainmethod.htm The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application. The args parameter is a String array that contains any command-line arguments used to run the application
  • 39. Main method args example import java.util.Arrays; public class PrintArguments { public static void main(String[] args) { String commandlineArgs = Arrays.toString(args); // The Arrays.toString function encases the Strings // in the array with square brackets. if (commandlineArgs.equals("[]")) { System.out.println("There were no arguments."); } else { System.out.println("There command-line arguments were: " + commandlineArgs + "."); } } } The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application. The args parameter is a String array that contains any command-line arguments used to run the application
  • 40. Example output The args parameter is a String array that contains any command-line arguments used to run the application.The args parameter is a String array that contains any command-line arguments used to run the application. The args parameter is a String array that contains any command-line arguments used to run the application
  • 41. Continuing We could go on about methods, classes and variables, but it will do little good without knowing the keywords. We will dive deeper into what we have learned so far after learning the basic keywords for the Java syntax, int cadence = 0;
  • 43. Keywords Are words used in the Java language to develop in as part of the Java syntax, We will cover keywords later as well in other sections. Sometimes keywords may be referred to as reserved words, reserved words are words reserved by the Java language, keywords are words reserved by the Java language to use as development. A variable has a type, name and value. So all keywords are reserved words. Keywords make up the Java language, so many people memorize them when developing. Knowing the keywords is the basis of all Java programming, the rest is structure of the code, scope of the execution, and extending basic features. So knowing the keywords provide the keys for knowing Java. A good reference to start with is http://www.dummies.com/how-to/content/java-keywords.html int cadence = 0;
  • 46. Primitive Data Types  We will start with the keywords that are the 8 primitive data types. As the name implies, these are the most basic data types used to store values.  A reference for the 8 primitive types can be found at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html  A variable has a type, name and value.  The type of the variable will define the criteria that the value must meet. For example, int age = 29; Where the value is an integer of 29, and the name is age. int cadence = 0;
  • 47. Primitive Data Types int cadence = 0;
  • 48. Primitive Data Types int cadence = 0;
  • 49. Primitive Data Types Example public class PrimitiveDataTypesExample { public static void main(String[] args) { // declaring primitive data types: 8 types int intNumber = 1000000000; short shortNumber = 32767; long longNumber = 1000000000; float floatNumber = 100.03244f; double doubleNumber = 100000.33432; char oneCharacter = 'A'; boolean flag = true; byte byteNumber = 127; // displaying primitive data types results System.out.println("integer number is: " + intNumber); System.out.println("short number is: " + shortNumber); System.out.println("long number is: " + longNumber); System.out.println("float number is: " + floatNumber); System.out.println("double number is: " + doubleNumber); System.out.println("charcter is: " + oneCharacter); System.out.println("boolean flag is: " + flag); System.out.println("byte is: " + byteNumber);}} int cadence = 0;
  • 50. Program output integer number is: 1000000000 short number is: 32767 long number is: 1000000000 float number is: 100.03244 double number is: 100000.33432 charcter is: A boolean flag is: true byte is: 127 int cadence = 0;
  • 51. Primitive Data Types The 8 primitive types are : We will start with the keywords that are the 8 primitive data types. As the name implies, these are the most basic data types used to store values. A reference for the 8 primitive types can be found at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html A variable has a type, name and value. The type of the variable will define the criteria that the value must meet. For example, int age = 29; Where the value is an integer of 29, and the name is age. The int is the integer primitive data type. int cadence = 0;
  • 52. Primitive Wrapper Classes The 8 primitive types have supporting classes for more features, such as parsing : See https://en.wikipedia.org/wiki/Primitive_wrapper_class int cadence = 0;
  • 53. Wrapping example code public class WrappingUnwrapping { public static void main(String args[]) { // data types byte grade = 2; int marks = 50; float price = 8.6f; double rate = 50.5; // data types to objects -- wrapping Byte g1 = new Byte(grade); Integer m1 = new Integer(marks); Float f1 = new Float(price); Double r1 = new Double(rate); // let us print the values from objects System.out.println("Values of Wrapper objects (printing as objects)"); System.out.println("Byte object g1: " + g1); System.out.println("Integer object m1: " + m1); System.out.println("Float object f1: " + f1); System.out.println("Double object r1: " + r1); int cadence = 0;
  • 54. Wrapping example code // objects to data types (retrieving data types from objects) byte bv = g1.byteValue(); // unwrapping int iv = m1.intValue(); float fv = f1.floatValue(); double dv = r1.doubleValue(); // let us print the values from data types System.out.println("Unwrapped values (printing as data types)"); System.out.println("byte value, bv: " + bv); System.out.println("int value, iv: " + iv); System.out.println("float value, fv: " + fv); System.out.println("double value, dv: " + dv); } } int cadence = 0;
  • 55. Output Values of Wrapper objects (printing as objects) Byte object g1: 2 Integer object m1: 50 Float object f1: 8.6 Double object r1: 50.5 Unwrapped values (printing as data types) byte value, bv: 2 int value, iv: 50 float value, fv: 8.6 double value, dv: 50.5 int cadence = 0;
  • 57. Next, we will approach conditionals and loops int cadence = 0;
  • 58. Conditional and loops Conditional Statements and loops use some of he same logic inside methods, An if-else conditional statement will check a condition and if the condition matches, it will execute a block of code. A loop, be it for, do-while, or while will continually execute a block of code while the condition is met. int cadence = 0;
  • 59. If - else The if-else conditional statements will look for the true or false, also it can be considered as a 1 or 0, to follow the statement if true, and skip if false. See http://www.wikijava.org/wiki/If_else_statements int cadence = 0;
  • 60. If – else example public class IfElseDemo { public static void main(String[] args) { // set the grade int testscore = 76; char grade; if (testscore >= 90) { // is 90 or above grade = 'A'; } else if (testscore >= 80) { // is 80 or above grade = 'B'; } else if (testscore >= 70) { // is 70 or above grade = 'C'; } else if (testscore >= 60) { // is 60 or above grade = 'D'; } else { // if none of the above grade = 'F'; } System.out.println("Grade = " + grade);}} int cadence = 0;
  • 61. If – else example output Grade = C int cadence = 0;
  • 62. Switch statement public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; int cadence = 0;
  • 63. Switch statement case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString);}} OUTPUT August int cadence = 0;
  • 64. Switch statement example Using too many if-else conditionals can become unreadable. The switch establishes many if-else’s to be put into a block of code where it checks for constants sequentially. The switch statement it limited to constants, exact values, as keys. See https://en.wikipedia.org/wiki/Switch_statement int cadence = 0;
  • 65. Loops -- For The for loop is the most basic of loops, A loop is like a conditional, except instead of executing only one statement, it executes the statements a given number of times, or based on a condition’s change. See http://www.tutorialspoint.com/java/java_loop_control.htm int cadence = 0;
  • 66. For loop syntax int cadence = 0;
  • 67. For loop example public class ForDemo { public static void main(String args[]) { for (int x = 10; x < 20; x = x + 1) { System.out.print("value of x : " + x); System.out.print("n"); } } } int cadence = 0;
  • 68. For loop example output value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 int cadence = 0;
  • 69. Loops – For Each The for loop has been extended in Java 5 to automatically go through the number of iterations available. Iterations and Collections will be addresses in a latter section as this section is only about the keywords themselves. int cadence = 0;
  • 70. Loops – For Each int cadence = 0;
  • 71. For Each example public class ForEachDemo { public static void main(String args[]) { int[] numbers = { 10, 20, 30, 40, 50 }; for (int x : numbers) { System.out.print(x); System.out.print(","); } System.out.print("n"); String[] names = { "James", "Larry", "Tom", "Lacy" }; for (String name : names) { System.out.print(name); System.out.print(","); } } } OUTPUT 10,20,30,40,50, James,Larry,Tom,Lacy, int cadence = 0;
  • 72. While Loop The while loop will continually execute its block of code while a particular condition is true. See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html The syntax is as follows: int cadence = 0; The while statement continually executes a block of statements while a particular condition is true. The while statement continually executes a block of statements while a particular condition is true.
  • 73. While Loop example public class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } OUTPUT Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 int cadence = 0; The while statement continually executes a block of statements while a particular condition is true. The while statement continually executes a block of statements while a particular condition is true.
  • 74. Do-while Loop The do-while loop, except that it’s expression is evaluated after the execution instead of before the execution of statements, so that the statements are executed at least once. The syntax is as follows: int cadence = 0; The while statement continually executes a block of statements while a particular condition is true. The while statement continually executes a block of statements while a particular condition is true.he Java programming language also provides a do-while statement, which can be expressed as follows: statement(s) } while (expression); he difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed
  • 75. Do-While Loop example public class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } } OUTPUT Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 int cadence = 0; The while statement continually executes a block of statements while a particular condition is true. The while statement continually executes a block of statements while a particular condition is true.
  • 76. Break and continue The break statement is used to break out of loop. The continue statement skips the rest of the statements in the current iteration of the loop. int cadence = 0;
  • 77. Continue and Break example public class ContinueBreakDemo { public static void main(String[] args) { System.out.println("starting loop:"); for (int n = 0; n < 7; ++n) { System.out.println("in loop: " + n); if (n == 2) { continue; } System.out.println(" survived first guard"); if (n == 4) { break; } System.out.println(" survived second guard"); // continue at head of loop } // break out of loop System.out.println("end of loop or exit via break"); } } int cadence = 0;
  • 78. Continue and Break output starting loop: in loop: 0 survived first guard survived second guard in loop: 1 survived first guard survived second guard in loop: 2 in loop: 3 survived first guard survived second guard in loop: 4 survived first guard end of loop or exit via break int cadence = 0;
  • 79. We will discuss the modifiers next int cadence = 0;
  • 81. Exception Handling Exception Handling is handling anything that happens abnormally in the program. Normally a program may operate fine, but when a file that is needed is removed, or memory is too low, something needs to be done to compensate for normal operation. When the program tries to account for the abnormal condition, it is called “Exception Handling”. See https://en.wikipedia.org/wiki/Exception_handling int cadence = 0;
  • 83. The try keyword  The first step in constructing an exception handler is to enclosed the code that might throw an exception with the try block.  This is to check to see if the code will try to throw the exception enclosed in a block of code.  See http:// docs.oracle.com/javase/tutorial/essential/exceptions/try.html  The syntax will look like the following: int cadence = 0;
  • 84. The catch keyword  When a program will try to look for an exception, it can either catch the exception or try to re-throw the exception.  The exception is a object containing all of the stack trace, message information, and other parts that tell what happened. It is like a wrapper to an abend in other languages.  See http:// docs.oracle.com/javase/tutorial/essential/exceptions/catch.html  The syntax will look like the following: int cadence = 0;
  • 85. The try-catch example import java.io.*; import org.apache.commons.io.FileUtils; public class TryCatchDemo { public static void main(String[] args) throws IOException { try { // constructor may throw FileNotFoundException String contents = FileUtils.readFileToString(new File("somefile.txt")); System.out.println("--- File End ---"); } catch (FileNotFoundException ex1) { //Create the file since it didn't exist System.out.println(ex1.getMessage()); File f=new File("somefile.txt"); f.createNewFile(); } } } int cadence = 0;
  • 86. The try-catch example output File 'somefile.txt' does not exist Please note that the file was created because it didn’t exist. int cadence = 0;
  • 87. The finally keyword The finally block always executes when the try bock exists. This includes rather a catch block is called or even exists. A catch block does not have to exist with a try block. The finally block is used to close files, and any other cleanup that needs to occur, just in case a catch block is called. See http:// docs.oracle.com/javase/tutorial/essential/exceptions/finally.html int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 88. The finally example public class TryCatchFinallyDemo { public static void main(String[] args) throws IOException { FileReader reader = null; try { reader = new FileReader("someFile.txt"); int i = 0; while (i != -1) { i = reader.read(); System.out.println((char) i); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } System.out.println("--- File End ---"); } } } int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 89. The finally example -output someFile.txt (The system cannot find the file specified) --- File End --- int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 90. The throw keyword  We were able to catch the exception, because another program or library threw the exception with the throw keyword.  Because the file was not found, in a previous example, the file library created a throw object to send to our catch block.  We will cover more in later sections if it seems complicated.  See http:// docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html int cadence = 0;
  • 91. The throw example public class ThrowDemo { public static void main(String[] args) throws IOException { try { File f = new File("somefile.txt"); if(!f.exists()) // if file doesn't exist throw new FileNotFoundException("Richs' file not found"); System.out.println("--- File End ---"); } catch (FileNotFoundException ex1) { System.out.println(ex1.getMessage()); } } } int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 92. The throw example-output Richs' file not found int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 93. The throws keyword The throws keyword is used at the method’s signature, and must be declared when the method itself does not catch the specific exception. In our examples, we have seen this with “throws IOException” as it could be caught from the try, but we were not catch’ing it: int cadence = 0;
  • 94. The throws example public class ThrowsDemo { public static void main(String[] args) throws FileNotFoundException { try { File f = new File("somefile.txt"); if(!f.exists()) // if file doesn't exist throw new FileNotFoundException("Richs' file not found"); } finally { System.out.println("--- File End ---"); } } } int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 95. The throws example -output Exception in thread "main" --- File End --- java.io.FileNotFoundException: Richs' file not found at ThrowsDemo.main(ThrowsDemo.java:10) int cadence = 0; p in constructing an exception handler is to enclose the code that might throw an exception w
  • 97. Modifiers  There are many types of modifiers in Java.  There are class modifiers that modify the behavior of Java classes.  There are method modifiers that modify the behavior of Java methods.  There a variable modifiers that modify the behavior of Java variables.  Of these modifiers, there are access modifiers that modify the access to classes, methods and variables.  There are non-access modifiers that change the behavior of these elements, but not the level of access.
  • 99. Access Modifiers  Access modifiers define what level of visibility and access that a class, method or variable to other classes and methods.  This piece will be further explained in the section that discusses Object-Oriented Design (OOD) with examples, this section is just to provide a definition of the keywords themselves.  There are 4 access levels for these keywords:
  • 101. Public, Protected and Private  When the “public” access modifier, or keyword, is placed in front of classes or methods, it gives all other pieces of the program access to the method or classes.  When the “protected” access modifier, or keyword, is placed in front of classes or methods, it gives the child class access to that class or method but no one else.  When the “private” access modifier, or keyword, is placed in front of classes or methods , it means that no other class may have access to that class or method.  If no access modifier is defined, the default is used, which states that it can be used in the same class and package.
  • 102. A simple table to see the access modifier
  • 104. Non-Access Modifiers  There are many types of modifiers in Java.  There are class modifiers that modify the behavior of Java classes.  There are method modifiers that modify the behavior of Java methods.  There a variable modifiers that modify the behavior of Java variables.  Of these modifiers, there are non-access modifiers that modify the lifetime behavior of classes, methods and variables.  See http://javabeginnerstutorial.com/core-java-tutorial/non- access-modifiers-in-java/
  • 107. Modifiers are in classes, variables and methods
  • 108. Class Modifiers  Non-Access Modifiers will define the behavior of classes.  As a reference, please see http://docs.oracle.com/javase/tutorial/reflect/class/classModifiers.html
  • 109. abstract types  An abstract class can have abstract methods. It is a class that contains abstract methods, but the class can be declared abstract without abstract methods.  Abstract methods contain the signature of the method, the declaration that a subclass must use, but not the body. The body is defined in the subclass.  As a reference, please see https://en.wikipedia.org/wiki/Abstract_type and http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
  • 110. abstract example //abstract class abstract class Sum{ //abstract methods public abstract int SumOfTwo(int n1, int n2); public abstract int SumOfThree(int n1, int n2, int n3); //Regular method public void disp(){ System.out.println("Method of class Sum"); } } class AbstractDemo extends Sum{ public int SumOfTwo(int num1, int num2){ return num1+num2; } public int SumOfThree(int num1, int num2, int num3){ return num1+num2+num3; } public static void main(String args[]){ AbstractDemo obj = new AbstractDemo(); System.out.println(obj.SumOfTwo(3, 7)); System.out.println(obj.SumOfThree(4, 3, 19)); obj.disp();}}
  • 111. abstract example - output 10 26 Method of class Sum
  • 112. final types  final – declares a a variable cannot be changed, a class cannot be extended, or a method cannot be overwritten. It cannot change. As a reference, please see https://en.wikipedia.org/wiki/Final_%28Java%29  The final class can be inherited, as well as the method, and the variable re-used, however, the class, method and variable cannot be changed, meaning that it cannot be overwritten. See http://javarevisited.blogspot.com/2011/12/final-variable-method-class-jav
  • 113. Final variable example public class FinalVariableExample { public static void main(String[] args) { /* * Final variables can be declared using final keyword. Once created and * initialized, its value can not be changed. */ final int hoursInDay = 24; // This statement will not compile. Value can't be changed. // hoursInDay=12; System.out.println("Hours in 5 days = " + hoursInDay * 5); } } } OUTPUT Hours in 5 days = 120
  • 114. static type  static – declares that methods and variables belong to a class and not of an instance, meaning that there is only one variable or method for all the objects of that class to use. It is different than final, as final cannot be changed, but a static variable can be changed, but there only one instance, and not multiple instances.  As a reference, please see https://en.wikibooks.org/wiki/Java_Programming/Keywords/static
  • 115. static variable example public class StaticDemo { static int count = 0; public void increment() { count++; } public static void main(String args[]) { // Multiple objects, but only one count StaticDemo obj1 = new StaticDemo(); StaticDemo obj2 = new StaticDemo(); obj1.increment(); obj2.increment(); System.out.println("Obj1: count is=" + obj1.count); System.out.println("Obj2: count is=" + obj2.count); } } OUTPUT Obj1: count is=2 Obj2: count is=2
  • 116. transient type  transient – declares that specific variables should not be serialized when variables are serialized.  For instance, an object can be saved into a file or database, the transient keyword tells the program not save the variable.  As a reference, please see https://en.wikibooks.org/wiki/Java_Programming/Keywords#transient
  • 117. native type  native – declares an implementation coming from a native programming language such as C.  This is only used if programming using native methods used in the Java Native Interface.  As a reference, please see https://en.wikibooks.org/wiki/Java_Programming/Keywords/native
  • 118. strictfp type  strictfp – used to restrict the precision and rounding of floating point calculations to ensure portability.  As a reference, please see http://www.javatpoint.com/strictfp-keyword
  • 119. synchronized type  synchronized – used to declare a method or code block to be thread safe, only allowing one thread to access the code at a time.  This is used when creating mult-threaded java programs.  As a reference, please see https://en.wikipedia.org/wiki/Java_concurrency
  • 120. volatile type  Used to declare that a variable can be changed in different threads or when serialized.  This is the opposite of synchronized when creating Java multi- threaded programs.  As a reference, please see http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example and http://javamex.com/tutorials/synchronization_volatile.shtml
  • 122. Class keywords There are still many keywords used in the declaration and references of classes. These are non-modifiers, as they are used to reference the object or declare a new one without any modifications to the existing one. Most of this will be covered in more detail in the OOD portion of the class. class – declares a class type. extends – is a class that will extend a parent or abstract. implements – declares that a class will implement a interface, which is a class that declares how is class it be formed without any of the implementation. import– declares what functionality from other classes can be imported into the current classes in the file. instanceof -- tests to see whether a certain object comes from a certain class. int cadence = 0;
  • 123. On more keywords  interface – declares a class to contain the rules, methods and variables, for other classes to implement, without actually implementing the pieces itself.  new – creates a new object from a class.  package – declares, in the first line of code in a class file, that this class file will now be declared to be part of a package of code, a package name is normally the reverse of a company URL, such as “com.cdle.Parser”.  super – used to access methods and variables of the parent object.  this –used to access methods and variables of the current object. int cadence = 0;
  • 125. Package and import  The package is the first line declared in a Java file, if used.  The package is a means to group Java programs to avoid conflicts with other Java programs.  For example, I could have 2 programs that create files with the createfile(File) function. So which one do we call.  The package identifier is used to identify which package that the file was created in, and import function is used to identify which package to retrieve the function from.  See http://javaworkshop.sourceforge.net/chapter3.html#What+is+a+ Package%3F int cadence = 0;
  • 126. Package and import  The package declaration will be in the first line, and now the file must be stored in the “com.coworkforce” subdirectory to create a path for the package of Java files will be stored: int cadence = 0;
  • 127. Package and import  If we want to import, or get the functionality from the ThisDemo.java file, we have to import the file from its package area: int cadence = 0;
  • 128. class  The Java class will declare a class which will be covered in ythe OOD piece of the course.  A class is the blueprints of an object. It defines it.  As a reference, please see http://docs.oracle.com/javase/tutorial/java/concepts/class.html
  • 129. new  The Java new keyword will create the instance of a class.  The class is the definition of the object, the new is the declaration of the class into an instance of an object.  Again, it will be covered again in greater depth later. This is just to familiarize oneself with the keywords.  As a reference, please see http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreatio n.html
  • 130. Class example public class ArrayObjDemo { public static void main(String args[]) { System.out.println("Hello, World!"); // step1 : first create array of 10 elements that holds object // addresses. Emp[] employees = new Emp[10]; // step2 : now create objects in a loop. for (int i = 0; i < employees.length; i++) { employees[i] = new Emp(i + 1);// this will call constructor. } } } class Emp { int eno; public Emp(int no) { eno = no; System.out.println("emp constructor called..eno is.." + eno); } }
  • 131. Class example What we just did was create 10 objects of an Emp class in the following output, new was used to create the 10 objects, of the only one class called Emp: Hello, World! emp constructor called..eno is..1 emp constructor called..eno is..2 emp constructor called..eno is..3 emp constructor called..eno is..4 emp constructor called..eno is..5 emp constructor called..eno is..6 emp constructor called..eno is..7 emp constructor called..eno is..8 emp constructor called..eno is..9 emp constructor called..eno is..10
  • 132. this  The this object reference is used to access methods and variables of the current object.  As a reference, please see http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
  • 133. This example package com.coworkforce; public class ThisDemo { int id; String name; public ThisDemo(int id, String name) { this.id = id; this.name = name; } void display() { System.out.println(id + " " + name); } public static void main(String args[]) { ThisDemo s1 = new ThisDemo(111, "Karan"); ThisDemo s2 = new ThisDemo(222, "Aryan"); s1.display(); s2.display(); }}
  • 134. This example --output In the “this” example, we simply attached the variable to the current variable of the same name in the current object using: this.id = id; this.name = name; We can see the output as: 111 Karan 222 Aryan
  • 135. Super object reference type  The super keyword is used to access methods and variables of the parent object.  As a reference, please see http://docs.oracle.com/javase/tutorial/java/IandI/super.html
  • 136. super example class Vehicle { Vehicle() { System.out.println("Vehicle is created"); } } class Bike extends Vehicle { Bike() { super();// will invoke parent class constructor System.out.println("Bike is created"); } public static void main(String args[]) { Bike b = new Bike(); } }
  • 137. super example --output The super keyword will invoke the Vehicle constructor. We can see the output as: Vehicle is created Bike is created
  • 138. instanceof  The instanceof keyword will return true if an object was created from a specific class.  It checks if an object reference is an instance of a type, and returns a boolean value  As a reference, please see https://en.wikibooks.org/wiki/Java_Programming/Keywords/inst anceof
  • 140. extends  The extends keyword will extend a parent class into a subclass, or child class.  The extends can only be used once in the declaration, so a child class has only one parent, thus why super( ) will call the one and only parent.  As a reference, please see https://en.wikibooks.org/wiki/Java_Programming/Keywords/inst anceof
  • 141. extends example class Parent { int x; void setIt (int n) { x=n;} void increase () { x=x+1;} void triple () {x=x*3;}; int returnIt () {return x;} }
  • 143. interface and implement type  The interface keyword declares that a class is not a concrete class, but an interface.  An interface is similar to an abstract class, except that all methods are not defined, but are used as declarations that must be implements.  The implement keyword will declare that the class must implement the interface functionality.  As a reference, please see http://docs.oracle.com/javase/tutorial/java/concepts/interface.ht ml and https://en.wikipedia.org/wiki/Interface_%28Java%29
  • 144. interface example interface IntExample { public void sayHello(); } /* * Classes are extended while interfaces are implemented. To implement an * interface use implements keyword. IMPORTANT : A class can extend only one * other class, while it can implement n number of interfaces. */ public class InterfaceDemo implements IntExample { /* * We have to define the method declared in implemented interface, or else * we have to declare the implementing class as abstract class. */
  • 145. interface example interface IntExample { public void sayHello(); } public class InterfaceDemo implements IntExample { public void sayHello() { System.out.println("Hello Visitor !"); } public static void main(String args[]) { // create object of the class InterfaceDemo demo = new InterfaceDemo(); // invoke sayHello(), declared in IntExample interface, but defined in // InterfaceDemo. demo.sayHello(); } } Output is “Hello Visitor !”
  • 148. More keywords We have not yet covered the keywords that we have used in the main method, such as void and return. void – designates that a method will not return a value. return – designates the return values from the method. We have also not covered the assert keyword. assert – tests that a condition is true/false, and if false throws an exception. We have also not covered the enum keyword. return – designates the return values from the method. int cadence = 0;
  • 150. Assert  The assert keyword tests that a condition is true/false, and if false throws an exception.  It must be ran with the “-ea” argument to use the assert function.  See https://en.wikipedia.org/wiki/Assertion_ %28software_development%29 int cadence = 0;
  • 151. Assert example public class AssertDemo { public static void main(String args[]) { boolean assertTest = true; assert assertTest; assertTest = false; assert assertTest; } } int cadence = 0;
  • 152. enum  An enum type is a special data type that enables for a variable to be a set of predefined constants.  See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html int cadence = 0;
  • 153. enum example public class EnumDemo { public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Day day; public EnumDemo(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break;}} int cadence = 0;
  • 154. enum example public static void main(String[] args) { EnumDemo firstDay = new EnumDemo(Day.MONDAY); firstDay.tellItLikeItIs(); EnumDemo thirdDay = new EnumDemo(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumDemo fifthDay = new EnumDemo(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumDemo sixthDay = new EnumDemo(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumDemo seventhDay = new EnumDemo(Day.SUNDAY); seventhDay.tellItLikeItIs(); } } The OUTPUT: Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best. int cadence = 0;
  • 155. void and return  In many cases, a value has to be returned from a function using the return statement, if no value is to be returned, then we must use the void statement on the method.  See http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.h tml int cadence = 0;
  • 156. Return example public class ReturnDemo { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if (t) return; // return to caller System.out.println("This won't execute."); } } The OUTPUT: Before the return. int cadence = 0;
  • 157. Keyword conclusion Knowing the Java keywords provides the keys for knowing Java,. There are more areas to cover to truly know Java, Object-Oriented Design (OOD), Operations on variables, Arrays, Collections, more on exception handling and loops. However, these are all extensions on what has been covered. Know the previous slides, and with further details, the rest of the chapters will reference the keywords. int cadence = 0;
  • 159. Operators  Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.  See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operator s.html and http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsum mary.html  We have been using the equal operator all along: int age = 50;
  • 162. Arithmetic operators example public class ArithmeticOperatorDemo { // Demonstrate the basic arithmetic operators. public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int i = 1 + 1; int n = i * 3; int m = n / 4; int p = m - i; int q = -p; System.out.println("i = " + i); System.out.println("n = " + n); System.out.println("m = " + m); System.out.println("p = " + p); System.out.println("q = " + q);
  • 163. Arithmetic operators example // arithmetic using doubles System.out.println("nFloating Point Arithmetic"); double a = 1 + 1; double b = a * 3; double c = b / 4; double d = c - a; double e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); } }
  • 164. Arithmetic operators example - output Integer Arithmetic i = 2 n = 6 m = 1 p = -1 q = 1 Floating Point Arithmetic a = 2.0 b = 6.0 c = 1.5 d = -0.5 e = 0.5
  • 165. Unary operators Unary means that there is only one operand, functions:
  • 166. Unary example public class UnaryDemo { public static void main(String[] args) { int result = +1; // result is now 1 System.out.println(result); result--; // result is now 0 System.out.println(result); result++; // result is now 1 System.out.println(result); result = -result; // result is now -1 System.out.println(result); boolean success = false; System.out.println(success); // false System.out.println(!success); // true } }
  • 167. Unary example -- output 1 0 1 -1 false true
  • 168. Bitwise operators Bitwise operators change the bits inside a number:
  • 169. Bitwise operators example public class BitwiseDemo { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c); c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c); c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c); c = ~a; /*-61 = 1100 0011 */ System.out.println("~a = " + c); c = a << 2; /* 240 = 1111 0000 */ System.out.println("a << 2 = " + c); c = a >> 2; /* 215 = 1111 */ System.out.println("a >> 2 = " + c); c = a >>> 2; /* 215 = 0000 1111 */ System.out.println("a >>> 2 = " + c);}}
  • 170. Bitwise operators example - output a & b = 12 a | b = 61 a ^ b = 49 ~a = -61 a << 2 = 240 a >> 2 = 15 a >>> 2 = 15
  • 171. Conditional Operators Conditional operators are used to evaluate a condition that is applied to one or two boolean expressions:
  • 172. Conditional operators example public class ConditionalDemo { public static void main(String args[]) { boolean a = true; boolean b = false; int c = 20; int d = 21; int max; System.out.println("a && b = " + (a && b)); System.out.println("a || b = " + (a || b)); System.out.println("!(a && b) = " + !(a && b)); if (c > d) { max = c; } else { max = d; } System.out.println("max with if = " + max); max = (c > d) ? c : d; System.out.println("max with ternary = " + max);}}
  • 173. Conditional operators example - output a && b = false a || b = true !(a && b) = true max with if = 21 max with ternary = 21
  • 174. Equality and Relational Operators Will test the relationship and equality from one operand to another:
  • 175. Equality operators example public class EqualityDemo { public static void main(String[] args) { int x = 5; int y = 10; if (x == y) System.out.println("value of x is equal to the value of y"); if (x != y) System.out.println("value of x is not equal to the value of y"); if (x > y) System.out.println("value of x is greater then the value of y"); if (x < y) System.out.println("value of x is less then the value of y"); if (x >= y) System.out .println("value of x is greater then or equal to the value of y"); if (x <= y) System.out .println("value of x is less then or equal to the value of y"); } }
  • 176. Equality operators example - output value of x is not equal to the value of y value of x is less then the value of y value of x is less then or equal to the value of y
  • 178. A BRIEF INTRODUCTION INTO OBJECT ORIENTED PROGRAMMING (OOP)
  • 179. A brief introduction to OOP  Learning Object Oriented Programming is as easy as PIE.  PIE stands for Polymorphism, Inheritance and Encapsulation.  These PIE characteristics provide common properties like re-use of pieces, hiding of internal data, and propagating characteristics of objects into other objects.  Don’t think that these code pieces are static in nature because the Business Objects can morph into new types of Business Objects as long as their constructs are defined.  Using this fluid style of programming, relational tables can be defined and created by simply defining the initial Business Object.  These concepts are expanded to create morphing viruses where a virus changes itself every time it hits a new machine so that it is a completely different characteristics after multiple propagations.
  • 180. Polymorphism  Polymorphism started a term in biology for how different types of species have the same generic traits.  It states that the same species may morph, having different qualities, in the same habitat.  For instance, the lady bug may morph into red spots or black spots in the same environment.  The commonality is that the two bugs are still lady bugs, but have different traits like spot colors.  Even though it has different spot colors, it is still lady bug, and flies like a lady bug, eats like a lady bug and does what lady bugs do.  When it no longer does the things a lady bug does, it is a different bug. That is when the bug morphs outside its common species definition.
  • 181. Polymorphism  In OOP, polymorphism is the ability of different objects, that are created by the same generic class, or traits, to be used the same across the same generic interface but still have different, or morphed, properties.  Let’s use an example, if we have a “Toyota” truck and “Ford” truck created with it’s parent class “Truck”.
  • 182. Polymorphism, continuing…  Now, let’s create a program called “Midas Touch” that handles the Truck objects and rotates their tires. class public MidasTouch{ Truck myTruck = new (Truck) Toyota (); }  The program “Midas Touch” can rotate the tires, regardless if it is a Toyota or Ford Truck object. The factory “Midas Touch” works with trucks but doesn’t have a preference over what type of truck it works on. Even though the Toyota or Ford Truck might have some different techniques for rotating tires, the factory will accept and work on any Truck object. … rotateTires(myTruck);
  • 183. Overriding methods Method overriding is a term in OOD that means that a child’s method will over write the parents method, both methods being exact in signature, method name, parameters and return type. See https://en.wikipedia.org/wiki/Method_overriding
  • 184. Overloading methods Method overloading is a term in OOD that means that a child’s method will be used over the parents when the child’s method signature does change. See https://en.wikipedia.org/wiki/Function_overloading
  • 185. Inheritance  Inheritance has to do more with genealogy and parentage.  This concept is to understand an objects behavior and traits by its inherited lineage.  A “child” class has a “parent” class that gave it many default properties. In Java only one parent.  For example, my parents gave me “brown hair” because they had brown hair, so I, the “child” class inherited my hair color from my “parent” class.  However, after being executed in the program, the program may change the hair color of the “child” class if the protection of the class allows it. For example, if I am indifferent to my hair color in real life, I could dye it if someone prompted me, but regardless, my hair started out brown and may return to its brown state.
  • 186. Inheritance  In the picture:  The Toyota and Ford are derived, or child classes, from their parent “Truck”  Because the “Toyota” object and “Ford” object inherited properties from its parent, we know that some traits are given to the child classes when they are created.  These Truck parent may have passed on to Toyota and Ford that they had an engine, 4 tires, a windshield, gas tank, brakes, etc.
  • 187. Inheritance, continuing…  Now, let’s use create a class from the parent class. class public Truck { Brakes myBrakes; Engine myEngine; Windsheild myWindSheild; } class public Toyota extends Truck{ // Already has myBrakes, myEngine, myWindsheild defined. } 
  • 188. Encapsulation  Encapsulation is also referred to as data hiding or information hiding.  Even though you may see the business object and its methods, you may not call or manipulate the inside data directly, or at all, unless you call a specific method.  Many objects may use a constructor to pass information into the object that it cannot retrieve without using a “getter( )” method.  For example, I could create a “Ford Truck” object, and it will have many properties like color, bed type, bin number, etc.  It will also have embedded objects like tires, windshields, radio, seats, etc.  In order to get data from the “Ford Truck” object, I need to call an getter method that it shows me like “getTirePressure( )” to return an integer of 35 for 35 psi.
  • 189. Putting it all together OOP introduced a new way of developing programs. See http://www.westga.edu/~bquest/1997/object.html Some of the benefits are: Better mapping of the problem domain, can treat objects as cars, car services, etc. Faster development as pieces can be modularized, farmed out separately and re-used. Modular Architecture and design, to assign some pieces for frameworks, other architects and other groups to develop.
  • 190. 2nd Java Sample Program with an object  Let’s create an class from the first program, and call it MyFirstObject: public class MyFirstObject{ private String myName; //Must go through function to change MyFirstObject(){// Constructor myName = "there"; } //Setter public void setName(String myName){ this.myName = myName; } //Getter public String getName(){ return this.myName; } }
  • 191. Some new terms  There are various terms that this program will add to our vocabulary, there are “setters”, functions that set variables, and “getters”, functions that get variables.  The Constructor is the method used to create the object. There could be multiple constructors, taking in different arguments as they “overload” their methods.  Overloading is when a method with the same name, but a different argument, is called based in it’s argument.  Also, introduced is the “this” pointer, or keyword, used in Java reflection.  “this” allows an object to look into the current instance of itself.  In other words, when the class becomes a object, I has state, variables, methods and information about itself, by using “this”, the class can manipulate its current data.
  • 192. 2nd Java Program object creation  In the code, there must always be one and only one “main” method that starts the execution.  The “main” method is static, which means that it is the only one. The execution of the program will load objects, and the “new” keyword will create our first object, “myObj”, from the “MyFirstObject” class.  After the “myObj” is created, we set the name if there is one passed through the argument, otherwise, it will return the default name “there”. Note: Even if a Constructor is not defined in code, a default one is always defined by the compiler. The “new” keyword must call a constructor to create an object from a class.
  • 193. 2nd Java Program object creation  Always remember that an object is never created, or instantiated, unless the “new” keyword is used. Let’s create the object: public class MySecondJavaProgram { public static void main(String[] args){ MyFirstObject myObj = new MyFirstObject(); if(args.length >0){ // If argument print name myObj.setName(args[0]); } System.out.println("Hello " + myObj.getName()); } // End Main }
  • 194. What happened  From this program, “MySecondJavaProgram”, we were able to create an object with the “new” keyword.  The object didn’t add much functionality than the first program, however, we can use the object across many programs, and start creating a framework of libraries.  A main purpose of OOP is reusability.  Another concept is also cleaner code construction. Because of the movement of the functionality of the program into a separate object, the code becomes compartmentalized.
  • 195. Extending functionality  Let’s extend the functionality of the first object, with the “extend” keyword, and create a child class: class MySecondObject extends MyFirstObject{ String myComment; // Constructor MySecondObject(){ myComment = "No Argument"; } //Setter void setComment(String myComment){ this.myComment = myComment; } //Getter String getComment(){ return this.myComment; } }
  • 196. Extending functionality  The program will create 2 objects now, the child object “MySecondObject” will create a “MyFirstObject” when created and use it’s functionality: public class MyThirdJavaProgram { public static void main(String[] args){ MySecondObject myObj = new MySecondObject(); if(args.length >0){ // If argument print name // From parent myObj.setName(args[0]); // From child myObj.setComment("Argument found"); } System.out.println("Hello " + myObj.getName()); } // End Main }
  • 197. Extending functionality  By extending functionality in a new object, I was able to add methods and variables without changing the initial code and how it works.  This becomes monumental when creating frameworks because now libraries can be extended without changing original functionality.  A new concept that can be introduced here is called “Overrriding”.  Overriding methods occurs when the method of the child class is used instead of the parent.  Since the parent, or super class, had a “setName” method, and the child did not, the parent’s method was used.  The child could “override” the parent’s “setName” method by simply having its own.
  • 198. SUPER  So far, we have discussed that when a child object is created, the parent object is also created and the child inherits their attributes.  The child object can also get data directly from their parent class using the “super” keyword. Here’s an example where the child object can get the “myName” information directly from their parent: //Print the name void printName(){ System.out.println("MyFirstObject's name " + super.myName); }
  • 199. Reflection  The “this” keyword has been briefly discussed. It is an important concept for an object to look at itself in introspection and examine what type of object it is, what state it is in, its current variables, and even its current properties. It is examining its own metadata.  Reflection comes in handy when serializing objects (saving to disk) and writing the objects variables and methods into XML.  The Simple API for XML (SAX) parser using reflection to develop its data definitions and types. Let’s start the code: import java.lang.reflect.*; public class Reflection1{ public static void main(String[] args) { WhoAmI whoami = new WhoAmI(); whoami.WhoAreYou(); } }
  • 200. Reflection (finding my fields/methods) class WhoAmI{ String test1 ="I think"; String test2 = "Therefore I am"; void CanYouSeeMe(){} void WhoAreYou(){ System.out.println("WhoAmI:" +this.getClass().getName()); Method [] methods = this.getClass().getDeclaredMethods(); Field [] fields = this.getClass().getDeclaredFields(); for(int i =0; i < methods.length;i++) System.out.println("Method:" +methods[i].getName()); for(int i =0; i < fields.length;i++) System.out.println("Field:" +fields[i].getName()); }
  • 201. Reflection  The code produced its fields and methods.  After collecting this information, it could easily be placed on the network, through XML or serialized to show what is available.  The output: WhoAmI:WhoAmI Method:WhoAreYou Method:CanYouSeeMe Field:test1 Field:test2
  • 202. Abstract (Must Do)  Not only can a child inherit from their parent, but a child can also be told the interface that they must produce.  This technique is an “interface” which is basically a parent that can “Do as I say and not as I do”.  Here’s an example interface that will force the child class to create the “setName” and “getName” methods: interface MustDo{ public abstract void setComment(String myComment); abstract String getComment(); } class MySecondObject extends MyFirstObject implements MustDo{  The second object will inherit from the first, but it “has to” create the functionality of the “MustDo” class.
  • 203. Final (Don’t Change)  In some instances of programming, a constant class, method or variable needs to be defined.  These are variables that do not change once they are set.  A class and method can be declared that a child class can not over write or perform overriding.  One example of a variable used in this way: final boolean DEBUG = false;  In this example, a developer may want a “DEBUG” variable that will be used in the class to decide to perform debug traces or not. In this case you want to force the variable to not be changeable.  During the instance of an object, the static variable can also be added to only allow the creation of the globally: static final boolean DEBUG = false;
  • 204. Import  The theme of Java has been abstraction, re-use, and frameworks.  It becomes a daunting task that there are so many frameworks to chose from and many are free.  By default, the “import” keyword is used to pull in other objects and packages into the file. For instance, the “import java.io.*;” statement at the top of the file will give scope to all classes in that the Java IO framework.  Pulling in the entire package does create some overhead on what is being exactly used and what is not, so a more precise definition of the package being used can be given in this example as the “Java IO File” class being referenced by “import java.io.File;”
  • 205. JAR  There are many frameworks, usually called packages, that come standard with Java.  These frameworks evolve to the Java standard over time.  For instance, the Java Cryptography Extensions (JCE) used to be Java Specification Request (JSR) 27 for some time. This is the framework for encrypting data with Triple-DES, RSA, and multiple algorithms.  During this period, a programmer who wanted to use the JCE.JAR had to download it separately. The package now comes with the J2SE.  The Java Archive (JAR ) file can be used by the program if both the file is associated through a “classpath” and its associated “import” is included.  The “classpath” is a property of the program that contains the paths of all classes.
  • 207. Java Properties  The program can determine it’s current environmental propeerties by using “System.getProperty()” and set them by “System.setProperty();”.  Here’s some sample code: public class JavaProperty { public static void main(String[] args) { System.out.println("Classpath:" + System.getProperty("java.class.path")); System.out.println("Java Version:" + System.getProperty("java.version")); System.out.println("Java Home:" + System.getProperty("java.home")); System.out.println("Operating System:" + System.getProperty("os.name")); System.out.println("User's Home:" + System.getProperty("user.home")); System.setProperty("user.home", "C:Documents and Settings"); System.out.println("User's Home:" + System.getProperty("user.home")); } }
  • 208. Java Properties  Notice that the “user.home” was changed by the program: Java Version:1.6.0_07 Java Home:C:Program FilesJavajre1.6.0_07 Operating System:Windows XP User's Home:C:Documents and Settingsqnwa08 User's Home:C:Documents and Settings
  • 209. Packages  As we discussed the “import” keyword, it is important to note that this statement defines the class and directory hierarchy in the JAR or file structure. See the JAR picture.  For instance, the JAR has the class “Cipher.class” file in the “javax/crypto/” subdirectory. The import statement will say “import javax.crypto.Cipher” on the calling file.  Part of the import statement tells which subdirectory to find the file starting from the JAR or classpath.  Subsequently, the file had to define this path and subsequent “import” statement by using the “package” keyword: package javax.crypto; public class Cipher { }  This is very important when creating packages or your own frameworks and to organize them in a directory structure.
  • 211. Strings  Strings are Java data objects that contain a sequence of characters.  The java platform provides the String class to create and manipulate Strings.  See http://docs.oracle.com/javase/tutorial/java/data/strings.html  Creating Strings: String greeting = “Hello World”; String greeting = "Hello world!";
  • 212. String methods String greeting = "Hello world!";
  • 213. Split example public class StringSplitDemo { public static void main(String a[]) { String str = "This program splits a string based on space"; String[] tokens = str.split(" "); for (String s : tokens) { System.out.println(s); } str = "This program splits a string based on space"; tokens = str.split("s+"); } } String greeting = "Hello world!";
  • 215. Compare example public class CompareString { public static void main(String[] args) { String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; /* compare two strings, case sensitive */ System.out.println( str.compareTo(anotherString) ); /* compare two strings, ignores character case */ System.out.println( str.compareToIgnoreCase(anotherStr ing) ); /* compare string with object */ System.out.println(str.equals(objStr) );}} OUTPUT -32 0 true String greeting = "Hello world!";
  • 216. Concat example public class ConcatDemo { public static void main(String args[]) { /* * String concatenation can be done in several ways in Java. */ String str1 = "Hello"; String str2 = " World"; // 1. Using + operator String str3 = str1 + str2; System.out.println("String concat using + operator : " + str3); String greeting = "Hello world!";
  • 217. Concat example /* * Internally str1 + str 2 statement would be executed as, new * StringBuffer().append(str1).append(str2) * * String concatenation using + operator is not recommended for large * number of concatenation as the performance is not good. */ // 2. Using String.concat() method String str4 = str1.concat(str2); System.out .println("String concat using String concat method : " + str4); String greeting = "Hello world!";
  • 218. Concat example // 3. Using StringBuffer.append method String str5 = new StringBuffer().append(str1).append(str2).toString(); System.out.println("String concat using StringBuffer append method : " + str5); } } OUTPUT String concat using + operator : Hello World String concat using String concat method : Hello World String concat using StringBuffer append method : Hello World String greeting = "Hello world!";
  • 219. String Array To List example import java.util.*; public class StringArrayToListDemo { public static void main(String args[]) { // create String array String[] numbers = new String[] { "one", "two", "three" }; /* * To covert String array to java.util.List object, use List * asList(String[] strArray) method of Arrays class. */ List list = (List) Arrays.asList(numbers); // display elements of List System.out.println("String array converted to List"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } String greeting = "Hello world!";
  • 220. String Array To List example } /* * Please note that list object created this way can not be modified. * Any attempt to call add or delete method would throw * UnsupportedOperationException exception. * * If you want modifiable list object, then use * * ArrayList list = (ArrayList) Arrays.asList(numbers); */ /* Alternate Method to covert String array to List */ List anotherList = new ArrayList(); Collections.addAll(anotherList, numbers); } } String greeting = "Hello world!";
  • 221. String Array To List example -output OUTPUT String array converted to List one two three String greeting = "Hello world!";
  • 222. Arrays
  • 223. Arrays  An array is a container object that holds a fixed number of values of a single type.  See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.h tml
  • 224. Array example 1 import java.util.Arrays; public class ArrayDemo2 { public static void main(String[] args) throws Exception { int[] ary = { 1, 2, 3, 4, 5, 6 }; int[] ary1 = { 1, 2, 3, 4, 5, 6 }; int[] ary2 = { 1, 2, 3, 4 }; System.out.println("Is array 1 equal to array 2?? " + Arrays.equals(ary, ary1)); System.out.println("Is array 1 equal to array 3?? " + Arrays.equals(ary, ary2));}} OUTPUT: Is array 1 equal to array 2?? true Is array 1 equal to array 3?? false
  • 225. Array example 2 import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayMergeDemo { public static void main(String args[]) { String a[] = { "A", "E", "I" }; String b[] = { "O", "U" }; List list = new ArrayList(Arrays.asList(a)); list.addAll(Arrays.asList(b)); Object[] c = list.toArray(); System.out.println(Arrays.toString(c));}} OUTPUT: [A, E, I, O, U]
  • 226. Array to List example
  • 228. Collections  Java collections are a set of frameworks for handling a collection of objects and data types.  By collection, it is a set, map, stack, queue and lists, that will manage a group of types and objects.  See https://en.wikipedia.org/wiki/Java_collections_framework
  • 229. Choosing a Collection  See http://javamex.com/tutorials/collections/how_to_choose.shtml
  • 230. Linked Lists The problem with arrays is that they are created to a fix size. Linked Lists are a Java collections that are meant to compensate for some of the array limitations. Linked Lists are data elements that are linked to each other and can be used as a single list of elements. See https://en.wikipedia.org/wiki/Linked_list With a link list, we can add a data element into a list, remove it, change position, and more.
  • 231. Linked Lists Example import java.util.LinkedList; public class LinkedListDemo1 { public static void main(String args[]) { /* Linked List Declaration */ LinkedList<String> linkedlist = new LinkedList<String>(); /*add(String Element) is used for adding * the elements to the linked list*/ linkedlist.add("Item1"); linkedlist.add("Item5"); linkedlist.add("Item3"); linkedlist.add("Item6"); linkedlist.add("Item2");
  • 232. Linked Lists Example /*Display Linked List Content*/ System.out.println("Linked List Content: " +linkedlist); /*Add First and Last Element*/ linkedlist.addFirst("First Item"); linkedlist.addLast("Last Item"); System.out.println("LinkedList Content after addition: " +linkedlist); /*This is how to get and set Values*/ Object firstvar = linkedlist.get(0); System.out.println("First element: " +firstvar); linkedlist.set(0, "Changed first item"); Object firstvar2 = linkedlist.get(0); System.out.println("First element after update by set method: " +firstvar2);
  • 233. Linked Lists Example /*Remove first and last element*/ linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); /* Add to a Position and remove from a position*/ linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); }}
  • 234. Linked Lists Example - output /*Remove first and last element*/ linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); /* Add to a Position and remove from a position*/ linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); }}
  • 235. Sets The problem with linked lists is that they can have duplicate elements added, for sets, not duplicate elements can be added, and no order in which they are stored. See https://docs.oracle.com/javase/tutorial/collections/interfaces/set.ht ml
  • 236. Set Example import java.util.*; public class TreeSetDemo { public static void main(String[] args) { // Set example with implement TreeSet Set<String> s = new TreeSet<String>(); s.add("b"); s.add("a"); s.add("d"); s.add("c"); java.util.Iterator<String> it = s.iterator(); while (it.hasNext()) { String value = (String) it.next(); System.out.println("Value :" + value); }}}
  • 237. Set Example -output Value :a Value :b Value :c Value :d
  • 238. Maps A map has a key and value, a key can be duplicated, Each can only contain one value. See http://docs.oracle.com/javase/tutorial/collections/interfaces/map.ht ml A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
  • 239. Map Example import java.util.*; public class MapDemo { public static void main(String[] args) { Map<Integer, String> mp = new HashMap<Integer,String>(); mp.put(new Integer(2), "Two"); mp.put(new Integer(1), "One"); mp.put(new Integer(3), "Three"); mp.put(new Integer(4), "Four"); Set<?> st = mp.entrySet(); Iterator<?> it = st.iterator(); while (it.hasNext()) { Map.Entry m = (Map.Entry) it.next(); int key = (Integer) m.getKey(); String value = (String) m.getValue(); System.out.println("Key :" + key + " Value :" + value); }}} A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
  • 240. Map Example -- output Key :1 Value :One Key :2 Value :Two Key :3 Value :Three Key :4 Value :Four A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
  • 241. Similar to HashMaps are HashTables HashTables also use a key-value pair like HashMaps, except some differences given:
  • 242. HashTable Example import java.util.Enumeration; import java.util.Hashtable; public class HashtableDemo1 { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); Enumeration<String> e = ht.keys(); while (e.hasMoreElements()){ System.out.println(e.nextElement());}}} OUTPUT 3 2 1 A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
  • 243. Queues Queues are to put data elements into a particular order, normally First-In-First-Out (FIFO). There is no key needed. See https://en.wikipedia.org/wiki/Queue_%28abstract_data_type %29
  • 244. Queue Example import java.util.*; public class QueueDemo1 { private static Queue <String> queue; public static void main(String[] args) { queue = new PriorityQueue<String>(); queue.add("One"); queue.add("Two"); queue.add("Three"); Iterator<String> iterator = queue.iterator(); while(iterator.hasNext()){ String element = (String) iterator.next(); System.out.println(element);}}} OUTPUT One Two Three A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value
  • 246. JavaBeans JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. See https://en.wikipedia.org/wiki/JavaBeans
  • 247. JavaBean Example public class JavabeanDemo implements java.io.Serializable { private static final long serialVersionUID = 1L; private int id; private String name; public JavabeanDemo() { } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setName(String name) { this.name = name; }
  • 248. JavaBean Example public String getName() { return name; } public static void main(String args[]) { JavabeanDemo e = new JavabeanDemo();// object is created e.setName("JavaBean");// setting value to the object System.out.println(e.getName()); } } OUTPUT JavaBean
  • 250. Basic I/O Basic I/O is a necessity in Java as Java is dependent on files and directory structure. The purpose of this section is to show the student some of the power of Java when copying files and reading the directory structure. See http://docs.oracle.com/javase/tutorial/essential/io/index.html
  • 251. Strings  A String is an immutable object that contains an array of bytes or characters.  By immutable, it is meant that you cannot modify the String object. You can create new Strings from the object, and when a substring or the String is modified, it is actually creating a new String() object.  A Sample String, “test” is created and then re-created again with a different sequence of characters: String test = "You cannot change"; test = test.toLowerCase(); System.out.println(test);
  • 252. StringBuffer  Re-creating objects can add a lot of overhead to a program. Every time that a program is created, the program allocates the methods and variables of that object in memory.  A simpler method is to use the “StringBuffer” class.  The “StringBuffer” class allows its contents to be modified without creating a new class.  Notice in the following that I did not have to create a new object, the output was “egnahc tonnac uoY”: StringBuffer test = new StringBuffer("You cannot change"); test.reverse(); System.out.println(test);
  • 253. Strings  Even though Strings may have some additional overhead, there is a lot of manipulation that can be done with strings in string arithmetic, observe some of the following: String test ="You" + " cannot " + "change me"; int len = "You cannot change me".length(); test = " You "; test += "cannot "; test += "change me";
  • 254. StringTokenizer  The String class is great for a sequence of characters and the StringBuffer class is great for appending and inserting the sequence into the same class but what about tokens.  Tokens are how humans have the tendency to break characters into individual words, or tokens.  The “StringTokenizer”, from the “java.util” package is a utility for breaking down the words of a sentence. Here’s a snippet String str = "Java,is,Cool"; StringTokenizer st = new StringTokenizer(str, ","); while (st.hasMoreTokens()) { System.out.print(st.nextToken()+ " "); The Output is : Java is Cool
  • 255. Files  When programming Java, it is very important to understand file Input/Output (I/O).  The File class, java.io.File, is used for manipulating the file, while classes like Scanner and FileInputStream manage the file’s data.  The programs in Java have dependencies based on he file structure and works well with manipulation of various files.  While many languages like Perl and other scripting languages have many utilities for parsing and Regex, Java’s strength rely in its cross-platform GUI’s and data manipulation with the use of buffers and files.  Java, especially JEE, relies heavily on object serialization for when an object is saved to file or a database. And is heavily dependent on property files that define how the program is to run.
  • 256. Create a File import java.io.*; public class CreateAFile { public static void main(String[] argv) throws IOException { // Ensure that a filename (or something) was given in argv[0] if (argv.length == 0) { System.err.println("Usage: CreateAFile filename"); System.exit(1); } // If arg is filled then create that file for (int i = 0; i< argv.length; i++) { new File(argv[i]).createNewFile( ); } } }
  • 257. List a Directory with class “ls”  The File class can also be used for directory calls: // List the Directory "ls" public class ls { public static void main(String argh_my_aching_fingers[]) { String[] dir = new java.io.File(".").list( ); // Get list of names java.util.Arrays.sort(dir); // Sort it (see Recipe 7.8) for (int i=0; i<dir.length; i++) System.out.println(dir[i]); // Print the list } }  Running “ls” will print the directory.
  • 258. The Path The directory path defines where files will go on the computer. Being able to locate See http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
  • 259. Open a File import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReader { public static void main(String[] args) { try{ Scanner text = new Scanner( new File( "Test.txt" ) ); }catch(FileNotFoundException ex){ System.out.println("Error: " +ex.getMessage()); } } }
  • 260. File I/O & Strings import java.io.IOException; import java.nio.charset.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import static java.nio.file.StandardCopyOption.*; public class FileStringDemo { public static void main(String[] args) { Charset utf8 = StandardCharsets.UTF_8; List<String> lines = Arrays.asList("1st line", "2nd line"); byte[] data = { 1, 2, 3, 4, 5 };
  • 261. File I/O & Strings
  • 262. File I/O & Strings
  • 263. File I/O & Strings
  • 264. File I/O & Strings -- output
  • 265. Regular Expressions  Regular expressions is the process of matching a pattern in a string.  For example, the “.” matches any character, so the pattern “.at” matches can be used to match any three character string ending with "at", including "hat", "cat", and "bat".  Regular expressions can also be used with the “java.util.regex.Matcher” class, the Pattern class or even the string.  By comparing the patterns in a string, input can be validated to match proper input.  See https://docs.oracle.com/javase/tutorial/essential/regex/  The following code snippet shows how to check a zip string so that it matches 5 digits, of course this string passes: String zip = “80120”; if(zip.matches("d{5}") == false) System.out.println("Error: zip code");
  • 266. Regex Example import java.util.ArrayList; import java.util.List; public class ValidateDemo { public static void main(String[] args) { List<String> input = new ArrayList<String>(); input.add("123-45-6789"); input.add("9876-5-4321"); input.add("987-65-4321 (attack)"); input.add("987-65-4321 "); input.add("192-83-7465"); for (String ssn : input) { if (ssn.matches("^(d{3}-?d{2}-?d{4})$")) { System.out.println("Found good SSN: " + ssn);}}}} linkedlist.add(0, "Newly added item"); linkedlist.remove(2); System.out.println("Final Content: " +linkedlist); }}
  • 267. Regex Example -- output Found good SSN: 123-45-6789 Found good SSN: 192-83-7465
  • 269. Generics Generics all programming to be developed generically for types, while the types are specified at runtime. This allows you to use the same code for different types. See https://en.wikipedia.org/wiki/Generics_in_Java and http://docs.oracle.com/javase/tutorial/java/generics/why.html
  • 270. Generic Example public static void main(String args[]) { GenericDemo1 type = new GenericDemo1(); type.set("Type Set"); String str = (String) type.get(); // type casting, error prone and can // cause ClassCastException } }
  • 271. Generic Example public static void main(String args[]) { GenericDemo1 type = new GenericDemo1(); type.set("Type Set"); String str = (String) type.get(); // type casting, error prone and can // cause ClassCastException } }
  • 272. Generic Example -- output Type Set
  • 274. Design Patterns A reusable design, template or recipe to resolve a repeatable software pattern. These patterns are an abstract way to describe coding techniques. See http://en.wikipedia.org/wiki/Software_design_pattern
  • 275. Singleton There can only be one instance of the object. Common uses are logging, where a connection is maintained to log data. See http://en.wikipedia.org/wiki/Singleton_pattern
  • 276. Singleton - example public class Singleton { private static ClassicSingleton instance; public static void main(String[] args) { // Will only retrieve a single instance of the class setInstance(ClassicSingleton.getInstance()); setInstance(ClassicSingleton.getInstance()); } public static ClassicSingleton getInstance() { return instance; }
  • 277. Singleton - example public static void setInstance(ClassicSingleton instance) { Singleton.instance = instance; } } class ClassicSingleton { private static ClassicSingleton instance = null; protected ClassicSingleton() { // Exists only to defeat instantiation. } public static ClassicSingleton getInstance() { if (instance == null) { instance = new ClassicSingleton(); } return instance; } }
  • 278. Singleton - example public static ClassicSingleton getInstance() { if (instance == null) { System.out.println("Create Instance"); instance = new ClassicSingleton(); } return instance; } }
  • 279. Singleton - example -- output Create Instance