Java Basics

  • Introduction to Java
  • Java Basic Knowledge
  • Lab

Agenda

Introduction to Java

Welcome to Java

What is Java?

  • A cross-platform language
  • A popular platform on mobile phones
  • A internet-targeted language
  • A fully objected-oriented language

JVM

With Java, the CPU executes the JVM, which is platform dependent. This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM availble for it to execute upon. You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.

Java Environment

  • JRE — Java Runtime Environment
  • JDK — Java Development Kit

 

EE — Enterprise Edition

SE — Standard Edition

ME — Micro Edition

Edition

Java Basic Knowledge

Things you should know in advance

Type

PRIMITIVE: 

byte, short, int, boolean, char....

 

EXTENDED:

class java.util.Scanner

class java.lang.String

......

Methods

How to write a method.

 

Parameter, return value.

Class and Object

In Java,  Class is a blue print used to create objects. In other words, a Class is a template that defines the methods (Functions) and Members (variables) to be included in a particular kind of Object.

 A Class is a template for an object, a user-defined datatype that contains the variables and methods in it.

 

A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing’s behaviors (the things it can do, or methods, operations or features). That is, Class is a blue print used to create objects. In other words, each object is an instance of a class. 

A class is a predefined frame of an object, in which its mentioning what all variables and methods an object (object of that class) can have.

class class-Name {
    //variables /methods/constructors
}

Class syntax

Object syntax

class-name variable-name = new class-name();

Overloading

public class Printer{
    public void printInteger(int a) {};
    public void printDouble(double a) {};
    public void printString(String a) {};
}
public class Printer{
    public void print(int a) {};
    public void print(double a) {};
    public void print(String a) {};
}
System.out.println(3 + a);  //plus(3, a);
System.out.println("" + a);  //plus("", a);

Method Overloading

Operator Overloading

Without overloading

Constructor

public class Record{
    private String name;
    private int score;

    public setName(String name) {
        this.name = name;
    }

    public setScore(int score) {
        this.score = score;
    }
}
Record r = new Record();

r.setName("Robin");
r.setScore(100);
public class Record{
    private String name;
    private int score;

    public Record(String name, int score) {
        this.name = name;
        this.score = score;
    }
}
Record r = new Record("Robin", 100);

Without Constructor

With Constructor

More convenient!

Garbage Collection

In computer sciencegarbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.

public class Record {
    private Record prev;
    public Record(Record p){
        prep = p;
    }
}

public class RecordDemo {
    public static void main(String[] arg){
        int i; 
        Record r1 = null;

        for(i = 0; i < 100; i++) {
            Record tmp = new Record(r1);
            r1 = tmp;
        }
    }
}

100 instances created, all of them alive.

public class Record{
    private int score;
}

public class RecordDemo {
    public static void main(String[] arg){
        int i; 
        Record r1;

        for(i = 0; i < 100; i++) {
            r1 = new Record();
        }
    }
}

100 instances created, only 1 alive after the loop.

Finalizer

public class Record{
    private int score;
    public Record(){
        sys.mem_usage += 10;
    }

    protected void finalize() throws Throwable{
        sys.mem_usage -= 10;
        System.out.printlin("Good Bye!");
    }
}

A mechanism to let the instance say goodbye.

Static Variable

public class Record{
    private static int total_rec = 0;
    public Record(){
        total_rec++;
    }
    
    public void show_total_rec(){
        System.out.println(total_rec);
    }
}

public class RecordDemo{
    public static void main(String[] args){
        Record r1 = new Record();
        r1.show_total_rec();
        Record r2 = new Record();
        r2.show_total_rec();
        
        System.out.println(Record.total_rec);
    }
}

In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables are generally automatic), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated in heap memory.

2

1

2

use scarcely.

public class myMath{
    public static double mean(double a, double b){
        return (a+b) *0.5;
    }
}

public class RecordDemo{
    public static void main(String[] args){
        double i = 3.5;
        double j = 2.4;

        System.out.println(myMath.mean(i, j));
    }
}

Static Method

Java static method program: static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.

class Record{
    String name;
    int score;
}

public class RecordDemo{
    public static void main(String[] arg){
        Record r1, r2;
        r1 = new Record(); r2 = new Record();
        r1.name = "HTLin"; r1.score = 95;
        r2.name = "HTLin"; r2.score = 95;
        System.out.println(r1 == r2);
        r2 = r1;
        System.out.println(r1 == r2);
    }
}

Reference Equal

False.

True.

Reference equal rather than content equal for extended types.

class Record{
    String name;
    int score;
}

