The Main Method
The Main Method
The Main Method
For example, the following code declares a method called test, which does
not return anything and has no parameters:void test()
The method's parameters are declared inside the parentheses that follow
the name of the method.
For main, it's an array of strings called args. We will use it in our next
lesson, so don't worry if you don't understand it all now.
String Concatenation
The + (plus) operator between strings adds them together to make a new
string. This process is called concatenation.
The resulted string is the first string put together with the second string.
For example:
String firstName, lastName;
firstName = "David";
lastName = "Williams";
While Java provides many different methods for getting user input,
the Scanner object is the most common, and perhaps the easiest to
implement. Import the Scanner class to use the Scanner object, as seen
here:import java.util.Scanner;
In order to use the Scanner class, create an instance of the class by using
the following syntax:Scanner myVar = new Scanner(System.in);
You can now read in different kinds of input data that the user enters.
Here are some methods that are available through the Scanner class:
Read a byte - nextByte()
Read a short - nextShort()
Read an int - nextInt()
Read a long - nextLong()
Read a float - nextFloat()
Read a double - nextDouble()
Read a boolean - nextBoolean()
Read a complete line - nextLine()
Read a word - next()
class MyClass {
public static void main(String[ ] args) {
Scanner myVar = new Scanner(System.in);
System.out.println(myVar.nextLine());
}
}Try It Yourself
This will wait for the user to input something and print that input.
The code might seem complex, but you will understand it all in the
upcoming lessons.
The example below tests day against a set of values and prints a
corresponding message.
int day = 3;
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
// Outputs "Wednesday"Try It Yourself
for Loops
Another loop structure is the for loop. A for loop allows you to efficiently
write a loop that needs to execute a specific number of times.
Syntax:for (initialization; condition; increment/decrement) {
statement(s)
}
Initialization: Expression executes only once during the beginning of loop
Condition: Is evaluated each time the loop iterates. The loop executes the
statement repeatedly, until this condition returns false.
Increment/Decrement: Executes after each iteration of the loop.
/* Outputs
1
2
3
4
5
*/Try It Yourself
This initializes x to the value 1, and repeatedly prints the value of x, until
the condition x<=5 becomes false. On each iteration, the statement x++
is executed, incrementing x by one.
Notice the semicolon (;) after initialization and condition in the syntax.
The break and continue statements change the loop's execution flow.
The break statement terminates the loop and transfers execution to the
statement immediately following the loop.
Example:
int x = 1;
while(x > 0) {
System.out.println(x);
if(x == 4) {
break;
}
x++;
}
/* Outputs
1
2
3
4
*/Try It Yourself
The continue statement causes the loop to skip the remainder of its body
and then immediately retest its condition prior to reiterating. In other
words, it makes the loop skip to its next iteration.
Example:
for(int x=10; x<=40; x=x+10) {
if(x == 30) {
continue;
}
System.out.println(x);
}
/* Outputs
10
20
40
*/Try It Yourself
As you can see, the above code skips the value of 30, as directed by
the continue statement.
Arrays
Now, you need to define the array's capacity, or the number of elements it
will hold. To accomplish this, use the keyword new.int[ ] arr = new int[5];
The code above declares an array of 5 integers.
In an array, the elements are ordered and each has a specific and constant
position, which is called an index.
Initializing Arrays
The enhanced for loop (sometimes called a "for each" loop) is used to
traverse elements in arrays.
The advantages are that it eliminates the possibility of bugs and makes
the code easier to read.
Example:
int[ ] primes = {2, 3, 5, 7};
/*
2
3
5
7
*/Try It Yourself
The enhanced for loop declares a variable of a type compatible with the
elements of the arraybeing accessed. The variable will be available within
the for block, and its value will be the same as the current array element.
So, on each iteration of the loop, the variable t will be equal to the
corresponding element in the array.
Notice the colon after the variable in the syntax.
Multidimensional Arrays
Multidimensional arrays are array that contain other arrays. The two-
dimensional array is the most basic multidimensional array.
To create multidimensional arrays, place each array within its own set of
square brackets. Example of a two-dimensional array:int[ ][ ] sample =
{ {1, 2, 3}, {4, 5, 6} };
This declares an array with two arrays as its elements.
To access an element in the two-dimensional array, provide two indexes,
one for the array, and another for the element inside that array.
The following example accesses the first element in the second array of
sample.
int x = sample[1][0];
System.out.println(x);
The array's two indexes are called row index and column index.
Multidimensional Arrays
You can get and set a multidimensional array's elements using the same
pair of square brackets.
Example:
int[ ][ ] myArr = { {1, 2, 3}, {4}, {5, 6, 7} };
myArr[0][2] = 42;
int x = myArr[1][0]; // 4Try It Yourself
The above two-dimensional array contains three arrays. The first array has
three elements, the second has a single element and the last of these has
three elements.
In Java, you're not limited to just two-dimensional arrays. Arrays can be
nested within arrays to as many levels as your program needs. All you
need to declare an array with more than two dimensions, is to add as
many sets of empty brackets as you need. However, these are harder to
maintain.
Remember, that all array members must be of the same type.
Object-Orientation
Classes
A class describes what the object will be, but is separate from the object itself.
In other words, classes can be described as blueprints, descriptions, or definitions
for an object. You can use the same class as a blueprint for creating multiple
objects. The first step is to define the class, which then becomes a blueprint for
object creation.
Each class has a name, and each is used to define attributes and behavior.
Some examples of attributes and behavior:
Methods
Method Parameters
You can also create a method that takes some data, called parameters,
along with it when you call it. Write parameters within the method's
parentheses.
For example, we can modify our sayHello() method to take and output
a String parameter.
class MyClass {
}
// Hello David
// Hello AmyTry It Yourself
Access Modifiers
Now let's discuss the public keyword in front of the main method.public
static void main(String[ ] args)
public is an access modifier, meaning that it is used to set the level of
access. You can use access modifiers for classes, attributes, and methods.
For classes, the available modifiers are public or default (left blank), as
described below:
public: The class is accessible by any other class.
default: The class is accessible only by classes in the same package.
Getters and Setters are used to effectively protect your data, particularly
when creating classes. For each variable, the get method returns its value,
while the set method sets the value.
Getters start with get, followed by the variable name, with the first letter
of the variable name capitalized.
Setters start with set, followed by the variable name, with the first letter
of the variable name capitalized.
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
The getter method returns the value of the attribute.
The setter method takes a parameter and assigns it to the attribute.
The keyword this is used to refer to the current object.
Basically, this.color is the color attribute of the current object.
Getters & Setters
Once our getter and setter have been defined, we can use it in our main:
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
Getters and setters allow us to have control over the values. You may, for
example, validate the given value in the setter before actually setting the
value.
Getters and setters are fundamental building blocks for encapsulation,
which will be covered in the next module.
Constructors
Using Constructors
Constructors
Vehicle() {
this.setColor("Red");
}
Vehicle(String c) {
this.setColor(c);
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
The class above has two constructors, one without any parameters setting
the color attribute to a default value of "Red", and another constructor that
accepts a parameter and assigns it to the attribute.
1/1
Math.pow() takes two parameters and returns the first parameter raised
to the power of the second parameter.
double p = Math.pow(2, 3); // 8.0Try It Yourself
There are a number of other methods available in the Math class,
including:
sqrt() for square root, sin() for sine, cos() for cosine, and others.
Static
Static
final
When you move/create a class in your package, the following code will
appear at the top of the list of files.package samples;
This indicates the package to which the class belongs.
Now, we need to import the classes that are inside a package in our main
to be able to use them.
The following example shows how to use the Vehicle class of
the samples package.import samples.Vehicle;
class MyClass {
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
v1.horn();
}
}
Two major results occur when a class is placed in a package. First, the
name of the packagebecomes a part of the name of the class.
Second, the name of the package must match the directory structure
where the corresponding class file resides.
Use a wildcard to import all classes in a package.
For example, import samples.* will import all classes in the
samples package.
Encapsulation
Encapsulation
The class inheriting the properties of another is the subclass (also called
derived class, or child class); the class whose properties are inherited is
the superclass (base class, or parent class).
When one class is inherited from another class, it inherits all of the
superclass' non-private variables and methods.
Example:class Animal {
protected int legs;
public void eat() {
System.out.println("Animal eats");
}
}
Recall the protected access modifier, which makes the members visible
only to the subclasses.
Inheritance
class Program {
public static void main(String[ ] args) {
B obj = new B();
}
}
/*Outputs
"New A"
"New B"
*/Try It Yourself
Polymorphism
b.makeSound();
//Outputs "Meow"Try It Yourself
Method Overriding
As we saw in the previous lesson, a subclass can define a behavior that's specific
to the subclass type, meaning that a subclass can implement a parent
class method based on its requirement.
This feature is known as method overriding.
Example:
class Animal {
public void makeSound() {
System.out.println("Grr...");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow");
}
}Try It Yourself
In the code above, the Cat class overrides the makeSound() method of its
superclass Animal.
Method Overloading
When methods have the same name, but different parameters, it is known
as method overloading.
This can be very useful when you need the same method functionality for
different types of parameters.
The following example illustrates a method that returns the maximum of its two
parameters.int max(int a, int b) {
if(a > b) {
return a;
}
else {
return b;
}
}
The method shown above will only work for parameters of type integer.
However, we might want to use it for doubles, as well. For that, you need to
overload the max method:
Abstraction
Data abstraction provides the outside world with only essential
information, in a process of representing essential features without
including implementation details.
A good real-world example is a book. When you hear the term book, you
don't know the exact specifics, such as the page count, the color, or the
size, but you understand the idea, or abstraction, of a book.
The concept of abstraction is that we focus on essential qualities, rather
than the specific characteristics of one particular example.
Abstract Class
For example, we can define our Animal class as abstract: abstract class Animal {
int legs = 0;
abstract void makeSound();
}
The makeSound method is also abstract, as it has no implementation in the
superclass.
We can inherit from the Animal class and define the makeSound() method for the
subclass:
Every Animal makes a sound, but each has a different way to do it. That's why
we define an abstract class Animal, and leave the implementation of how they
make sounds to the subclasses.
This is used when there is no meaningful definition for the method in the
superclass.
Interfaces
Interfaces
interface Animal {
public void eat();
public void makeSound();
}
When you implement an interface, you need to override all of its methods.
Type Casting
To cast a value to a specific type, place the type in parentheses and position it in
front of the value.
Example:
The code above is casting the value 3.14 to an integer, with 3 as the resulting
value.
Another example:
double a = 42.571;
int b = (int) a;
System.out.println(b);
//Outputs 42Try It Yourself
Java supports automatic type casting of integers to floating points, since there is
no loss of precision.
On the other hand, type casting is mandatory when assigning floating point
values to integer variables.
Type Casting
Downcasting
Anonymous Classes
Anonymous classes are a way to extend the existing classes on the fly.
For example, consider having a class Machine:class Machine {
public void start() {
System.out.println("Starting...");
}
}
When creating the Machine object, we can change the start method on the fly.
After the constructor call, we have opened the curly braces and have overridden
the start method's implementation on the fly.
The @Override annotation is used to make your code easier to understand,
because it makes it more obvious when methods are overridden.
Anonymous Classes
The modification is applicable only to the current object, and not the class
itself. So if we create another object of that class, the start method's
implementation will be the one defined in the class.
class Machine {
public void start() {
System.out.println("Starting...");
}
}
public static void main(String[ ] args) {
Machine m1 = new Machine() {
@Override public void start() {
System.out.println("Wooooo");
}
};
Machine m2 = new Machine();
m2.start();
}
//Outputs "Starting..."
Inner Classes
class Robot {
int id;
Robot(int i) {
id = i;
Brain b = new Brain();
b.think();
}
}Try It Yourself
The class Robot has an inner class Brain. The inner class can access all of the
member variables and methods of its outer class, but it cannot be accessed from
any outside class.
Comparing Objects
Remember that when you create objects, the variables store references to the
objects.
So, when you compare objects using the equality testing operator (==), it
actually compares the references and not the object values.
Example:
class Animal {
String name;
Animal(String n) {
name = n;
}
}
class MyClass {
public static void main(String[ ] args) {
Animal a1 = new Animal("Robby");
Animal a2 = new Animal("Robby");
System.out.println(a1 == a2);
}
}
//Outputs falseTry It Yourself
Despite having two objects with the same name, the equality testing returns
false, because we have two different objects (two different references or memory
locations).
equals()
Each object has a predefined equals() method that is used for semantical
equality testing.
But, to make it work for our classes, we need to override it and check the
conditions we need.
There is a simple and fast way of generating the equals() method, other than
writing it manually.
Just right click in your class, go to Source->Generate hashCode() and
equals()...
You can use the same menu to generate other useful methods, such
as getters and setters for your class attributes.
Enums
Java API
The Java API is a collection of classes and interfaces that have been
written for you to use.
The Java API Documentation with all of the available APIs can be located
on the Oracle website at
http://docs.oracle.com/javase/7/docs/api/
Once you locate the package you want to use, you need to import it into
your code.
The package can be imported using the import keyword.
For example:import java.awt.*;
The awt package contains all of the classes for creating user interfaces
and for painting graphics and images.
The wildcard character (*) is used to import all of the classes in
the package.
Exceptions
Exception Handling
Exceptions can be caught using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.
Syntax:try {
//some code
} catch (Exception e) {
//some code to handle errors
}
A catch statement involves declaring the type of exception you are trying to
catch. If an exceptionoccurs in the try block, the catch block that follows
the try is checked. If the type of exception that occurred is listed in
a catch block, the exception is passed to the catch block much as
an argument is passed into a method parameter.
The Exception type can be used to catch all possible exceptions.
The example below demonstrates exception handling when trying to access
an array index that does not exist:
Without the try/catch block this code should crash the program, as a[5] does not
exist.
Notice the (Exception e) statement in the catch block - it is used to catch all
possible Exceptions.
throw
The throw keyword allows you to manually generate exceptions from your
methods. Some of the numerous available exception types include the
IndexOutOfBoundsException, IllegalArgumentException, ArithmeticException, and
so on.
For example, we can throw an ArithmeticException in our method when the
parameter is 0.
The throws statement in the method definition defines the type of Exception(s)
the method can throw.
Next, the throw keyword throws the corresponding exception, along with a
custom message.
If we call the div method with the second parameter equal to 0, it will throw an
ArithmeticException with the message "Division by Zero".
Multiple exceptions can be defined in the throws statement using a comma-
separated list.
Threads
class MyClass {
public static void main(String[ ] args) {
Loader obj = new Loader();
obj.start();
}
}Try It Yourself
As you can see, our Loader class extends the Thread class and overrides
its run() method.
When we create the obj object and call its start() method,
the run() method statements execute on a different thread.
Every Java thread is prioritized to help the operating system determine the order
in which to schedule threads. The priorities range from 1 to 10, with each thread
defaulting to priority 5. You can set the thread priority with
the setPriority() method.
Threads
class MyClass {
public static void main(String[ ] args) {
Thread t = new Thread(new Loader());
t.start();
}
}Try It Yourself
The Thread.sleep() method pauses a Thread for a specified period of time. For
example, calling Thread.sleep(1000); pauses the thread for one second. Keep
in mind that Thread.sleep() throws an InterruptedException, so be sure to
surround it with a try/catch block.
It may seem that implementing the Runnable interface is a bit more complex
than extending from the Thread class. However, implementing the
Runnable interface is the preferred way to start a Thread, because it enables you
to extend from another class, as well.
Types of Exceptions
There are two exception types, checked and unchecked (also called
runtime). The main difference is that checked exceptions are checked
when compiled, while unchecked exceptions are checked at runtime.
As mentioned in our previous lesson, Thread.sleep() throws an
InterruptedException. This is an example of a checked exception. Your
code will not compile until you've handled the exception.
ArrayList
The Java API provides special classes to store and manipulate groups of
objects.
One such class is the ArrayList. Standard Java arrays are of a fixed length,
which means that after they are created, they cannot expand or shrink.
On the other hand, ArrayLists are created with an initial size, but when
this size is exceeded, the collection is automatically enlarged.
When objects are removed, the ArrayList may shrink in size. Note that
the ArrayList class is in the java.util package, so it's necessary to import
it before using it.
Create an ArrayList as you would any object.import java.util.ArrayList;
//...
ArrayList colors = new ArrayList();
You can optionally specify a capacity and type of objects
the ArrayList will hold:ArrayList<String> colors = new
ArrayList<String>(10);
The code above defines an ArrayList of Strings with 10 as its initial size.
ArrayLists store objects. Thus, the type specified must be a class type. You
cannot pass, for example, int as the objects' type. Instead, use the
special class types that correspond to the desired value type, such
as Integer for int, Double for double, and so on.
ArrayList
The ArrayList class provides a number of useful methods for manipulating its
objects.
The add() method adds new objects to the ArrayList. Conversely, the remove()
methods remove objects from the ArrayList.
Example:
import java.util.ArrayList;
System.out.println(colors);
}
}
// Output: [Red, Blue, Orange]Try It Yourself
The most notable difference between the LinkedList and the ArrayList is in the
way they store objects.
The ArrayList is better for storing and accessing data, as it is very similar to a
normal array.
The LinkedList is better for manipulating data, such as making numerous
inserts and deletes.
In addition to storing the object, the LinkedList stores the memory address (or
link) of the element that follows it. It's called a LinkedList because each element
contains a link to the neighboring element.
You can use the enhanced for loop to iterate over its elements.
for(String s: c) {
System.out.println(s);
}
/* Output:
Red
Blue
Orange
*/Try It Yourself
Summary:
- Use an ArrayList when you need rapid access to your data.
- Use a LinkedList when you need to make a large number of inserts and/or
deletes.
HashMap
Arrays and Lists store elements as ordered collections, with each element given
an integer index.
HashMap is used for storing data collections as key and value pairs. One object
is used as a key (index) to another object (the value).
The put, remove, and get methods are used to add, delete, and access values
in the HashMap.
Example:
import java.util.HashMap;
public class MyClass {
public static void main(String[ ] args) {
HashMap<String, Integer> points = new HashMap<String, Integer>();
points.put("Amy", 154);
points.put("Dave", 42);
points.put("Rob", 733);
System.out.println(points.get("Dave"));
}
}
// Outputs 42Try It Yourself
We have created a HashMap with Strings as its keys and Integers as its values.
Use the get method and the corresponding key to access
the HashMap elements.
HashMap
Arrays and Lists store elements as ordered collections, with each element given
an integer index.
HashMap is used for storing data collections as key and value pairs. One object
is used as a key (index) to another object (the value).
The put, remove, and get methods are used to add, delete, and access values
in the HashMap.
Example:
import java.util.HashMap;
public class MyClass {
public static void main(String[ ] args) {
HashMap<String, Integer> points = new HashMap<String, Integer>();
points.put("Amy", 154);
points.put("Dave", 42);
points.put("Rob", 733);
System.out.println(points.get("Dave"));
}
}
// Outputs 42Try It Yourself
We have created a HashMap with Strings as its keys and Integers as its values.
Use the get method and the corresponding key to access
the HashMap elements.