java basics m taimoor khan [email protected]
TRANSCRIPT
Java BasicsM Taimoor Khan
Content• Java language syntax• Structure of Java programs• Creating a Java program• Documentation, why it is important• Reading and writing from the console
2
Important• Java is cAsE sensitive• A semicolon “;” is used to indicate the end of a
statement ( VB is different)• Braces , “{“ & “}” are often used to create blocks
of code
3
• All code is written in a class• A program will have at least one class and may
use many other classes• Classes are written by programmers• Many classes are supplied with Java• The program will start running with a class that
contains a special methodpublic static void main (String args[])
4
Hello World
5
Execution will start with this statement
Comments
6
Comments may appear in blocks/** indicates start of comment*/ indicates end of comment All methods should have comments that describe what they do
Comments may also appear at the end of a line of codeThese comments use two slashes // to indicate a start of comment.
Defining a class
7
A class is defined by the key word “class”
A class has a name.By convention starts with a capital letter and each new word is also capitalised(Look up the syntax rules)
The first brace indicates where the class begins
The last “matching” brace indicates where the class ends
Methods
8
Methods have an opening brace “{“
A class will normally contain many methods. These are the same as functions and procedures.This class has one method
Methods start with a method signature.
A closing brace “}”
A number of statements each terminated by a “;” semicolon
• import java.awt.*;• /**• * A square that can be manipulated and that draws itself on a canvas.• * • * @author Michael Kolling and David J. Barnes• * @version 2008.03.30• */• public class Square• {• private int size;• private int xPosition;• private int yPosition;• private String color;• private boolean isVisible;• /**• * Create a new square at default position with default color.• */• public Square()• {• size = 30;• xPosition = 60;• yPosition = 50;• color = "red";• isVisible = false;• }
9
Knows about other classes
Have a class header that describes the class
Have instance variables that hold data for this class
Have a constructor
Have many methods, not shown
Structure within a class
• Attributes, (what the class knows about)o Defined as variables
• Data used within the class only (use private)• Can be used externally (provide accessor or make public)
• Operations, (the things the class does)• Defined in methods (Functions & Procedures)
o Classified as accessor methods or mutator methods
• Constructorso Used when we create objects based on a class
10Should be cohesive
A Program works with many classes
11
A class that has a public static void main methodThe place where the program starts
Other classes written by you
classes written by other programmers
classes that come with Java
Breaking a program into classes helps us understand our programs better.“Like behaviour” can be grouped into classes
Variables• Most programs manipulate data. • Data must be stored while the program is
running• We use variables to store the data • Look at the tutorial
o http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.htmlbyte -128 +127
short -32768 +32767int -2147483648 2147483647 DEFAULT CHOICE FOR INTEGERSlong -9223372036854775808 +9223372036854775807float 32 bit floating point numberdouble 64 bit floating point numberboolean true falsechar '\u0000' \uFFFF' 16 bit unicode
\Use BigDecimal for currency
12
String ClassString str = "abc";
How do I find out more about String?
Look at the APIo http://java.sun.com/javase/6/docs/api/java/lang/String.ht
ml
Do a java tutorialo http://java.sun.com/docs/books/tutorial/java/data/strings.html
13
“Strings are constant; their values cannot be changed after they are created”
Declaring variables and assigning
valuesLocal variables – (located inside methods)
boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;
Instance variables - (inside a class, but not in a method)public char capitalC = 'C'; private byte b = 100;
Parameterspublic void myProcedure(int i,String r)
14
Note use of public or private – Very Important. We will talk about scope often.
This method has two parameters
Variables – Different types
• Instance Variableso Available when an object is created
• Class Variableso Declared with a static modifier
• Local Variableso Declared within methods
• Parameterso Declared as part of method signature
15
These are different from instance variables
Arguments are sent to methods
Arrays
16
Source: Sun Java Tutorials
Functions & Parameters
17
for Loop
18
while Loop
19
do Loop
20
if
21
if …else
22
switch
23
if ….elseif …..else
24
Reading from the Console
• Independent researcho http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.htmlo http://www.cs.utexas.edu/users/ndale/Scanner.htmlo http://www.java-tips.org/java-se-tips/java.util/scanning-text-with-java.ut
il.scanner-3.htmlo http://www.cs.utk.edu/~cs365/examples/datacheck.html
25
The “.” , what does it mean?
• "the dot" connects classes and objects to members. o when you are connecting an object reference variable to a
method. o when you are connecting a class name to one of its static
fields. “An example of this is the dot between "System" and "out" in
the statements we use to print stuff to the console window. System is the name of a class included in every Java implementation. It has an object reference variable that points to a PrintStream object for the console. So, "System.out.println( "text") invokes the println() method of the System.out object.”
• Source : http://www.bfoit.org/Intro_to_Programming/JavaOperators.html
26Are there any other uses of the “.” operator?
Pass by value or by reference?
• http://javadude.com/articles/passbyvalue.htmIntroductiono Pass-by-value
• “The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it)
o Pass-by-reference• “The formal parameter merely acts as an alias for the actual
parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.”
• Java is strictly pass-by-value27
Scope• What does scope mean?
o Restricting what code has access to variables, methods and classes
• Why do we care about it?o Poor scope means our programs
• may become corrupted or vulnerable• May not run as expected
• How do we set scope?o Use an access modifier public, privateo By being careful about
• where we declare variables and methods• how we declare variables and methods
28
How can you document your code?
• Class Header• Class Name• Variables names• Method names• Method headers• Comments in code ( Block and Line )• Comment to Javadoc standard• Run Javadoc software
29
Why is documentation vital?
• Maintenance of code is very costlyo Improve or modifyo Fix bugs
• What is obvious now will not be in one months time
• Makes the code easier to reuse• Makes the code easier to understand• Gets you better marks
30
References• http://java.sun.com/docs/books/tutorial/getStarted/applicati
on/index.html• http://java.sun.com/docs/books/tutorial/java/nutsandbolts/a
rrays.html• http://java.sun.com/docs/books/tutorial/java/nutsandbolts/d
atatypes.html• http://webclass.superquest.net/apjava/JavaNotes• Escape sequences
o http://www.cerritos.edu/jwilson/cis_182/Language_Resources/Java_Escape_Sequences.htm
• Code Conventionso http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.ht
ml• Java 6 API
o http://java.sun.com/javase/6/docs/api/
31