• No results found

Java from a C perspective. Plan

N/A
N/A
Protected

Academic year: 2021

Share "Java from a C perspective. Plan"

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

Java from a C perspective

Cristian Bogdan

2D2052/ingint04

Plan

• Objectives and Book

• Packages and Classes

• Types and memory allocation

• Syntax and C-like Statements

• Object Orientation (minimal intro)

• Exceptions, exception programming

• Some fundamental classes that you’ll

(2)

Objectives and Book

• Introduce Java to a sufficient level so that it can

be used in the course

• Mark the main differences from C

• How-to compile and run

• Not an exhaustive course of Java

• Not a thorough explanation of object-orientation

• Book: Java in a Nutshell, available online

http://msp-of.de/oreilly/books/javaenterprise/jnut/index.htm

Packages and Classes

• Java source code is organised in

classes

• Every .java file contains at least one class, which

has the same name as the file

– HelloWorld.java will contain the class HelloWorld)

• Classes are organized in packages,

hierarchically. Generally, a package is a

directory

– all .java files of classes from the package mycompany.mypackage will be in the directory mycompany/mypackage, etc.

(3)

package

and

import

• Every .java file can begin with at most one package

statement, declaring the package of the class

package se.mycompany.mypackage;

• and a number of import statements

import java.lang.*; // redundant

import java.util.Vector; import java.util.*;

• if a class has not been imported, you can refer to it in code by the fully qualified name like

se.mycompany.mypackage.HelloWorld

• Import is the only way to borrow code from other

packages, Java has no #include and no preprocessor

(no conditional compilation, etc)

Class visibility

• A .java file can contain other classes but only the

one that has the same name as the file can be

made visible outside the file.

• For a class to be visible outside the package, it

needs to be declared

public

package se.mycompany.mypackage; public class HelloWorld { … } class HelloWorldHelper{… }

• The rest of the classes defined in the file can

only be used as local helpers for the main class

(4)

Classes and Members

• Think of a class as a C struct (Java has no struct or

union), that has both variables and methods (called members). No variable or method can be defined outside class bodies

• Methods are like C functions

• Members are not visible outside the class if declared

private

• If declaredpublic, members are visible outside the package

• If no accessibility is specified, members are visible in the package only

• Typically, member variables are private or package-accessible, only somemethods(no variables!) are made public (encapsulation)

• The methods are manipulating the member variables to provide ”services” to the world outside the class

Example

package se.kth.nada.ingint; import java.util.Date;

public class HelloWorld extends Object { // no need to speficify ”extends Object” private Date now; // member variable public HelloWorld() // constructor

{now= new Date(); }

public void doSomethingUseful() // member method {

System.out.println(

”Hello World, the time is ”

+ now.toString() // can be just ”now” );

}

public static void main(String[] argv){ HelloWorld hw= new HelloWorld(); hw.doSomethingUseful();

} }

(5)

Objects

• Classes can be

instantiated

to create

objects

Object o= new

se.kth.nada.ingint.HelloWorld();

Or:

import se.kth.nada.ingint.*; …

HelloWorld o= new HelloWorld();

• Public methods of the objects can be used to

ask them to do something

o.doSomethingUseful();

Statics

There are

no global variables

but a class can

define a variable visible everywhere else e.g.

public static int numberOfAccesses;

• this is not recommeded, because anybody can change the variable as they wish

• To avoid that, declare the variablefinal(const in C)

All variables declared

static

are allocated

only once and can be seen by all objects made

from the class

Static methods can be defined to express

procedures that are specific to the class but do

not refer to any object

E.g.

out

is a

static public final

(6)

Methods

• Unlike in C, methods have fixed number of

arguments, with fixed types (strict type checking)

public void doSomethingUseful(String

message)

{ System.out.println(message+now);}

• A method can be declared after being used by

another method in the class (forward

declaration)

• Methods that do not return anything must be

explicitely declared void

• Methods can have identical names provided

they have different number or type of arguments

Variables and data types

• Variables can be declared as class

member variables

• or as varialbes in methods (anywhere in

the method body, not just in the begining

as in C)

• Integer and floating point types are similar

to C, but they have the same size on any

platform:

– byte

(8),

short

(16),

int

(32),

long

(64),

float

(32),

double

(64)

(7)

References and Garbage

Collection

• Numeric types, boolean and char are the only Java types that do not refer to an object. They are called primitive

types, because they are needed to compose objects • The rest of the types are just class names and denote

references (Java has no pointers)

int aPrimitive;

HelloWorld aReference;

• If a reference is null it refers to no object. Calling a method of or referring to a field of a null reference will produceNullPointerException

• Objects that are not referenced from anywhere are

