Intro
Java is a statically typed language, which means that all variables, parameters and methods must have a declared type. After declaration , the type can never change. And before executing the code ,Java will check the type first , so it will never run into type erroe.
Basic syntax
-
All statements must end with a semi-colon ‘;’
-
Curly brace{} : which enclose section of code (functions classes and etc.)
-
Declare varible :variable must be declared before it used , and must be given a type.
-
the difference between System.out.println() and System.out.print()
- println will include a new line (or a return)
- System.out.print() must have the parameter(s) in the brackets
-
Commentary
- Java comments can either start with ‘//’ or can extend over any number of lines using “/*” and “*/”
- “/**” : documentation comments, which can be interpreted by some tools
-
Class
- Every function and variable in Java is contained in the class , which is similar as class in Python
- All code lives with classes
- All classes , in turn , belong to some package.
-
Method(Function)
- Function Headers in Java contain more information that those in Python.
- NEED to specity the types of values returned by the function and taken as parameters to the function , like int, void etc.
- type void has no possible values; the main function here returns nothing
- type String is like the str in Python
- the trailing ‘[]’ means array of . Arrays are like Python lists ,except that their size is fixed once created.
- Functions named main are special : they are what get called when one runs a Java program.(In python ,the main function is essentially anonymous)
- Any code we want to run must be inside of a function public static void main(String[] args)
- Function Headers in Java contain more information that those in Python.
-
Selection
- In python a.b means the thing names b that is in or that applies to the thing identified (or computed) by a
- Thus System.out means the variable named out that is found in the class named System
- Likewise System.out.println means the method named println that applies to the object referenced by the value of variable System.out
-
Access
- Every declared entity in Java has access permissions indicating what pieces of code may mention it.
- In particular , public classes , methods and variables may be referred to anywhere else in the program.
- We sometimes refer to them as exported from their class( for methods or variables) or package( for classes)
- Static method / variable
- Static methods and variables are “one-of” things
- A static method is just like an ordinary python function (outside of any class) or a function in a python class that annotated @staticmethod
- A static variable is like a Python variable defined outside of any class or a variable selected from a class ,as opposed to from a class instance.
- Other variables are local variables (in functions) or instance variables(in classes), and these are as in python.
-
*Using java the implement 'print(“hello world”)
public class Hello{
public static void main(String[] args){
System.out.println("hello world");
}
}
Basic code compared with Python
# python
class Car:
def __init__(self, m):
self.model = m
self.wheels = 4
def drive(self):
if self.wheels < 4:
print(self.model +" no go vroom")
return
print(self.model + " goes vroom") # driving makes noise
def getNumWheels(self):
return self.wheels
def driveIntoDitch(self, wheelsLost):
self.wheels = self.wheels - wheelsLost
c1 = Car("Civil type R")
c2 = Car("Toyota Camry")
c1.drive()
c1.driveIntoDitch(2)
c1.drive()
print(c2.getNumWheels())
// java
public class Car{
public String model;
public int wheels;
public Car(String m){
this.model = m;
this.wheels = 4;
}
// void means nothing will return
public void drive(){
if (this.wheels < 4){
System.out.println(this.model+" no go vroom");
}
System.out.println(this.model+" goes vroom");
}
public int getNumWheels(){
// sometimes when we ignore 'this.' the code still work while there just exists one argument named wheels.
return this.wheels;
}
public void driveIntoDitch(int wheelsLost){
this.wheels = this.wheels - wheelsLost;
}
public static void main(String[] args){
Car c1; // declare the car exists then we can use
Car c2;
c1 = new Car("Civil type R");
c2 = new Car("Toyota Camry");
c1.drive();
c1.driveIntoDitch(2);
c1.drive();
}
}
Defining and Using Classes
Static vs. Non-static Methods
Client
All code in Java must be a part of a class and most code is written inside of methods.If we build a method in a class without main method and run it directly ,we will get an error message . So at this time if we want to use the method of that class, we can build another class with main function and use the method of the previous class .
public class Dog{
public static void makeNoise(){
System.out.println("Bark");
}
}
public class DogLauncher{
public static void main(String[] args){
Dog.makeNoise();
}
}
Since the class Dog does not have the main method , it does not do anything. class DogLauncher uses the method of the class Dog .
A class that uses another class is sometimes called a client of that class. Doglauncher is a client of Dog.
Instance Variables and object Instantiation
If we want more kind of dogs’ sounds , one approach is to create separate classes for each type of dog .
public class TinyDog{
public static void makeNoise(){
System.out.println("yip yip")
}
}
And we know that classed can be instantiated and instances can hold data . So we can create instances of the Dog class and make the behavior of the Dog methods contingent upon the properties of the specific Dog.
public class Dog{
public int weightInPounds;
public void makeNoise(){
if (weightInPounds < 10){
System.out.println("yip yip");
} else if (weightInPounds < 30){
System.out.println("bark bark");
} else {
System.out.println("woof");
}
}
}
// if we want to use the makeNoise method we can rewrite the class DogLauncher
public class DogLauncher{
public static void main(String[] args){
Dog d;
d = new Dog(); // instantiate
d.weightInPounds = 20; // instance attribute , but need to be declared in the class dog
d.makeNoise();
}
}
Key information
- An object in java is an instance of any class.
- The Dog class has its own variables, also known as instance variables or non-static variables.These must be declared inside the class , unlike Python and matlab where new variables can be added at runtime.
- The method that we created in the Dod class did not have the static keyword, so we can call such methods instance methods or non-static methods.
- To call the makeNoise method, we had to first instantiate a Dog using the new keyword , and the make a specific Dog bark.
- Once an object has been instantiated, it can be assigned to a declared variable of the appropriate type. e.g. d = new Dog()
- Variables and methods of a class are also called members of a class.
- Members of a classs are accessed using dot notation.
Constructors in java
The following instantiation is parameterized. The constructor with signature public Dog(int w) will be invoked anytime that we try ro create a Dog using the new keyword and a single integer parameter. It is vert similar to the _init_ method in python.
public class Dog {
public int weightInPounds;
// constructor
public Dog(int w) {
weightInPounds = w;
}
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
Array Instantiation and Arrays of Objects
Arrays are also instantiated in Java using the new keyword.
public class ArrayDemo{
public static void main(String[] args){
/* create an array of five integers*/
int[] someArray = new int[5];
someArray[0] = 3;
someArray[1] = 4;
}
}
/* create array of instantiated object */
public class DogArrayDemo{
public static void main(String[] args){
/* create an array of two dogs*/
Dog[] dogs = new Dog[2];
dogs[0] = new Dog(8);
dogs[1] = new Dog(20);
/* the dog0 has the weight of 8*/
dogs[0].makeNoise();
}
}
We can see that the keyword new appear three times in the class DogArrayDemo . The first time is to create an array thay can hold two Dog objects . And the left is to create each actual Dog
Class Methods vs. Instance Methods
- Class Methods : static methods
- Static methods are actions that are taken by the class itself
- eg : x = Math.sqrt(100);
- Instance Method : non-static methods
- Instance Methods are actions that can be taken only by specific instance of a class.
- Math m = new Math() ; x = m.sqrt(100);
/* a class with both instance and static methods : compare two dogs*/
public static Dog maxDog(Dog d1 Dog d2){
if (d1.weightInPounds > d2.weightInPounds){
return d1;
}
return d2;
}
/* invoke above method*/
Dog d = new Dog(13);
Dog d2 = new Dog(131);
/* using the class name to invoke since the method is a static method*/
Dog.maxDog(d, d2);
/* non- static method : implementing the maxDog*/
public Dog maxDog(Dog d2){
if (this.weightInPounds > d2.weightInPounds){
/* using this to refer to the current object */
return this;
}
return d2;
/* this non-static method can be invoked as follows*/
Dog d3 = new Dog(23);
Dog d4 = new Dog(100);
/* using the specific isntance to invoke the method*/
d3.maxDog(d4);
}
Cannot reference non-static from a static context
/* ERROR*/
public static Dog maxDog(Dog d1, Dog d2) {
if (weightInPounds > d2.weightInPounds) {
return this;
}
return d2;
}
Static variables
It is occasionally useful for classes to have static variables . These are properties inherent to the class itself , rather than the instance .
Static variables should be accessed using the name of the class rather than a specific instance . We need to using ClassName.v_name not InstanceName.v_name . i.e. Test.y is right not t.y (not error but confusing).
public class Test{
public int x;
public static String y = "static variable";
}
t = new Test()
- Analyse public static void main(String[] args)
- public : so far all of our methods start with this keyword
- static: It is a static method , not associated with any particular instance
- void : no return type
- main : name of the method
- String[] args : a parameter that is passed to the main method
Reference, Recursion and Lists
Containers
- Values are numbers, booleans, and pointers. Values never change.
- Simple containers contain values. (The contents of containers can change)
- Structure containers contain (0 or more) other containers
- class object / array object / empty object
- Pointers
- Pointers(or references) are values that reference (point to) containers.
- One particular pointer , called null,points to nothing.
- In java. structured containers contain only simple containers , but pointers allow us to build arbitrarily big or complex structures anyway.
- Containers may be named or anonymous/
- In java , all simple containers are named , all structured containers are anonymous , and pointers point only to structured containers.
- (structured containers contain only simple containers)
type
Primitive type
- 8 primitive type in Java: byte, short, int, long, float, double, boolean, char
Referenced type
box and pointer
the 9th type is references to Objects(an arrow) , references may be null
Define new types of object
- List of integers
public class IntList{
// constructor function (used to initialize new object)
/** list cell containing (head tail)*/
public IntList(int Head, IntList tail){
this.head = head;
this.tail = tail;
}
// names of simple containers (fields)
// public instance variables usually bad style
public int head;
public IntList tail;
}
Public vs. Private
Private variables and methods can only be accessed by code inside the same .java.
When you create a public member (i.e. method or variable), be careful , because you are effectively committing to supporting that members’s behavior exactly as it is now ,forever
Why nested class
Nested classes are useful when a class does not stand on its own and is obvious subordinate to another class
-
make the nested class private if other classes should never use the nested class.
-
Static Nested Classed
If the nested class never uses any instance variables or methods of the out
Having a nested class has no meaningful effect on code performance and is simply a tool for keeping code organized .
If the nested class has no need to use any of the instance methods or variables of SLList , you may declare the nested class static.
Declaring a nested class as static means that method inside the static class can not access any of the members of the enclosing class.
In java all the items in List must be the same type.