Java Review Session CS 402 Melissa Carroll Berk Kapicioglu Most slides by: Matt Hibbs

Preview:

Citation preview

Java Review Session

CS 402Melissa CarrollBerk Kapicioglu

Most slides by: Matt Hibbs

First Off

• Slides available on course website• This presentation doesn’t get into very fine detail, so for

more info check out Java in a Nutshell, which is available online to Princeton students for free. You can search/find it at:

catalog.princeton.edu

Why Java?

• Cross Platform– Bytecode and the JVM run on most platforms

• Security– JVM can restrict access to local machine

• Safety– Garbage Collection (fewer memory leaks)

• Ease of Coding– Many available packages

Java Basics

• http://java.sun.com (SDK)

• Development Environments– Eclipse– Emacs– Notepad and Command Line

Hello World

• In Cint main (int argc, char** argv) {

printf(“Hello World!\n”);

return 0;

}/* end main */

• In Javapublic class HelloWorld {

public static void main (String[] args) {

System.out.println(“Hello World!”);

}/* end main */

}//end HelloWorld

• Things to notice:

• Similar syntax

• Classes

• System.out.println()

• main is void: public static void main

How Java Differs from C

• Exclusively Object-Oriented Language– EVERYTHING must live in a class (mostly)– No Global Variables

• No Pointers– Also, no ‘*’ ‘->’ or ‘&’ operators– Blessing and a Curse

• Garbage Collection• Loss of Power

How Java Differs from C

