Java Basics - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

Java Basics

Description:

This is what runs when you run your Java program from the command line ... Main methods in java are always void they never return any data. ... – PowerPoint PPT presentation

Number of Views:1032
Avg rating:3.0/5.0
Slides: 30
Provided by: chrisf2
Category:
Tags: basics | java

less

Transcript and Presenter's Notes

Title: Java Basics


1
Java Basics
  • Syntax is similar to C, but
  • -Hard-to-use and error prone features
    removed
  • -More compiler error checking
  • -Error handling built in from start
  • -Inheritance is much neater
  • -Large, standard, portable API

2
Whats completely gone
  • Pointers (kinda), Pointer arithmetic
  • Preprocessor
  • Enums and typedefs
  • Passing by reference
  • Goto (not that this should ever be used in C)
  • operator, include statements
  • Global functions and variables
  • Operator overloading, templates, Multiple
    Inheritance

3
Whats New
  • Compiler now does a conservative flow analysis
    (makes sure variables are initialized with values
    and return values are assigned)
  • First rate exception handling (more on this
    later)
  • Automatic Garbage collection
  • Objects accessed by reference variables (which
    are really just pointers)
  • Multithreaded is easier than in other languages
    and its built right in (its sometimes overused)
  • Network programming very easy

4
A Simple Java Program
  • Lets look at a really simple Java
    programimport java.io.
  • public class HelloWorld
  • public static void main(String args)
  • System.out.println(Hello World!)

5
A Simple Java Program
  • Everything in Java lives inside of a class. In
    the previous case, the class was HelloWorld, and
    everything inside the belongs to that class.
  • There should only be one public class per file
  • The filename must match the public class name.
    So in the previous example, the appropriate
    filename for that program would be
    HelloWorld.java

6
The main method
  • This is what runs when you run your Java program
    from the command line
  • Not all classes have mains Applets in particular
    do not (more on Applets later)
  • Main methods in java are always void they never
    return any data.
  • The (String args) is a String array of
    arguments passed in from the command line. Well
    see how to use this shortly, but for now, just
    realize that this has to be there.

7
Comments in Java
  • Commenting in Java (and I expect lots of use of
    it) is just like in C // This is a single
    line comment
  • / This is a
  • multiple line comment /
  • / This is a javadoc comment
  • more on this later /

8
Import directives
  • No C like includes in Java
  • import directive sort of like Cs using
    directive, creates sort hand to point to a
    library. Forinstance,
  • import java.util.Date
  • Date thisdate new Date()
  • // These basically do the same thing
  • java.util.Date thatDatenew
    java.util.Date()

9
Java Data Types
  • Unlike other languages, Javas data types are
    defined by the language itself, not the
    platform/compiler.
  • These primitives types (except for String) are
    not objects.
  • For the primitives types that are not objects,
    there are wrapper classes.
  • All integral data types are signed.

10
Java Integer Datatypes
  • byte (1 byte, -128 127)
  • short (2 bytes, -32,768 32,767)
  • int (4 bytes, -2,147,483,648 2,147,483,647)
  • long (8 bytes. Im not writing the numbers out
    ? )
  • These can be specified in special bases (decimal,
    octal, hex), if necessary.

11
Java Floating Point Datatypes
  • Double
  • 8 bytes
  • 15 significant digis
  • Denoted by d or D suffix (or no suffix)
  • Float
  • 4 bytes
  • 6.5 significant digits
  • Denoted by f or F suffix

12
Other Java datatypes
  • boolean false or true values
  • char 2 bytes in Java (unicode)
  • chars can include certain useful escape
    sequences, such as /n (newline) /r (return)
    and /t (tab)

13
Declaring variables in Java
  • Similar to C
  • int a
  • char b
  • double c,d
  • Variable names must start with a letter and can
    be any length.
  • int thisIsAnInteger
  • Variables can be declared with initalization
  • boolean willIPassThisClasstrue //hopefully

14
Constants in Java
  • Constants in Java are declared just like normal
    variables, but are prefixed with the keyword
    final
  • final int example5
  • By coding convention, all constants should be
    UPPERCASE.
  • final int FEET_PER_MILE5280
  • Software Engineering Tip Constants that need to
    be accessed by throughout the class should be
    declared outside any methods (but inside the
    class itself) and be declared as static and
    final.
  • static final int FEET_PER_YARD3

15
Operators
  • Again, very similar to C
  • Arithmetic , -, , /, and .
  • Prefix and postfix and --.
  • Boolean , !, , , , and .
  • Bitwise , , , and .
  • Arithmetic shift .
  • Logical shift .

16
High level math functions
  • Built-in High level math functions are built into
    the Math class
  • All statics, called by Math.sin(1)
  • Functions like ceil, round, sin
  • Constants like Pi and E

