SlideShare una empresa de Scribd logo
1 de 42
Descargar para leer sin conexión
1 © 2001-2003 Marty Hall, Larry Brown: http://www.corewebprogramming.com
core
programming
Basic Java Syntax
Basic Java Syntax2 www.corewebprogramming.com
Agenda
• Creating, compiling, and executing simple
Java programs
• Accessing arrays
• Looping
• Using if statements
• Comparing strings
• Building arrays
– One-step process
– Two-step process
• Using multidimensional arrays
• Manipulating data structures
• Handling errors
Basic Java Syntax3 www.corewebprogramming.com
Getting Started
• Name of file must match name of class
– It is case sensitive, even on Windows
• Processing starts in main
– public static void main(String[] args)
– Routines usually called “methods,” not “functions.”
• Printing is done with System.out
– System.out.println, System.out.print
• Compile with “javac”
– Open DOS window; work from there
– Supply full case-sensitive file name (with file extension)
• Execute with “java”
– Supply base class name (no file extension)
Basic Java Syntax4 www.corewebprogramming.com
Example
• File: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world.");
}
}
• Compiling
DOS> javac HelloWorld.java
• Executing
DOS> java HelloWorld
Hello, world.
Basic Java Syntax5 www.corewebprogramming.com
More Basics
• Use + for string concatenation
• Arrays are accessed with []
– Array indices are zero-based
– The argument to main is an array of strings that
correspond to the command line arguments
• args[0] returns first command-line argument
• args[1] returns second command-line argument
• Etc.
• The length field gives the number of
elements in an array
– Thus, args.length gives the number of command-
line arguments
– Unlike in C/C++, the name of the program is not inserted
into the command-line arguments
Basic Java Syntax6 www.corewebprogramming.com
Example
• File: ShowTwoArgs.java
public class ShowTwoArgs {
public static void main(String[] args) {
System.out.println("First arg: " +
args[0]);
System.out.println("Second arg: " +
args[1]);
}
}
Basic Java Syntax7 www.corewebprogramming.com
Example (Continued)
• Compiling
DOS> javac ShowTwoArgs.java
• Executing
DOS> java ShowTwoArgs Hello World
First args Hello
Second arg: Class
DOS> java ShowTwoArgs
[Error message]
Basic Java Syntax8 www.corewebprogramming.com
Looping Constructs
• while
while (continueTest) {
body;
}
• do
do {
body;
} while (continueTest);
• for
for(init; continueTest; updateOp) {
body;
}
Basic Java Syntax9 www.corewebprogramming.com
While Loops
public static void listNums1(int max) {
int i = 0;
while (i <= max) {
System.out.println("Number: " + i);
i++; // "++" means "add one"
}
}
Basic Java Syntax10 www.corewebprogramming.com
Do Loops
public static void listNums2(int max) {
int i = 0;
do {
System.out.println("Number: " + i);
i++;
} while (i <= max);
// ^ Don’t forget semicolon
}
Basic Java Syntax11 www.corewebprogramming.com
For Loops
public static void listNums3(int max) {
for(int i=0; i<max; i++) {
System.out.println("Number: " + i);
}
}
Basic Java Syntax12 www.corewebprogramming.com
Aside: Defining Multiple
Methods in Single Class
public class LoopTest {
public static void main(String[] args) {
listNums1(5);
listNums2(6);
listNums3(7);
}
public static void listNums1(int max) {…}
public static void listNums2(int max) {…}
public static void listNums3(int max) {…}
}
Basic Java Syntax13 www.corewebprogramming.com
Loop Example
• File ShowArgs.java:
public class ShowArgs {
public static void main(String[] args) {
for(int i=0; i<args.length; i++) {
System.out.println("Arg " + i +
" is " +
args[i]);
}
}
}
Basic Java Syntax14 www.corewebprogramming.com
If Statements
• Single Option
if (boolean-expression) {
statement;
}
• Multiple Options
if (boolean-expression) {
statement1;
} else {
statement2;
}
Basic Java Syntax15 www.corewebprogramming.com
Boolean Operators
• ==, !=
– Equality, inequality. In addition to comparing primitive
types, == tests if two objects are identical (the same
object), not just if they appear equal (have the same
fields). More details when we introduce objects.
• <, <=, >, >=
– Numeric less than, less than or equal to, greater than,
greater than or equal to.
• &&, ||
– Logical AND, OR. Both use short-circuit evaluation to
more efficiently compute the results of complicated
expressions.
• !
– Logical negation.
Basic Java Syntax16 www.corewebprogramming.com
Example: If Statements
public static int max2(int n1, int n2) {
if (n1 >= n2)
return(n1);
else
return(n2);
}
Basic Java Syntax17 www.corewebprogramming.com
Strings
• String is a real class in Java, not an array of
characters as in C and C++.
• The String class has a shortcut method to
create a new object: just use double quotes
– This differs from normal objects, where you use the new
construct to build an object
• Use equals to compare strings
– Never use ==
Basic Java Syntax18 www.corewebprogramming.com
Strings: Common Error
public static void main(String[] args) {
String match = "Test";
if (args.length == 0) {
System.out.println("No args");
} else if (args[0] == match) {
System.out.println("Match");
} else {
System.out.println("No match");
}
}
• Prints "No match" for all inputs
– Fix:
if (args[0].equals(match))
Basic Java Syntax19 www.corewebprogramming.com
Building Arrays:
One-Step Process
• Declare and allocate array in one fell swoop
type[] var = { val1, val2, ... , valN };
• Examples:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2),
... };
Basic Java Syntax20 www.corewebprogramming.com
Building Arrays:
Two-Step Process
• Step 1: allocate an array of references:
type[] var = new type[size];
• Eg:
int[] values = new int[7];
Point[] points = new Point[someArray.length];
• Step 2: populate the array
points[0] = new Point(...);
points[1] = new Point(...);
...
Points[6] = new Point(…);
• If you fail to populate an entry
– Default value is 0 for numeric arrays
– Default value is null for object arrays
Basic Java Syntax21 www.corewebprogramming.com
Multidimensional Arrays
• Multidimensional arrays are implemented as
arrays of arrays
int[][] twoD = new int[64][32];
String[][] cats = { { "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted", "red-point" } };
• Note: the number of elements in each row (dimension)
need not be equal
int[][] irregular = { { 1 },
{ 2, 3, 4},
{ 5 },
{ 6, 7 } };
Basic Java Syntax22 www.corewebprogramming.com
TriangleArray: Example
public class TriangleArray {
public static void main(String[] args) {
int[][] triangle = new int[10][];
for(int i=0; i<triangle.length; i++) {
triangle[i] = new int[i+1];
}
for (int i=0; i<triangle.length; i++) {
for(int j=0; j<triangle[i].length; j++) {
System.out.print(triangle[i][j]);
}
System.out.println();
}
}
}
Basic Java Syntax23 www.corewebprogramming.com
TriangleArray: Result
> java TriangleArray
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
Basic Java Syntax24 www.corewebprogramming.com
Data Structures
• Java 1.0 introduced two synchronized data
structures in the java.util package
– Vector
• A strechable (resizeable) array of Objects
• Time to access an element is constant regardless of
position
• Time to insert element is proportional to the size of the
vector
• In Java 2 (eg JDK 1.2 and later), use ArrayList
– Hashtable
• Stores key-value pairs as Objects
• Neither the keys or values can be null
• Time to access/insert is constant
• In Java 2, use HashMap
Basic Java Syntax25 www.corewebprogramming.com
Useful Vector Methods
• addElement/insertElementAt/setElementAt
– Add elements to the vector
• removeElement/removeElementAt
– Removes an element from the vector
• firstElement/lastElement
– Returns a reference to the first and last element, respectively
(without removing)
• elementAt
– Returns the element at the specified index
• indexOf
– Returns the index of an element that equals the object specified
• contains
– Determines if the vector contains an object
Basic Java Syntax26 www.corewebprogramming.com
Useful Vector Methods
• elements
– Returns an Enumeration of objects in the vector
Enumeration elements = vector.elements();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
• size
– The number of elements in the vector
• capacity
– The number of elements the vector can hold before
becoming resized
Basic Java Syntax27 www.corewebprogramming.com
Useful Hashtable Methods
• put/get
– Stores or retrieves a value in the hashtable
• remove/clear
– Removes a particular entry or all entries from the hashtable
• containsKey/contains
– Determines if the hashtable contains a particular key or element
• keys/elements
– Returns an enumeration of all keys or elements, respectively
• size
– Returns the number of elements in the hashtable
• rehash
– Increases the capacity of the hashtable and reorganizes it
Basic Java Syntax28 www.corewebprogramming.com
Collections Framework
• Additional data structures added by Java 2
Platform
Collection
Set
SortedSet
List
ArrayList
LinkedList
Vector†
HashSet
TreeSet
Map
SortedMap
HashMap
Hashtable†
TreeMap
†Synchronized AccessInterface Concrete class
Basic Java Syntax29 www.corewebprogramming.com
Collection Interfaces
• Collection
– Abstract class for holding groups of objects
• Set
– Group of objects containing no duplicates
• SortedSet
– Set of objects (no duplicates) stored in ascending order
– Order is determined by a Comparator
• List
– Physically (versus logically) ordered sequence of objects
• Map
– Stores objects (unordered) identified by unique keys
• SortedMap
– Objects stored in ascending order based on their key value
– Neither duplicate or null keys are permitted
Basic Java Syntax30 www.corewebprogramming.com
Collections Class
• Use to create synchronized data structures
List list = Collection.synchronizedList(new ArrayList());
Map map = Collections.synchronizedMap(new HashMap());
• Provides useful (static) utility methods
– sort
• Sorts (ascending) the elements in the list
– max, min
• Returns the maximum or minimum element in the
collection
– reverse
• Reverses the order of the elements in the list
– shuffle
• Randomly permutes the order of the elements
Basic Java Syntax31 www.corewebprogramming.com
Wrapper Classes
• Each primitive data type has a
corresponding object (wrapper class)
– The data is stored as an immutable field of the object
Primitive Corresponding
Data Type Object Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Basic Java Syntax32 www.corewebprogramming.com
Wrapper Uses
• Defines useful constants for each data type
– For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
• Convert between data types
– Use parseXxx method to convert a String to the
corresponding primitive data type
try {
String value = "3.14e6";
Double d = Double.parseDouble(value);
} catch (NumberFormatException nfe) {
System.out.println("Can't convert: " + value);
}
Basic Java Syntax33 www.corewebprogramming.com
Wrappers: Converting Strings
Data Type Convert String using either …
byte Byte.parseByte(string )
new Byte(string ).byteValue()
short Short.parseShort(string )
new Short(string ).shortValue()
int Integer.parseInteger(string )
new Integer(string ).intValue()
long Long.parseLong(string )
new Long(string ).longValue()
float Float.parseFloat(string )
new Float(string ).floatValue()
double Double.parseDouble(string )
new Double(string ).doubleValue()
Basic Java Syntax34 www.corewebprogramming.com
Error Handling: Exceptions
• In Java, the error-handling system is based
on exceptions
– Exceptions must be handed in a try/catch block
– When an exception occurs, process flow is immediately
transferred to the catch block
• Basic Form
try {
statement1;
statement2;
...
} catch(SomeException someVar) {
handleTheException(someVar);
}
Basic Java Syntax35 www.corewebprogramming.com
Exception Hierarchy
• Simplified Diagram of Exception Hierarchy
Throwable
Exception Error
…
IOException RuntimeException
Basic Java Syntax36 www.corewebprogramming.com
Throwable Types
• Error
– A non-recoverable problem that should not be caught
(OutOfMemoryError, StackOverflowError, …)
• Exception
– An abnormal condition that should be caught and handled
by the programmer
• RuntimeException
– Special case; does not have to be caught
– Usually the result of a poorly written program (integer
division by zero, array out-of-bounds, etc.)
• A RuntimeException is considered a bug
Basic Java Syntax37 www.corewebprogramming.com
Multiple Catch Clauses
• A single try can have more that one catch
clause
– If multiple catch clauses are used, order them from the
most specific to the most general
– If no appropriate catch is found, the exception is
handed to any outer try blocks
• If no catch clause is found within the method, then the
exception is thrown by the method
try {
...
} catch (ExceptionType1 var1) {
// Do something
} catch (ExceptionType2 var2) {
// Do something else
}
Basic Java Syntax38 www.corewebprogramming.com
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
}
Basic Java Syntax39 www.corewebprogramming.com
The finally Clause
• After the final catch clause, an optional
finally clause may be defined
• The finally clause is always executed,
even if the try or catch blocks are exited
through a break, continue, or return
try {
...
} catch (SomeException someVar) {
// Do something
} finally {
// Always executed
}
Basic Java Syntax40 www.corewebprogramming.com
Thrown Exceptions
• If a potential exception is not handled in the
method, then the method must declare that
the exception can be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
– Note: Multiple exception types (comma separated) can be
declared in the throws clause
• Explicitly generating an exception
throw new IOException("Blocked by firewall.");
throw new MalformedURLException("Invalid protocol");
Basic Java Syntax41 www.corewebprogramming.com
Summary
• Loops, conditional statements, and array
access is the same as in C and C++
• String is a real class in Java
• Use equals, not ==, to compare strings
• You can allocate arrays in one step or in two
steps
• Vector or ArrayList is a useful data
structure
– Can hold an arbitrary number of elements
• Handle exceptions with try/catch blocks
42 © 2001-2003 Marty Hall, Larry Brown: http://www.corewebprogramming.com
core
programming
Questions?