public class RecordDemo{
    public static void main(String[] arg){
        Record r1, r2;
        r1 = null; 
        r2 = new Record();
        System.out.println(r1 == r2);
        r2 = r1;
        System.out.println(r1 == r2);
    }
}

False.

True.

class myInt{
    int val;
    
    myInt(int v){
        val = v;
    }
}

class Tool{
    void swap(myInt first, myInt second){
        int tmp = first.val;
        first.val = second.val;
        second.val = tmp;
        System.out.println(first.val);
        System.out.println(second.val);
    }
}

Reference Parameter

public class Demo{
    public static void main(String arg[]){
        Tool t = new Tool();
        myInt i = new myInt(3);
        myInt j = new myInt(5);
        t.swap(i, j);
        System.out.println(i.val);
        System.out.println(j.val);
    }
}

5

5

3

3

static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)

As for it being mandatory - basically the Java designers decided to stick to a single method signature, which is frankly simpler than allowing for it to be optional. 

Ultimately it doesn't make a lot of difference, to be honest. There's no significant downside in having to include the parameter.

Why always

public static void main(String arg[]){
    //do something here.
}

?

okey in C# though.

Code Convention

Please refer to the file at...

http://10.193.200.40:8080/doc

初级阶段/SE/Class/Materials/Class_03_OOP/Java basics/javacodeconventions.pdf

Lab

1. Install Java

2. Install Eclipse

Setup Environment

Assignment 1

Material path

2. http://10.193.200.40:8080/doc

    初级阶段/SE/Class/Materials/Class_03_OOP/Java basics/Lab01/introToEclipse.pdf

1.  http://10.193.200.40:8080/OOP/.......

Assignment 2

We provide two classes, Book and Library, that provide the functionality for the book database. You must implement the 
missing methods to make these classes work.
 

The libraries of SmallTownX need a new electronic rental system, and it is up to you to build it. SmallTownX has two libraries. Each library offers many books to rent. Customers can print the list of available books, borrow, and return books. 

You can find the files you need in the following address:

Description

   http://10.193.200.40:8080/doc

    初级阶段/SE/Class/Materials/Class_03_OOP/Java basics/Lab01/...

I'm here, dude!

First we need a class to model books. Start by creating a class called Book. Copy and paste the skeleton below. This class defines methods to get the title of a book, find out if it is available, borrow the book, and return the book. However, the skeleton that we provide is missing the implementations of the methods. Fill in the body of the methods with the 
appropriate code. The main method tests the methods. When you run the program, the output should be: 

Hint: Look at the main method to see how the methods are used, then fill in the code for each method. 

Title (should be The Da Vinci Code): The Da Vinci Code
Rented? (should be false): false
Rented? (should be true): true
Rented? (should be false): false 

Step One: Implement Book 

Step Two: Implement Library 

Next we need to build the class that will represent each library, and manage a collection of books. All libraries have the same hours: 9 AM to 5 PM daily. However, they have different addresses and book collections (i.e., arrays of Book objects). 
Create a class called Library. Copy and paste the skeleton below. We provide a main method that creates two libraries, then performs some operations on the books. However, all the methods and member variables are missing. You will need 
to define and implemen

  • Some methods will need to be static methods, and some need to be instance methods.
  • Be careful when comparing Strings objects. Use string1.equals(string2) for comparing the contents of string1 and string2.
  • You should get a small part working at a time. Start by commenting the entire main method, then uncomment it line by line. Run the program, get the first lines working, then uncomment the next line, get that working, etc. You can comment a block of code in Eclipse by selecting the code, then choosing Source → Toggle Comment. Do the same again to uncomment it.
  • You must not modify the main method.

Notes

The output when you run this program should be similar to the following: 

Library hours:
Libraries are open daily from 9am to 5pm.
Library addresses:
10 Main St.
228 Liberty St.Borrowing The Lord of the Rings:
You successfully borrowed The Lord of the Rings
Sorry, this book is already borrowed.
Sorry, this book is not in our catalog.
Books available in the first library:
The Da Vinci Code
Le Petit Prince
A Tale of Two Cities
Books available in the second library:
No book in catalog
Returning The Lord of the Rings:
You successfully returned The Lord of the Rings
Books available in the first library:
The Da Vinci Code
Le Petit Prince
A Tale of Two Cities
The Lord of the Rings

Submission

Path:

Submit Eclipse Project file via Git

Project name:   Lab01

Due date: 

10.193.200.199:2014/工/Stage1/LAB/OOP/

2014.11.23

Java Basics

By TingSheng Lee

Java Basics

  • 826