17
Java Strings
  • Built-in String class for immutable character
    strings
  • Class provides lots of methods, including
  • char charAt(int index)
  • boolean equals(Object other)
  • String substring(int beginIndex, int endIndex)
  • String toUpperCase()
  • String literals are surrounded by double quotes,
    e.g.
  • String bozo "This is a test.

18
Java Strings
  • String concatenation is very simple, simply use
    the operator.
  • String firstNameChris
  • String lastNameFischer
  • System.out.println(My name is
    firstNamelastName)
  • If you concatenation a string with another data
    type, it gets coerced to a string
  • int a15 boolean isTruefalse
  • System.out.println(The value of a is a)
    //prints The value of a is 15
  • System.out.println(The value of isTrue is
    isTrue) //prints The value of isTrue is false

19
Java Strings
  • Since the operator concatenates strings like it
    would logically be expected to do, would just
    compare them, right?
  • Well, no. The tests to see if the String
    occupies the same space in memory, not equality.
    To test equality, use the .equals() method.
    This can be an insidious bug, so get it right
    from the start. Lets look at the following
    example.

20
Java Strings
  • String testString1This is a string
  • String testString2This is a string
  • System.out.println(testString1testString2)
    //can output true
  • System.out.println(testString1.equals(testSt
    ring2) //outputs true
  • This will sometimes (usually) output true, true.
    The reason is probably that since the String
    class is immutable (they dont change), the Java
    compiler, in an effort to optimize space, uses
    the same spot in memory for the variable. Now,
    if we do..

21
Java Strings
  • //Now we use the new operator to force each
    string to a different mem location
  • String testString1new String(This is a
    string)
  • String testString2new String(This is a
    string)
  • System.out.println(testString1testString2)
    //now prints FALSE
  • System.out.println(testString1.equals(testStrin
    g2) //still prints TRUE
  • This is a good example of how unpredictability
    can creep into programs. Bugs like these are a
    real pain to find too. Moral of the story Make
    sure you use .equals when comparing Strings.

22
Java Strings
  • For Java strings that need to be mutable, there
    is a StringBuffer class. These are especially
    useful for reading in data from streams.
  • This primarily exists for performance reasons.
  • The String class exposes about 50 other methods,
    for just about everything you could want to do
    with a String. Check the API.

23
Control Flow
  • if, for, while, switch just like C
  • break and continue unlabelled or labelled
  • Compound statements grouped in braces ( and
    ).
  • This is also almost exactly like C.

24
Arrays
  • Java supports C like arrays (and even cleaned
    them up a bit!)
  • To declare an array of ints, for example, would
    you do
  • int array_of_int
  • This only declares the array, it doesnt
    initialize it. To initialize the array, you must
    do
  • int array_of_intnew int50
  • or you can initialize it with values, like
  • int array_of_int2,3,5,7,9

25
Arrays
  • Array indices starts at zero.
  • The length of an array can be accessed by the
    length member
  • int array_of_ints2,11,18,23,28,39
  • System.out.print(Tonights winning lotto numbers
    are )
  • for (int j0 j
  • System.out.print(array_of_intsj )
  • Note that length is not a method, dont use ()
    after it.

26
Array Copying
  • Array copying is not straightforward
  • int array_of_ints1,3,5,7,9
  • int copy_of_int_array
  • copy_of_int_arrayarray_of_ints
  • array_of_ints299
  • System.out.println(array_of_ints2)
    //prints 99
  • System.out.println(copy_of_int_array2)
    //also prints 99
  • Assigned an array to another simple makes another
    reference to that array.

27
Array Copying
  • So, to copy an array, you call the
    System.arraycopy method
  • int array_of_ints2,4,6,8,10
  • int copy_of_array
  • //from array,
    from index, to array, to index, count
  • System.arraycopy( array_of_ints, 0 ,
    copy_of_array, 0 , 5 )
  • Java even has a build in utilities for sorting
    arrays (provided they are for primitives types,
    or objects that implement the comparable
    interface. More on interfaces later.).
  • java.utils.Arrays.sort(array_name)

28
Command Line Arguments
  • Available as array of Strings passed to main.
  • First element is first argument, not program name
    or class name.
  • Example
  • class ArgTest
  • public static void main(String argv)
  • for (int i0 i
  • System.out.println(argvi)

29
Command Line arguments
  • Ok, great, what if I want to use an argument that
    isnt a string? Answer Use one of the primitive
    wrappers to convert them to the type you want
  • public static void main(String args)
  • try //This is exception handling.
    More on this later
  • int someIntInteger.parseInt(args0)
  • catch (NumberFormatException exp)
  • System.out.println(That wasnt
    an integer!)
Write a Comment
User Comments (0)
About PowerShow.com