LEC_2
LEC_2
Outline
• For-Each Loop , Break and continue
• Java Arrays
• Java - Object and Classes
• Class variable types
• Constructors
• Accessing Instance Variables and Methods
• Source File Declaration Rules
• Java Packages & API (Application Programming Interface)
1
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in
an array:
Syntax
for (type variableName : arrayName) {
if (i == 4) { 0
break; 1
} 2
System.out.println(i); 3
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
2
for (int i = 0; i < 10; i++) { 1
if (i == 4) { 2
continue; 3
} 5
System.out.println(i); 6
} 7
8
9
Java Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
String[] cars;
3
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
4
Java - Object and Classes:
class in Java
Class: A class is a large container that can contain all the code from variables,
functions, objects, etc.. To define a new class, it is enough to write the word class,
then give it a name, then open parentheses that specify its beginning and end.
Example:
class ClassName {
}
Now we will define a new class that contains 4 variables, in addition to a function that
displays the values of these variables when it is called.
Person.java
class Person {
String name;
String gender;
String job;
int age;
void printInfo() {
System.out.println("Name: " +name);
System.out.println("Gender: " +gender);
System.out.println("Job: " +job);
System.out.println("Age: " +age);
}
****** Any variables that are defined inside a class and outside any function are
called attributes, which means that any object of this class will have these attributes.
5
Object
- the object is an exact copy of a specific class. Since the object is a copy of the
class, we can say that an object cannot be created if there is no class.
Example
Person.java
String name;
String gender;
String job;
int age;
void printInfo() {
System.out.println("Name: " +name);
System.out.println("Gender: " +gender);
System.out.println("Job: " +job);
System.out.println("Age: " +age);
System.out.println();
}
6
Main.java
public class Main {
p1.name = "Mhamad";
p1.gender = "Male";
p1.job = "Programmer";
p1.age = 21;
p2.name = "Rose";
p2.gender = "Female";
p2.job = "Secretary";
p2.age = 22;
p3.name = "Ahmad";
p3.gender = "Male";
p3.job = "Doctor";
p3.age = 34;
p4.name = "Rabih";
p4.gender = "Male";
p4.job = "Engineer";
p4.age = 27;
p1.printInfo();
p2.printInfo();
p3.printInfo();
p4.printInfo();
}
}
7
Output:
Name: Mhamad
Gender: Male
Job: Programmer
Age: 21
Name: Rose
Gender: Female
Job: Secretary
Age: 22
Name: Ahmad
Gender: Male
Job: Doctor
Age: 34
Name: Rabih
Gender: Male
Job: Engineer
Age: 27
8
class Counter{
int count=0;
Counter(){
count++;
System.out.println(count);
} Output
1
public static void main(String args[]){
1
class Counter{
static int count=0;
Counter(){
count++;
System.out.println(count);
}
Output
1
public static void main(String args[]){
2
9
Example
class VariablesTypes {
int a;
public int b;
protected int c;
private int d;
static int e;
Java – Constructors:
A constructor initializes an object when it is created. It has the same name as its class
and is syntactically similar to a method. However, constructors have no explicit return
type. Typically, you will use a constructor to give initial values to the instance variables
defined by the class, or to perform any other start-up procedures required to create a
fully formed object.
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member variables to
zero. However, once you define your own constructor, the default constructor is no
longer used.
10
Java allows two types of constructors namely −
• No argument Constructors
• Parameterized Constructors
No argument Constructors
As the name specifies the no argument constructors of Java does not accept any
parameters instead, using these constructors the instance variables of a method will be
initialized with fixed values for all objects.
Example
Public class MyClass {
int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows
11
Example
Here is a simple example that uses a constructor −
// A simple constructor.
class MyClass {
int x;
Example:
Person.java
public Person() {
12
public Person(String n, String s, String j, int a) {
name = n;
gender = s;
job = j;
age = a;
}
void printInfo() {
System.out.println("Name: " +name);
System.out.println("Gender: " +gender);
System.out.println("Job: " +job);
System.out.println("Age: " +age);
System.out.println();
}
}
Main.java
public class Main {
p5.name = "Lina";
p5.gender = "Female";
p5.job = "Graphic Designer";
p5.age = 24;
p1.printInfo();
p2.printInfo();
p3.printInfo();
p4.printInfo();
p5.printInfo();
}
}
13
output
Name: Mohamad
Gender: Male
Job: Programmer
Age: 21
Name: Rose
Gender: Female
Job: Secretary
Age: 22
Name: Ahmad
Gender: Male
Job: Doctor
Age: 34
Name: Rabih
Gender: Male
Job: Engineer
Age: 27
Name: Lina
Gender: Female
Job: Graphic Designer
Age: 24
14
Example
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;
15
Source File Declaration Rules
As the last part of this section, let's now look into the source file declaration rules.
These rules are essential when declaring classes, import statements
and package statements in a source file.
• There can be only one public class per source file.
• A source file can have multiple non-public classes.
• The public class name should be the name of the source file as well which
should be appended by .java at the end. For example: the class name
is public class Employee{} then the source file should be as Employee.java.
• If the class is defined inside a package, then the package statement should
be the first statement in the source file.
• If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
• Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.
Classes have several access levels and there are different types of classes; abstract
classes, final classes, etc. We will be explaining about all these in the access modifiers
section.
Apart from the above mentioned types of classes, Java also has some special classes
called Inner classes and Anonymous classes.
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
16
The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles website
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 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
import java.util.Scanner;
class MyClass {
17
System.out.println("Enter username");
Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date
and time facilities, random-number generator and other utility classes.
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:
Example
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:
Example
└── root
└── mypack
└── MyPackageClass.java
18
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
Import Statements
In Java if a fully qualified name, which includes the package and the class name is given,
then the compiler can easily locate the source code or classes. Import statement is a
way of giving the proper location for the compiler to find that particular class.
For example, the following line would ask the compiler to load all the classes available
in directory java_installation/java/io −
import java.io.*;
First open notepad and add the following code. Remember this is the Employee class
and the class is a public class. Now, save this source file with the name Employee.java.
The Employee class has four instance variables - name, age, designation and salary.
The class has one explicitly defined constructor, which takes a parameter.
19
Example
import java.io.*;
public class Employee {
String name;
int age;
String designation;
double salary;
20
Following is the EmployeeTest class, which creates two instances of the class
Employee and invokes the methods for each object to assign values for each variable.
Save the following code in EmployeeTest.java file.
import java.io.*;
public class EmployeeTest {
public static void main(String args[]) {
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Now, compile both the classes and then run EmployeeTest to see the result as follows:
Output
C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
21
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
22