0% found this document useful (0 votes)
17 views

AP - Study Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

AP - Study Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Java Classes/Objects

Java is an object-oriented programming language.


Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:


Main.java
Create a class named "Main" with a variable x:
public class Main
{
int x = 5;
}
Remember that a class should always start with an uppercase first letter, and that the
name of the java file should match the class name.

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 create multiple objects of one class:


Example
Create two objects of Main:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

Using Multiple Classes

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:

public class Main


{
int x = 5;
int y = 3;
}

Another term for class attributes is fields.

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:

public class Main


{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class Main


{
int x;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}

Or override existing values:

Example
Change the value of x to 25:

public class Main


{
int x = 10;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}

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:

public class Main


{
int x = 5;
public static void main(String[] args)
{
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
}

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!");
}

public static void main(String[] args)


{
myMethod();
}
}

Static vs. Non-Static

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

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method on the object
}
}

Access Methods With an Object


Example
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:

// Create a Main class


public class Main
{
// Create a fullThrottle() method
public void fullThrottle()
{
System.out.println("The car is going as fast as it can!");
}
// Create a speed() method and add a parameter
public void speed(int maxSpeed)
{
System.out.println("Max speed is: " + maxSpeed);
}

// Inside main, call the methods on the myCar object


public static void main(String[] args)
{
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
Example explained

1) We created a custom Main class with the class keyword.


2) We created the fullThrottle() and speed() methods in the Main class.
3) The fullThrottle() method and the speed() method will print out some text, when they
are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of
the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that
runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the
program using the name of the object (myCar), followed by a dot (.), followed by the name
of the method (fullThrottle(); and speed(200);). Notice that we add an int parameter
of 200 inside the speed() method.

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).

Using Multiple Classes

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!");
}

public void speed(int maxSpeed)


{
System.out.println("Max speed is: " + maxSpeed);
}
}
Second.java
class Second
{
public static void main(String[] args)
{
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}

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:

// Create a Main class


public class Main
{
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main()
{
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args)


{
Main myObj = new Main();
System.out.println(myObj.x); // Print the value of x
}
}
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the constructor
we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor
(5), which will set the value of x to 5:

Example
public class Main
{
int x;

public Main(int y)
{
x = y;
}

public static void main(String[] args)


{
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}

Example
public class Main
{
int modelYear;
String modelName;

public Main(int year, String name)


{
modelYear = year;
modelName = name;
}

public static void main(String[] args)


{
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:

Example
Create a variable of type String and assign it a value:

String greeting = "Hello";

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());

More String Methods


There are many string methods available, for
example toUpperCase() and toLowerCase():

Example
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a
specified text in a string (including whitespace):

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:

Escape character Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash
The sequence \" inserts a double quote in a string:

Example
String txt = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

Example
String txt = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:


Example
String txt = "The character \\ is called backslash.";

Six other escape sequences are valid in Java:

Code Result

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

Adding Numbers and Strings

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:

public class Main


{
static void myMethod() {
// code to be executed
}
}
Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object of the
Main class. You will learn more about objects and how to access methods through
objects later in this tutorial.
 void means that this method does not have a return value. You will learn more
about return values later in this chapter

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:

public class Main


{
static void myMethod()
{
System.out.println("I just got executed!");
}

public static void main(String[] args)


{
myMethod();
}
}

Example
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}

public static void main(String[] args)


{
myMethod();
myMethod();
myMethod();
}
}
Java Method Parameters
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside
the method.
Parameters are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method
to print the full name:

Example
public class Main
{
static void myMethod(String fname)
{
System.out.println(fname + " Refsnes");
}

public static void main(String[] args)


{
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}

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);
}

public static void main(String[] args)


{
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Return Values
The void keyword, used in the examples above, indicates that the method should not
return a value. If you want the method to return a value, you can use a primitive data type
(such as int, char, etc.) instead of void, and use the return keyword inside the method:

Example
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}

public static void main(String[] args)


{
System.out.println(myMethod(3));
}
}

Example
public class Main
{
static int myMethod(int x, int y)
{
return x + y;
}

public static void main(String[] args)


{
System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)

Example
public class Main
{
static int myMethod(int x, int y)
{
return x + y;
}

public static void main(String[] args)


{
int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)

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.

public class Main


{
public static void main(String[] args)
{
int result = sum(10);
System.out.println(result);
}
public static int sum(int k)
{
if (k > 0)
{
return k + sum(k - 1);
}
else
{
return 0;
}
}
}
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class

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

Creating Wrapper Objects


To create a wrapper object, use the wrapper class instead of the primitive type. To get the
value, you can just print the object:

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:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.


In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

Example
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();

// 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);
}
}

Did you notice the protected modifier in Vehicle?


We set the brand attribute in Vehicle to a protected access modifier. If it was set
to private, the Car class would not be able to access it.

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods
to perform different tasks.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Vehicle {


...
}

class Car extends Vehicle {


...
}
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

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 Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

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

Another way to achieve abstraction in Java, is with interfaces.


An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

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)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

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)

Why And When To Use Interfaces?

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 DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

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).

Java try and catch


The try statement allows you to define a block of code to be tested for errors while it is
being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
The try and catch keywords come in pairs:

Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Consider the following example:


This will generate an error, because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

The output will be something like this:


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
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.");
}
}
}

The throw keyword


The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":

public class Main {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy