Cheat Sheet Java
Cheat Sheet Java
Cumulative Project 3
Java instance
Java instances are objects that are based on classes. For example, Bob may be
an instance of the class Person.
Every instance has access to its own set of variables which are known
as instance fields, which are variables declared within the scope of the
instance. Values for instance fields are assigned within the constructor
method.
public class Person {
int age;
String name;
// Constructor method
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public static void main(String[] args) {
Person Bob = new Person(31, "Bob");
Person Alice = new Person(27, "Alice");
}
}
instanceOrClassName.fieldOrMethodName
public class Person {
int age;
public static void main(String [] args) {
Person p = new Person();
// here we use dot notation to set age
p.age = 20;
// here we use dot notation to access age and print
System.out.println("Age is " + p.age);
// Output: Age is 20
}
}
Constructor Signatures
A class can contain multiple constructors as long as they have different
parameter values. A signature helps the compiler differentiate between the
different constructors.
null Values
null is
a special value that denotes that an object has a void reference.
public class Bear {
String species;
public Bear(String speciesOfBear;) {
species = speciesOfBear;
}
Declaring a Method
Method declarations should define the following method information: scope
(private or public), return type, method name, and any parameters it receives.
// Here is a public method named sum whose return type is int
and has two int parameters a and b
public int sum(int a, int b) {
return(a + b);
}
In the example, a and b are two parameters which, when the method is called,
hold the value 10 and 20 respectively.
public class Maths {
public int sum(int a, int b) {
int k = a + b;
return k;
}
public static void main(String [] args) {
Maths m = new Maths();
int result = m.sum(10, 20);
System.out.println("sum is " + result);
// prints - sum is 30
}
}