Más contenido relacionado

La actualidad más candente

Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Jay Coskey
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207Jay Coskey
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LABHari Christian
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simpleleonsabr
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics modulemanikanta361
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 

La actualidad más candente (20)

Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Java 103
Java 103Java 103
Java 103
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simple
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Meet scala
Meet scalaMeet scala
Meet scala
 
4 gouping object
4 gouping object4 gouping object
4 gouping object
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 

Destacado

Introduction to java
Introduction to javaIntroduction to java
Introduction to javaASU Online
 
Lists, queues and stacks
Lists, queues and stacksLists, queues and stacks
Lists, queues and stacksASU Online
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsPragya Rastogi
 
Lists, queues and stacks 1
Lists, queues and stacks 1Lists, queues and stacks 1
Lists, queues and stacks 1ASU Online
 
Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarationssshhzap
 
Midterm common mistakes
Midterm common mistakesMidterm common mistakes
Midterm common mistakesASU Online
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
Introducción a CSS en XHTML
Introducción a CSS en XHTMLIntroducción a CSS en XHTML
Introducción a CSS en XHTMLOmar Sosa-Tzec
 
Future-proof Your Students
Future-proof Your StudentsFuture-proof Your Students
Future-proof Your Studentsbrianbelen
 
Lectores rss francisco_avila.
Lectores rss francisco_avila.Lectores rss francisco_avila.
Lectores rss francisco_avila.flavilab
 
