[go: up one dir, main page]

0% found this document useful (0 votes)
8 views29 pages

First Mock Test

The document explains Object-Oriented Programming (OOP) in Java, highlighting its advantages over procedural programming, such as improved code structure and reusability. It covers key concepts like classes, objects, methods, constructors, and inheritance, providing examples for better understanding. Additionally, it discusses method overloading, access modifiers, and the use of packages in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

First Mock Test

The document explains Object-Oriented Programming (OOP) in Java, highlighting its advantages over procedural programming, such as improved code structure and reusability. It covers key concepts like classes, objects, methods, constructors, and inheritance, providing examples for better understanding. Additionally, it discusses method overloading, access modifiers, and the use of packages in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Java - What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code
and shorter development time

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.

Java - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

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

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and
methods from the class.

Method and function

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 MyClass:

public class MyClass {

static void myMethod() {

// code to be executed

Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the MyClass class and not an
object of the MyClass 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 MyClass {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

Run example »

A method can also be called multiple times:

Example
public class MyClass {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();
myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

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 MyClass {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");
myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Run example »

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 MyClass {

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

// 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 {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {


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

// Outputs 8 (5 + 3)

Run example »

This example returns the sum of a method's two parameters:

Example
public class MyClass {

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)

Run example »

You can also store the result in a variable (recommended, as it is easier to read
and maintain):

Example
public class MyClass {

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)

Run example »

A Method with If...Else


It is common to use if...else statements inside methods:

Example
public class MyClass {

// Create a checkAge() method with an integer variable called age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old


enough!");

// If age is greater than 18, print "access granted"

} else {
System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an age


of 20

// Outputs "Access granted - You

Java Method Overloading


❮ PreviousNext ❯

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

Example
int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

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;

static double plusMethodDouble(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethodInt(8, 5);

double myNum2 = plusMethodDouble(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

Run example »

Instead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for


both int and double:

Example
static int plusMethod(int x, int y) {

return x + y;

}
static double plusMethod(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

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:

// Create a MyClass class

public class MyClass {

int x; // Create a class attribute


// Create a class constructor for the MyClass class

public MyClass() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

MyClass myObj = new MyClass(); // Create an object of class


MyClass (This will call the constructor)

System.out.println(myObj.x); // Print the value of x

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

public static void main(String[] args) {

MyClass myObj = new MyClass(5);

System.out.println(myObj.x);

// Outputs 5

Run example »

You can have as many parameters as you want:

Example
public class Car {

int modelYear;

String modelName;
public Car(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Car myCar = new Car(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

Modifiers
By now, you are quite familiar with the public keyword that appears in
almost all of our examples:

public class MyClass

The public keyword is an access modifier, meaning that it is used to set


the access level for classes, attributes, methods and constructors.

We divide modifiers into two groups:

 Access Modifiers - controls the access level


 Non-Access Modifiers - do not control access level, but provides other
functionality

Access Modifiers
For classes, you can use either public or default:
Modifier Description Try
it

publi The class is accessible by any Try


c other class it »

default The class is only accessible Try


by classes in the same it »
package. This is used when
you don't specify a modifier.
You will learn more about
packages in the Packages
chapter

For attributes, methods and constructors, you can use the one of the
following:

Java Packages & API


A package in Java is used to group related classes. Think of it as a folder in a
file directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.

The library contains components for managing input, database programming,


and much much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole package
that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use


the import keyword:

Syntax
import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

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;

In the example above, java.util is a package, while Scanner is a class


of the java.util package.

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:

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.


Car class (subclass) inherits the attributes and
In the example below, the
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);

}
Run example »

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 Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which
you will learn more about in the next chapter).
The abstract keyword is a non-access modifier, used for classes and
methods:

 Abstract class: is a restricted class that cannot be used to create objects


(to access it, it must be inherited from another class).

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

An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

From the example above, it is not possible to create an object of the Animal
class:

Animal myObj = new Animal(); // will generate an error

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

abstract class Animal {


// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

}
Run example »

Why And When To Use Abstract Classes and Methods?


To achieve security - hide certain details and only show the important details of
an object.

Java File Handling


The File class from the java.io package, allows us to work with files.

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

File myObj = new File("filename.txt"); // Specify the filename

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:

Method Type Description

canRead() Boolean Tests whether


the file is
readable or
not

canWrite() Boolean Tests whether


the file is
writable or not
createNewFile() Boolean Creates an
empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether


the file exists

getName() String Returns the


name of the
file

getAbsolutePath String Returns the


() absolute
pathname of
the file

length() Long Returns the


size of the file
in bytes

list() String[] Returns an


array of the
files in the
directory

mkdir() Boolea
n
All String Methods
The String class has a set of built-in methods that you can use on strings.

Method Description Return


Type

charAt() Returns the char


character at the
specified index
(position)

codePointAt() Returns the int


Unicode of the
character at the
specified index

codePointBefore() Returns the int


Unicode of the
character
before the
specified index

codePointCount() Returns the int


Unicode in the
specified text
range of this
String

compareTo() Compares two int


strings
lexicographicall
y

compareToIgnoreCase Compares two int


() strings
lexicographicall
y, ignoring case
differences
concat() Appends a String
string to the
end of another
string

contains() Checks whether boolean


a string
contains a
sequence of
characters

contentEquals() Checks whether boolean


a string
contains the
exact same
sequence of
characters of
the specified
CharSequence
or StringBuffer

copyValueOf() Returns a String String


that represents
the characters
of the character
array

endsWith() Checks whether boolean


a string ends
with the
specified
character(s)

equals() Compares two boolean


strings. Returns
true if the
strings are
equal, and false
if not

equalsIgnoreCase() Compares two boolean


strings, ignoring
case
considerations

format() Returns a String


formatted string
using the
specified locale,
format string,
and arguments

getBytes() Encodes this byte[]


String into a
sequence of
bytes using the
named charset,
storing the
result into a
new byte array

getChars() Copies void


characters from
a string to an
array of chars

hashCode() Returns the int


hash code of a
string

indexOf() Returns the int


position of the
first found
occurrence of
specified
characters in a
string

intern() Returns the String


index within this
string of the
first occurrence
of the specified
character,
starting the
search at the
specified index

isEmpty() Checks whether boolean


a string is
empty or not

lastIndexOf() Returns the int


position of the
last found
occurrence of
specified
characters in a
string

length() Returns the int


length of a
specified string

matches() Searches a boolean


string for a
match against a
regular
expression, and
returns the
matches

offsetByCodePoints() Returns the int


index within this
String that is
offset from the
given index by
codePointOffset
code points

regionMatches() Tests if two boolean


string regions
are equal
replace() Searches a String
string for a
specified value,
and returns a
new string
where the
specified values
are replaced

replaceFirst() Replaces the String


first occurrence
of a substring
that matches
the given
regular
expression with
the given
replacement

replaceAll() Replaces each String


substring of this
string that
matches the
given regular
expression with
the given
replacement

split() Splits a string String[]


into an array of
substrings

startsWith() Checks whether boolean


a string starts
with specified
characters

subSequence() Returns a new CharSequenc


character e
sequence that is
a subsequence
of this sequence

substring() Extracts the String


characters from
a string,
beginning at a
specified start
position, and
through the
specified
number of
character

toCharArray() Converts this char[]


string to a new
character array

toLowerCase() Converts a String


string to lower
case letters

toString() Returns the String


value of a String
object

toUpperCase() Converts a String


string to upper
case letters

trim() Removes String


whitespace
from both ends
of a string

valueOf() Returns the


primitive value
of a String

You might also like