First Mock Test
First Mock Test
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and
methods from the class.
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 MyClass:
// code to be executed
Example Explained
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
myMethod();
Run example »
Example
public class MyClass {
myMethod();
myMethod();
myMethod();
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 MyClass {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Run example »
Multiple Parameters
You can have as many parameters as you like:
Example
public class MyClass {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
// Liam is 5
// Jenny is 8
// Anja is 31
Run example »
Note that when you are working with multiple parameters, the method call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.
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 MyClass {
return 5 + x;
// Outputs 8 (5 + 3)
Run example »
Example
public class MyClass {
return x + y;
System.out.println(myMethod(5, 3));
// Outputs 8 (5 + 3)
Run example »
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
Example
public class MyClass {
return x + y;
}
System.out.println(z);
// Outputs 8 (5 + 3)
Run example »
Example
public class MyClass {
} else {
System.out.println("Access granted - You are old enough!");
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
Example
int myMethod(int x)
float myMethod(float x)
Consider the following example, which have two methods that add numbers of
different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
return x + y;
Run example »
Instead of defining two methods that should do the same thing, it is better to
overload one.
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
Run example »
Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.
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:
public MyClass() {
// Outputs 5
Run example »
Note that the constructor name must match the class name, and it cannot
have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
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 MyClass {
int x;
public MyClass(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
Run example »
Example
public class Car {
int modelYear;
String modelName;
public Car(int year, String name) {
modelYear = year;
modelName = name;
Modifiers
By now, you are quite familiar with the public keyword that appears in
almost all of our examples:
Access Modifiers
For classes, you can use either public or default:
Modifier Description Try
it
For attributes, methods and constructors, you can use the one of the
following:
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.
Syntax
import package.name.Class; // Import a single class
Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our
example, we will use the nextLine() method, which is used to read a
complete line:
Example
class Vehicle {
System.out.println("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar
object
myCar.honk();
}
Run example »
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited
methods to perform different tasks.
...
...
Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
System.out.println("Zzz");
From the example above, it is not possible to create an object of the Animal
class:
To access the abstract class, it must be inherited from another class. Let's
convert the Animal class we used in the Polymorphism chapter to an abstract
class:
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.
Example
// Abstract class
// Regular method
System.out.println("Zzz");
class MyMainClass {
myPig.animalSound();
myPig.sleep();
}
Run example »
To use the File class, create an object of the class, and specify the filename or directory name:
Example
import java.io.File; // Import the File class
If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information about files. For
example:
mkdir() Boolea
n
All String Methods
The String class has a set of built-in methods that you can use on strings.