Uhren mit Design - ausgezeichnet mit dem Red Dot Award
Uhren mit Design - ausgezeichnet mit dem Red Dot AwardUhren mit Design - ausgezeichnet mit dem Red Dot Award
Uhren mit Design - ausgezeichnet mit dem Red Dot Awardred-dot-award
 
Newsletter September
Newsletter SeptemberNewsletter September
Newsletter SeptembermrBanerjee
 
TwEVS - An idea for using twitter as a student owned electronic voting system
TwEVS - An idea for using twitter as a student owned electronic voting systemTwEVS - An idea for using twitter as a student owned electronic voting system
TwEVS - An idea for using twitter as a student owned electronic voting systemMartin Hawksey
 
The Magic Of Love
The Magic Of LoveThe Magic Of Love
The Magic Of LoveMihaela
 

Destacado (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Lists, queues and stacks
Lists, queues and stacksLists, queues and stacks
Lists, queues and stacks
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Lists, queues and stacks 1
Lists, queues and stacks 1Lists, queues and stacks 1
Lists, queues and stacks 1
 
Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarations
 
Midterm common mistakes
Midterm common mistakesMidterm common mistakes
Midterm common mistakes
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Spacemy.Pps
Spacemy.PpsSpacemy.Pps
Spacemy.Pps
 
Introducción a CSS en XHTML
Introducción a CSS en XHTMLIntroducción a CSS en XHTML
Introducción a CSS en XHTML
 
Normas.resumo[1]
Normas.resumo[1]Normas.resumo[1]
Normas.resumo[1]
 
Állat01
Állat01Állat01
Állat01
 
Future-proof Your Students
Future-proof Your StudentsFuture-proof Your Students
Future-proof Your Students
 
412 an 29_janeiro_2013.ok
412 an 29_janeiro_2013.ok412 an 29_janeiro_2013.ok
412 an 29_janeiro_2013.ok
 
Lectores rss francisco_avila.
Lectores rss francisco_avila.Lectores rss francisco_avila.
Lectores rss francisco_avila.
 
Genesis Wellness Centre Presentation
Genesis Wellness Centre PresentationGenesis Wellness Centre Presentation
Genesis Wellness Centre Presentation
 
Vodafone Club 2020
Vodafone Club 2020Vodafone Club 2020
Vodafone Club 2020
 
Uhren mit Design - ausgezeichnet mit dem Red Dot Award
Uhren mit Design - ausgezeichnet mit dem Red Dot AwardUhren mit Design - ausgezeichnet mit dem Red Dot Award
Uhren mit Design - ausgezeichnet mit dem Red Dot Award
 
Newsletter September
Newsletter SeptemberNewsletter September
Newsletter September
 
TwEVS - An idea for using twitter as a student owned electronic voting system
TwEVS - An idea for using twitter as a student owned electronic voting systemTwEVS - An idea for using twitter as a student owned electronic voting system
TwEVS - An idea for using twitter as a student owned electronic voting system
 
The Magic Of Love
The Magic Of LoveThe Magic Of Love
The Magic Of Love
 

Similar a 4java Basic Syntax

06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VIHari Christian
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesAndrey Karpov
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMERAndrey Karpov
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Top 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetTop 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetDevLabs Alliance
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...Howard Greenberg
 

Similar a 4java Basic Syntax (20)

Java introduction
Java introductionJava introduction
Java introduction
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java
Java Java
Java
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutes
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Collection
CollectionCollection
Collection
 
Top 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdetTop 20 java programming interview questions for sdet
Top 20 java programming interview questions for sdet
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 

Más de Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

Más de Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Último

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

4java Basic Syntax

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown: http://www.corewebprogramming.com core programming Basic Java Syntax
  • 2. Basic Java Syntax2 www.corewebprogramming.com Agenda • Creating, compiling, and executing simple Java programs • Accessing arrays • Looping • Using if statements • Comparing strings • Building arrays – One-step process – Two-step process • Using multidimensional arrays • Manipulating data structures • Handling errors
  • 3. Basic Java Syntax3 www.corewebprogramming.com Getting Started • Name of file must match name of class – It is case sensitive, even on Windows • Processing starts in main – public static void main(String[] args) – Routines usually called “methods,” not “functions.” • Printing is done with System.out – System.out.println, System.out.print • Compile with “javac” – Open DOS window; work from there – Supply full case-sensitive file name (with file extension) • Execute with “java” – Supply base class name (no file extension)
  • 4. Basic Java Syntax4 www.corewebprogramming.com Example • File: HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world."); } } • Compiling DOS> javac HelloWorld.java • Executing DOS> java HelloWorld Hello, world.
  • 5. Basic Java Syntax5 www.corewebprogramming.com More Basics • Use + for string concatenation • Arrays are accessed with [] – Array indices are zero-based – The argument to main is an array of strings that correspond to the command line arguments • args[0] returns first command-line argument • args[1] returns second command-line argument • Etc. • The length field gives the number of elements in an array – Thus, args.length gives the number of command- line arguments – Unlike in C/C++, the name of the program is not inserted into the command-line arguments
  • 6. Basic Java Syntax6 www.corewebprogramming.com Example • File: ShowTwoArgs.java public class ShowTwoArgs { public static void main(String[] args) { System.out.println("First arg: " + args[0]); System.out.println("Second arg: " + args[1]); } }
  • 7. Basic Java Syntax7 www.corewebprogramming.com Example (Continued) • Compiling DOS> javac ShowTwoArgs.java • Executing DOS> java ShowTwoArgs Hello World First args Hello Second arg: Class DOS> java ShowTwoArgs [Error message]
  • 8. Basic Java Syntax8 www.corewebprogramming.com Looping Constructs • while while (continueTest) { body; } • do do { body; } while (continueTest); • for for(init; continueTest; updateOp) { body; }
  • 9. Basic Java Syntax9 www.corewebprogramming.com While Loops public static void listNums1(int max) { int i = 0; while (i <= max) { System.out.println("Number: " + i); i++; // "++" means "add one" } }
  • 10. Basic Java Syntax10 www.corewebprogramming.com Do Loops public static void listNums2(int max) { int i = 0; do { System.out.println("Number: " + i); i++; } while (i <= max); // ^ Don’t forget semicolon }
  • 11. Basic Java Syntax11 www.corewebprogramming.com For Loops public static void listNums3(int max) { for(int i=0; i<max; i++) { System.out.println("Number: " + i); } }
  • 12. Basic Java Syntax12 www.corewebprogramming.com Aside: Defining Multiple Methods in Single Class public class LoopTest { public static void main(String[] args) { listNums1(5); listNums2(6); listNums3(7); } public static void listNums1(int max) {…} public static void listNums2(int max) {…} public static void listNums3(int max) {…} }
  • 13. Basic Java Syntax13 www.corewebprogramming.com Loop Example • File ShowArgs.java: public class ShowArgs { public static void main(String[] args) { for(int i=0; i<args.length; i++) { System.out.println("Arg " + i + " is " + args[i]); } } }
  • 14. Basic Java Syntax14 www.corewebprogramming.com If Statements • Single Option if (boolean-expression) { statement; } • Multiple Options if (boolean-expression) { statement1; } else { statement2; }
  • 15. Basic Java Syntax15 www.corewebprogramming.com Boolean Operators • ==, != – Equality, inequality. In addition to comparing primitive types, == tests if two objects are identical (the same object), not just if they appear equal (have the same fields). More details when we introduce objects. • <, <=, >, >= – Numeric less than, less than or equal to, greater than, greater than or equal to. • &&, || – Logical AND, OR. Both use short-circuit evaluation to more efficiently compute the results of complicated expressions. • ! – Logical negation.
  • 16. Basic Java Syntax16 www.corewebprogramming.com Example: If Statements public static int max2(int n1, int n2) { if (n1 >= n2) return(n1); else return(n2); }
  • 17. Basic Java Syntax17 www.corewebprogramming.com Strings • String is a real class in Java, not an array of characters as in C and C++. • The String class has a shortcut method to create a new object: just use double quotes – This differs from normal objects, where you use the new construct to build an object • Use equals to compare strings – Never use ==
  • 18. Basic Java Syntax18 www.corewebprogramming.com Strings: Common Error public static void main(String[] args) { String match = "Test"; if (args.length == 0) { System.out.println("No args"); } else if (args[0] == match) { System.out.println("Match"); } else { System.out.println("No match"); } } • Prints "No match" for all inputs – Fix: if (args[0].equals(match))
  • 19. Basic Java Syntax19 www.corewebprogramming.com Building Arrays: One-Step Process • Declare and allocate array in one fell swoop type[] var = { val1, val2, ... , valN }; • Examples: int[] values = { 10, 100, 1000 }; Point[] points = { new Point(0, 0), new Point(1, 2), ... };
  • 20. Basic Java Syntax20 www.corewebprogramming.com Building Arrays: Two-Step Process • Step 1: allocate an array of references: type[] var = new type[size]; • Eg: int[] values = new int[7]; Point[] points = new Point[someArray.length]; • Step 2: populate the array points[0] = new Point(...); points[1] = new Point(...); ... Points[6] = new Point(…); • If you fail to populate an entry – Default value is 0 for numeric arrays – Default value is null for object arrays
  • 21. Basic Java Syntax21 www.corewebprogramming.com Multidimensional Arrays • Multidimensional arrays are implemented as arrays of arrays int[][] twoD = new int[64][32]; String[][] cats = { { "Caesar", "blue-point" }, { "Heather", "seal-point" }, { "Ted", "red-point" } }; • Note: the number of elements in each row (dimension) need not be equal int[][] irregular = { { 1 }, { 2, 3, 4}, { 5 }, { 6, 7 } };
  • 22. Basic Java Syntax22 www.corewebprogramming.com TriangleArray: Example public class TriangleArray { public static void main(String[] args) { int[][] triangle = new int[10][]; for(int i=0; i<triangle.length; i++) { triangle[i] = new int[i+1]; } for (int i=0; i<triangle.length; i++) { for(int j=0; j<triangle[i].length; j++) { System.out.print(triangle[i][j]); } System.out.println(); } } }
  • 23. Basic Java Syntax23 www.corewebprogramming.com TriangleArray: Result > java TriangleArray 0 00 000 0000 00000 000000 0000000 00000000 000000000 0000000000
  • 24. Basic Java Syntax24 www.corewebprogramming.com Data Structures • Java 1.0 introduced two synchronized data structures in the java.util package – Vector • A strechable (resizeable) array of Objects • Time to access an element is constant regardless of position • Time to insert element is proportional to the size of the vector • In Java 2 (eg JDK 1.2 and later), use ArrayList – Hashtable • Stores key-value pairs as Objects • Neither the keys or values can be null • Time to access/insert is constant • In Java 2, use HashMap
  • 25. Basic Java Syntax25 www.corewebprogramming.com Useful Vector Methods • addElement/insertElementAt/setElementAt – Add elements to the vector • removeElement/removeElementAt – Removes an element from the vector • firstElement/lastElement – Returns a reference to the first and last element, respectively (without removing) • elementAt – Returns the element at the specified index • indexOf – Returns the index of an element that equals the object specified • contains – Determines if the vector contains an object
  • 26. Basic Java Syntax26 www.corewebprogramming.com Useful Vector Methods • elements – Returns an Enumeration of objects in the vector Enumeration elements = vector.elements(); while(elements.hasMoreElements()) { System.out.println(elements.nextElement()); } • size – The number of elements in the vector • capacity – The number of elements the vector can hold before becoming resized
  • 27. Basic Java Syntax27 www.corewebprogramming.com Useful Hashtable Methods • put/get – Stores or retrieves a value in the hashtable • remove/clear – Removes a particular entry or all entries from the hashtable • containsKey/contains – Determines if the hashtable contains a particular key or element • keys/elements – Returns an enumeration of all keys or elements, respectively • size – Returns the number of elements in the hashtable • rehash – Increases the capacity of the hashtable and reorganizes it
  • 28. Basic Java Syntax28 www.corewebprogramming.com Collections Framework • Additional data structures added by Java 2 Platform Collection Set SortedSet List ArrayList LinkedList Vector† HashSet TreeSet Map SortedMap HashMap Hashtable† TreeMap †Synchronized AccessInterface Concrete class
  • 29. Basic Java Syntax29 www.corewebprogramming.com Collection Interfaces • Collection – Abstract class for holding groups of objects • Set – Group of objects containing no duplicates • SortedSet – Set of objects (no duplicates) stored in ascending order – Order is determined by a Comparator • List – Physically (versus logically) ordered sequence of objects • Map – Stores objects (unordered) identified by unique keys • SortedMap – Objects stored in ascending order based on their key value – Neither duplicate or null keys are permitted
  • 30. Basic Java Syntax30 www.corewebprogramming.com Collections Class • Use to create synchronized data structures List list = Collection.synchronizedList(new ArrayList()); Map map = Collections.synchronizedMap(new HashMap()); • Provides useful (static) utility methods – sort • Sorts (ascending) the elements in the list – max, min • Returns the maximum or minimum element in the collection – reverse • Reverses the order of the elements in the list – shuffle • Randomly permutes the order of the elements
  • 31. Basic Java Syntax31 www.corewebprogramming.com Wrapper Classes • Each primitive data type has a corresponding object (wrapper class) – The data is stored as an immutable field of the object Primitive Corresponding Data Type Object Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean
  • 32. Basic Java Syntax32 www.corewebprogramming.com Wrapper Uses • Defines useful constants for each data type – For example, Integer.MAX_VALUE Float.NEGATIVE_INFINITY • Convert between data types – Use parseXxx method to convert a String to the corresponding primitive data type try { String value = "3.14e6"; Double d = Double.parseDouble(value); } catch (NumberFormatException nfe) { System.out.println("Can't convert: " + value); }
  • 33. Basic Java Syntax33 www.corewebprogramming.com Wrappers: Converting Strings Data Type Convert String using either … byte Byte.parseByte(string ) new Byte(string ).byteValue() short Short.parseShort(string ) new Short(string ).shortValue() int Integer.parseInteger(string ) new Integer(string ).intValue() long Long.parseLong(string ) new Long(string ).longValue() float Float.parseFloat(string ) new Float(string ).floatValue() double Double.parseDouble(string ) new Double(string ).doubleValue()
  • 34. Basic Java Syntax34 www.corewebprogramming.com Error Handling: Exceptions • In Java, the error-handling system is based on exceptions – Exceptions must be handed in a try/catch block – When an exception occurs, process flow is immediately transferred to the catch block • Basic Form try { statement1; statement2; ... } catch(SomeException someVar) { handleTheException(someVar); }
  • 35. Basic Java Syntax35 www.corewebprogramming.com Exception Hierarchy • Simplified Diagram of Exception Hierarchy Throwable Exception Error … IOException RuntimeException
  • 36. Basic Java Syntax36 www.corewebprogramming.com Throwable Types • Error – A non-recoverable problem that should not be caught (OutOfMemoryError, StackOverflowError, …) • Exception – An abnormal condition that should be caught and handled by the programmer • RuntimeException – Special case; does not have to be caught – Usually the result of a poorly written program (integer division by zero, array out-of-bounds, etc.) • A RuntimeException is considered a bug
  • 37. Basic Java Syntax37 www.corewebprogramming.com Multiple Catch Clauses • A single try can have more that one catch clause – If multiple catch clauses are used, order them from the most specific to the most general – If no appropriate catch is found, the exception is handed to any outer try blocks • If no catch clause is found within the method, then the exception is thrown by the method try { ... } catch (ExceptionType1 var1) { // Do something } catch (ExceptionType2 var2) { // Do something else }
  • 38. Basic Java Syntax38 www.corewebprogramming.com Try-Catch, Example ... BufferedReader in = null; String lineIn; try { in = new BufferedReader(new FileReader("book.txt")); while((lineIn = in.readLine()) != null) { System.out.println(lineIn); } in.close(); } catch (FileNotFoundException fnfe ) { System.out.println("File not found."); } catch (EOFException eofe) { System.out.println("Unexpected End of File."); } catch (IOException ioe) { System.out.println("IOError reading input: " + ioe); ioe.printStackTrace(); // Show stack dump }
  • 39. Basic Java Syntax39 www.corewebprogramming.com The finally Clause • After the final catch clause, an optional finally clause may be defined • The finally clause is always executed, even if the try or catch blocks are exited through a break, continue, or return try { ... } catch (SomeException someVar) { // Do something } finally { // Always executed }
  • 40. Basic Java Syntax40 www.corewebprogramming.com Thrown Exceptions • If a potential exception is not handled in the method, then the method must declare that the exception can be thrown public SomeType someMethod(...) throws SomeException { // Unhandled potential exception ... } – Note: Multiple exception types (comma separated) can be declared in the throws clause • Explicitly generating an exception throw new IOException("Blocked by firewall."); throw new MalformedURLException("Invalid protocol");
  • 41. Basic Java Syntax41 www.corewebprogramming.com Summary • Loops, conditional statements, and array access is the same as in C and C++ • String is a real class in Java • Use equals, not ==, to compare strings • You can allocate arrays in one step or in two steps • Vector or ArrayList is a useful data structure – Can hold an arbitrary number of elements • Handle exceptions with try/catch blocks
  • 42. 42 © 2001-2003 Marty Hall, Larry Brown: http://www.corewebprogramming.com core programming Questions?