Java Introduction
Java Introduction
INTRODUCTION
Java is a popular programming language, created in 1995.
Web applications
Games
Database connection
• Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is
short for "output". The println() method, short for "print line", is used to print a
value to the screen (or a file).
Don't worry too much about System, out and println(). Just know that you need
them together to print stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Java Output / Print
• You can add as many println() methods as you want. Note
that it will add a new line for each method:
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
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:
ExampleGet your own Java Server
Create a method inside Main:
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:
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message
(like "InputMismatchException").
You can read more about exceptions and how to handle errors in the Exceptions chapter.
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
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:
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:
Ex:
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);
}
}
// Outputs 5
You can have as many parameters as you want:
//filename: Main.java
public class Main {
int modelYear;
String modelName;
Modifier Description
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
default The code is only accessible in the same package.
This is used when you don't specify a modifier. You
will learn more about packages in the
Packages chapter
protected The code is accessible in the same package
and subclasses. You will learn more about
subclasses and super classes in the
Inheritance chapter
Non-Access Modifiers
abstract The class cannot be used to create objects (To access an abstract class, it must
be inherited from another class. You will learn more about inheritance and
abstraction in the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method does
not have a body, for example abstract void run();. The body is provided by the subclass
(inherited from). You will learn more about inheritance and abstraction in the Inheritance
and Abstraction chapters
Java Encapsulation
• The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:
• declare class variables/attributes as private
• provide public get and set methods to access and update the value of a
private variable
Get and Set
• You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide public get and set
methods.
• The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of
the variable, with the first letter in upper case:
Ex:
public class Person {
private String name; // private = restricted access
// method to read variable value
public String getName() {
return name;
}
// method to write variable value
public void setName(String newName) {
this.name = newName;
}
}
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable. The this
keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class:
Ex:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
However, as we try to access a private variable, we get an error:
Instead, we use the getName() and setName() methods to access and update the variable:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John“
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if
you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Java Packages
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:
• 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:
import java.util.Scanner;
Import a Package
To import a whole package, end the sentence with an asterisk sign (*). The
following example will import ALL the classes in the java.util package:
import java.util.*;
User-defined Packages
• To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer:
Mypackageclass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:
When we compiled the package in the example above, a new folder was created,
called "mypack".
To run the MyPackageClass.java file, write the following:
// 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.
The final Keyword
If you don't want other classes to inherit from a class,
use the final keyword:
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.
class InnerClass {
• In Java, it is also possible int y = 5;
to nest classes (a class }
within a class). The purpose }
of nested classes is to
group classes that belong public class Main {
together, which makes your public static void main(String[] args) {
code more readable and OuterClass myOuter = new OuterClass();
maintainable. OuterClass.InnerClass myInner = myOuter.new
InnerClass();
• To access the inner class, System.out.println(myInner.y + myOuter.x);
create an object of the }
outer class, and then create }
an object of the inner class:
// Outputs 15 (5 + 10)
Private Inner Class
class OuterClass {
int x = 10;
// Outputs 5
Access Outer Class From Inner Class
class OuterClass {
int x = 10;
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
abstract class Animal {
methods: public abstract void
• From the example given, it is animalSound();
not possible to create an
object of the Animal class: public void sleep() {
To access the abstract class, it System.out.println("Zzz");
must be inherited from another
class. Let's convert the Animal }
class we used in
the Polymorphism chapter to }
an abstract class:
// Abstract class class Main {
abstract class Animal {
public static void main(String[] args) {
// Abstract method (does not have a body)
public abstract void animalSound(); Pig myPig = new Pig(); // Create a Pig
// Regular method
object
public void sleep() { myPig.animalSound();
System.out.println("Zzz"); myPig.sleep();
}
}
}
// Subclass (inherit from Animal) }
class Pig extends Animal {
public void animalSound() {
Why And When To Use Abstract Classes and Methods?
// The body of animalSound() is provided To achieve security - hide certain details and only show the
here important details of an object.
Note: Abstraction can also be achieved with Interfaces,
System.out.println("The pig says: wee
wee");
}
}
Java Interface Example
// interface
• Another way to achieve
abstraction in Java, is with interface Animal {
interfaces. public void animalSound(); //
interface method (does not have
• An interface is a a body)
completely "abstract class" public void run(); // interface
that is used to group related method (does not have a body)
methods with empty }
bodies:
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:
// Interface
interface Animal { class Main {
public void animalSound(); // interface method (does not have
a body) public static void main(String[] args) {
public void sleep(); // interface method (does not have a body) Pig myPig = new Pig(); // Create a Pig
} object
// Pig "implements" the Animal interface
class Pig implements Animal {
myPig.animalSound();
public void animalSound() { myPig.sleep();
// 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");
}
}