• No Preprocessor (no #include, #define, etc.)

• No goto statement

• Declare/Define Variables & Methods anywhere (within a class)

• No struct, enum, or typedef• Can’t overload Operators• Use new rather than malloc()

Java – Data Types

• Primitives– boolean, char, byte, short, int, long, float, double

• char is Unicode (16 bits)• boolean is true/false (not 1/0)

int i = 1;

if (i) { } //BAD

if (i == 1) { } //GOOD

Java – Data Types

• Primitives– Type conversions

• Can’t convert booleanboolean b = false;int i = b; //BADint j = b ? 1 : 0; //GOOD

• Converting ‘up’ is automatic• Converting ‘down’ requires a cast

double f = 37.5; // it used to be float but // gave compiler error

int i = f; //BADint j = (int) f; //GOOD (truncates)

Java – Data Types

• References (by reference vs. by value)– Everything that’s not primitive (classes and

arrays)– Think of these as hidden pointers

Foo a = new Foo();

Foo b = a;•a and b now reference the same object

Java – Arrays

• Mostly what you would expectString[] textLines;String[] textLines2 = new String[15];textLines2[3] = “Hi, how are you today?”;int[] fib = {1, 1, 2, 3, 5, 8, 13, 21};System.out.print(fib[5]); // 8

• textLines is just a Reference, no array was actually made

• textLines2 is an un-initialized array• fib is an initialized array

Java Development

Java Platform

• Lots of built-in objects and functions for various purposes– Graphics (java.awt)– Math Functions (java.math)– Networking (java.net)– Databases (java.sql)

• We’ll mostly use the platform for data structures (java.util) and I/O (java.io)

Java Packages

• Java organizes classes into larger groups called packages

• Both the Java Platform and any classes that you write are organized into packages

• For code that you write, don’t worry so much about what package you’re in (the default is fine)

Using the Java Platform

• http://java.sun.com/j2se/1.4.2/docs/api/index.html

• You can always use the full package path name to access classesjava.io.FileReader fr = new java.io.FileReader (“test.txt”);

• But that’s pretty annoying, so you can use import statements at the beginning of your code to avoid thisimport java.io.FileReader;

//...

FileReader fr = new FileReader(“test.txt”);

//...

Object Orientation

Java - Classes

• Similar to C++ classes in many ways• Here’s a simple Java class that we’ll break down:

public class Circle {private float radius;

public static final double PI = 3.14159;

public Circle(float r) {radius = r;

}

public float area() {return PI * radius * radius;

}}

Java - Classes

• Namingpublic class Circle {– The basic form is:

• <modifiers> class <name> {

– Typically need an access modifier• public, protected, private

– Can have additional modifiers• static, final, abstract

• If a Class is public, it MUST be the only public class in its file, and this file MUST be called <name>.java

Java – Access Modifiers

• Access modifiers control who has access to a variable or class

public – anything can access it

protected – only classes in same package can access (not important for 402)

private – only accessible within the class that defines it

Java - Classes

• Instance Fieldprivate float radius;

– Any variable declared in a class is a field– Typically have an access modifier– In this case the field is uninitialized, so it will

get the default value (0).

Java - Classes

• Class fields and methods– Use static modifier– Are instance-independent– Refer to using class name e.g. Circle.PI– No need to include class name if using within

class– If only used static methods, would not be OO

Java - Classes

• Constant class fieldpublic static final double PI = 3.14159;

– Again, typically have an access modifier– If you want to have a constant variable, also

use the static and final modifiers– static means that there is only one PI no

matter how many instances of Circle we make

– final means that PI cannot be changed

Java - Classes

• Constructorspublic Circle(float r) {radius = r;}

– This is what gets called when an instance of your class is created

– Typically used to just initialize fields– If you don’t write one, you get a default

constructor for free, which does nothing– Refer to other constructors with this()

Name of the class

Java - Classes

• Methodspublic float area() {

return PI * radius * radius;

}

– Again, need an access modifier– Need a return type (void is a valid choice)– Can optionally pass in arguments

Java - Classes

• Here’s the whole thing again:public class Circle {private float radius;

public static final double PI = 3.14159;

public Circle(float r) {radius = r;

}

public float area() {return PI * radius * radius;

}}

Java - Objects

• So, we’ve made a class, now what?• We can start making circles…

public Circle c1;public Circle c2 = new Circle();public Circle c3 = new Circle(2.5);

– c1 didn’t actually make a circle, it just made a circle reference

– c2 used the default constructor, and has radius 0

– c3 used our constructor, and has radius 2.5

Java - Objects

• Now that we have circles, we can call methods on them

public float f = c3.area();

System.out.print(f); //19.6349

Java - Interfaces

• Interfaces are one of the ways that Java allows for Inheritance (the other is with subclasses)

• For example, we could make an interface called Shape that our Circle class can implementpublic interface Shape {public float area ();

}// end Shape

public class Circle implements Shape {//...

}//end Circle• Now, since we know the Circle implements Shape, we

know that Circle must contain an area() method• Classes can implement one interface, no interfaces, or

multiple interfaces (many do)

Java – Reference Oddities

• Since we only deal with references to objects, some behavior may seem odd

Circle hulaHoop = new Circle (3);

Circle CD = hulaHoop;

CD.radius = 1; //we can’t actually do this (let’s pretend)

System.out.print(hulaHoop.radius); // 1

Packages to Look At

• Have a look at java.util, especially java.util.HashMap and java.util.LinkedList

• Both are what they sound like and have fairly straightforward functions

• These may or may not be useful in upcoming assignments

What to Focus on for 402

• Do focus on– Basic syntax like control flow, declarations– Syntax for declaring classes and methods,

instantiating objects– Writing output to stdout, stderr (for debugging)– Basic OO like interfaces– Java.util

• Don’t worry so much about– Reading input from stdin and files– Misc packages like java.security

Example Demo

Suggestions

• Play around with Java– Find an IDE your comfortable with, and just write some

programs to get a feel for it.

• Use the Java API specification at http://java.sun.com/j2se/1.4.2/docs/api/index.html

• If you have any problems, e-mail Berk (bkapicio@cs) or Melissa (mkc@cs) or feel free to ask your friends and/or classmates for help

Suggested Programs

• A rcenet rsesercah sduty fnuod taht it deosn’t mttaer in waht oredr the ltteers of a wrod are, so lnog as the frist and lsat letetrs are in the rgiht pclae. The rset can be a toatl mses and you can siltl raed it whtuoit a porbelm.

Suggested Programs

• A recent research study found that it doesn’t matter in what order the letters of a word are, so long as the first and last letters are in the right place. The rest can be a total mess and you can still read it without a problem.

• As a toy, write a program that garbles text like this – it would get you familiar with I/O and text manipulation.

Suggested Programs

• Using the built in HashMap, write a tester as though you had written this class yourself (possibly in CS 226)

• Maybe you could help out the TAs by writing a program that uses student names as a key and maps them to student ID numbers (You don’t really need to do this, we can just look it up)

Questions?

Recommended