AP - Study Material
AP - Study Material
Create a Class
Create an Object
In Java, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and
use the keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Multiple Objects
You can also create an object of a class and access it in another class. This is often used
for better organization of classes (one class has all the attributes and methods, while the
other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this example, we
have created two files in the same directory/folder:
Main.java
Second.java
Main.java
public class Main
{
int x = 5;
}
Second.java
class Second
{
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown
below). It is actually an attribute of the class. Or you could say that class attributes are
variables within a class:
Example
Create a class called "Main" with two attributes: x and y:
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax
(.): The following example will create an object of the Main class, with the name myObj.
We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
Example
Set the value of x to 40:
Example
Change the value of x to 25:
If you don't want the ability to override existing values, declare the attribute as final:
Example
public class Main
{
final int x = 10;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
The final keyword is useful when you want a variable to always store the same value, like
PI (3.14159...).
Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one
object, without affecting the attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main
{
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
Java Class Methods
You learned from the Java Methods chapter that methods are declared within a class, and
that they are used to perform certain actions:
Example
Create a method named myMethod() in Main:
public class Main
{
static void myMethod()
{
System.out.println("Hello World!");
}
}
myMethod() prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;
Example
Inside main, call myMethod():
public class Main
{
static void myMethod()
{
System.out.println("Hello World!");
}
You will often see Java programs that have either static or public attributes and methods.
In the example above, we created a static method, which means that it can be accessed
without creating an object of the class, unlike public, which can only be accessed by
objects:
Example
An example to demonstrate the differences between static and public methods:
public class Main
{
// Static method
static void myStaticMethod()
{
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod()
{
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args)
{
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Remember that..
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (),
followed by a semicolon (;).
A class must have a matching filename (Main and Main.java).
Like we specified in the Classes chapter, it is a good practice to create an object of a class
and access it in another class.
Remember that the name of the java file should match the class name. In this example, we
have created two files in the same directory:
Main.java
Second.java
Main.java
public class Main
{
public void fullThrottle()
{
System.out.println("The car is going as fast as it can!");
}
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values
for object attributes:
Example
Create a constructor:
Example
public class Main
{
int x;
public Main(int y)
{
x = y;
}
Example
public class Main
{
int modelYear;
String modelName;
Example
Create a variable of type String and assign it a value:
String Length
A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with
the length() method:
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
Example
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
Example
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
You can also use the concat() method to concatenate two strings:
Example
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and
generate an error:
String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
\\ \ Backslash
The sequence \" inserts a double quote in a string:
Example
String txt = "We are the so-called \"Vikings\" from the north.";
Example
String txt = "It\'s alright.";
Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Java Math
The Java Math class has many methods that allows you to perform mathematical tasks on
numbers.
Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y:
Example
Math.max(5, 10);
Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:
Example
Math.min(5, 10);
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:
Example
Math.sqrt(64);
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of x:
Example
Math.abs(-4.7);
Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Example
Math.random();
To get more control over the random number, e.g. you only want a random number
between 0 and 100, you can use the following formula:
Example
int randomNum = (int)(Math.random() * 101); // 0 to 100
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such
as System.out.println(), but you can also create your own methods to perform certain
actions:
Example
Create a method inside Main:
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
Example
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
Example
public class Main
{
static void myMethod(String fname)
{
System.out.println(fname + " Refsnes");
}
When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main
{
static void myMethod(String fname, int age)
{
System.out.println(fname + " is " + age);
}
Example
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}
Example
public class Main
{
static int myMethod(int x, int y)
{
return x + y;
}
Example
public class Main
{
static int myMethod(int x, int y)
{
return x + y;
}
Java Recursion
Recursion is the technique of making a function call itself. This technique provides a way
to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is
to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Example
Use recursion to add all of the numbers up to 10.
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working with Collection
objects, such as ArrayList, where primitive types cannot be used (the list can only store
objects):
Example
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}
Java Inheritance
Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We
group the "inheritance concept" into two categories:
Example
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
Remember from the Inheritance chapter that we use the extends keyword to inherit from
a class. Now we can create Pig and Dog objects and call the animalSound() method on
both of them:
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Interfaces
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends). The body
of the interface method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
1) To achieve security - hide certain details and only show the important details of an
object (interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces, separate
them with a comma (see example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":