garbage collected. Java has only new (like C malloc()), no delete or free()

• Before the object is ”forgotten” the finalize() method is called

protected void finalize()

{ System.out.println(”Help, I’m dying!!!!”); }

Garbage Collection examples

• When a reference is made null

HelloWorld hw= new HelloWorld(); hw.doSomethingUseful();

hw=null;

• When a method referring to the object ends

void myMethod(){

HelloWorld hw= new HelloWorld(); hw.doSomethingUseful();

}

hw was only known here and has not been passed to other objects

• When the (only) referrer object is garbage collected

Class MyClass{ HelloWorld hw; … } ... Object mc= new MyClass(); …

when mc dies, hw will die, unless mc passes the hw reference to some other object

(8)

Arrays

• You can allocate arrays of variable size, of both primitive types and references to objects

• All arrays are homogeneous (contain only one type)

int [] aPrimitiveArray= new int[anExpression]; Object [] aReferenceArray=

new HelloWorld[someExpr];

• For arrays of references, the objects themselves are _not_ instantiated

aReferenceArray[7]= new HelloWorld()

• Arrays have a special ”field” called length

aReferenceArray.length==someExpr -> true • Refering to a non-existing index throws

ArrayIndexOutOfBondsException

aReferenceArray[-1] -> exception

• Multidimensional arrays can be defined

int[][] aPrimitiveBiDimensionalArray matrix=

new int[2][7]; // members are arrays that need be // initialized!!!

Statements and Operators

• Following C statements are present in

Java with the same meaning:

if/else, case/switch/default/break

do/while/for/continue/break

return

• return cannot return a value in void

methods (some flavours of C allow this)

• Most operators look the same as in C

(9)

The main() method

• Is the entry point in a Java program

public static void main(String[] argv)

• publicbecause it needs to be visible from outside

• staticbecause at the begining of the program there are no objects created, so we need a method that can be accessed without having an object

• void, to return a value to the operating system, use

System.exit(value)

• String[] argv (or any other name) is the list of arguments from the command line. Unlike in C, there is no need for an int argument that specifies the number of arguments, because that can be found out

argv.length

Exceptions

• When things go wrong java throws exceptions instead of (e.g.) returning a negative value

• This is much more meaningful for the programmer

java.lang.ArrayIndexOutOfBondsException, java.lang.NullPointerException,

java.io.FileNotFoundException, java.net.UnknownHostException

• How to throw an exception

public void doSthUseful(String msg)

throws MyException{

if(msg.length()<3) throw new

MyException(”Message too short”); …

(10)

Exceptions

• How to catch an exception

public void doSthElse(String msg) {

try{ doSomethingUseful(msg); }catch(MyException me){

me.printStackTrace(); }

finally{

// this is executed anyway! }

}

• RuntimeExceptions do not need to be caught! They are typically programmer errors, so the errors need to be corrected instead • java.lang.Throwable, java.lang.Exception, java.lang.Error

• Letting an exception pass through, so the code that calls the method will need to deal with it

public void doSthElse(String msg) throws MyException{ doSomethingUseful(msg);

}

Other issues

• Other object oriented concepts

– abstract methods: empty methods to be implemented by subclasses. Classes that haveabstract methods must be declaredabstract

– interfaces are like classes but contain only public abstract non-static methods and static public fields.

– A class canextends at most one class and implements

more interfaces

– protected members are visible in subclasses and in the package (less than public access, more than private)

• Threads: parallel execution of code: java.lang.Thread, java.lang.Runnable

class DoInParallel implements Runnable{

public void run(){ // code to run in parallel }

}

// in other code:

(11)

Some Fundamental Classes

• http://java.sun.com/j2se/1.4.2/docs/api/overview-summary.html

• string manipulation: java.lang:

String,

StringBuffer

• containers and iterators: java.util:

Vector,

Hashtable, Enumeration

• I/O: java.io:

InputStream

,

OutputStream

,

Reader

,

Writer, FileInputStream,

FileOutputStream, FileReader,

FileWriter

References

Related documents

We will now create a Java class called “HelloWorld” that will have a single main method, and this method will simply print out “Hello World” to the

public class DialogFragment extends android.app.DialogFragment { private DialogFragmentListener

public interface List extends Collection { // adds the following to Collection boolean addAll(int index, Collection c);. Object

public interface Stack extends Container { public abstract Object getTop();.. public abstract void

public class TextFieldTest extends JFrame { private JTextField text1, text2, text3;. private

public class Team extends JPanel implements ActionListener { private JButton nameButton;. private

public class Run_App2 extends JApplet { // changed from MyFrame private Ex2_Panel left;. private

public class QuizActivity extends AppCompatActivity { private Button mTrueButton;.. private