0% found this document useful (0 votes)
2 views

LEC_2

This document covers fundamental concepts in Java programming, including for-each loops, arrays, classes, objects, and constructors. It explains how to declare and manipulate arrays, define classes with instance and class variables, and create objects using constructors. Additionally, it discusses source file declaration rules and the use of Java packages and APIs for better code organization.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

LEC_2

This document covers fundamental concepts in Java programming, including for-each loops, arrays, classes, objects, and constructors. It explains how to declare and manipulate arrays, define classes with instance and class variables, and create objects using constructors. Additionally, it discusses source file declaration rules and the use of Java packages and APIs for better code organization.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Lecture 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) {

// code block to be executed

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Volvo


for (String i : cars) { BMW
Ford
System.out.println(i); Mazda
}

Java Break and continue


You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

for (int i = 0; i < 10; i++) {

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.

To declare an array, define the variable type with square brackets:

String[] cars;

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in 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.

Change an Array Element


To change the value of a specific element, refer to the index number:

Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

System.out.println(cars[0]);

// Now outputs Opel instead of Volvo

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.

- So in the concept of object-oriented programming, we create a specific class


called blue print, which means (the raw copy or the original copy), and then we
create one or more copies of this class and do with them what we want without
changing the contents of the main class, and thus we have preserved the codes
of the main class because we modify the copies and not directly.

- Since the object is an instance of the class. To define an object of a particular


class, you must specify the name of the class and then specify a name for the
object.

Person ahmad = new Person();

Example
Person.java

public 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);
System.out.println();
}

6
Main.java
public class Main {

public static void main(String[] args) {

Person p1 = new Person();


Person p2 = new Person();
Person p3 = new Person();
Person p4 = new Person();

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

A class can contain any of the following variable types:


• Local variables − Variables defined inside methods, constructors or blocks
are called local variables. The variable will be declared and initialized within
the method and the variable will be destroyed when the method has
completed.
• Instance variables − Instance variables are variables within a class but
outside any method. These variables are initialized when the class is
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
• Class variables − Class variables are variables declared within a class,
outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Following is some of the important topics that need to be discussed when looking into
classes of the Java Language.

8
class Counter{
int count=0;

Counter(){
count++;
System.out.println(count);
} Output
1
public static void main(String args[]){
1

Counter c1 = new Counter(); 1


Counter c2 = new Counter();
Counter c3 = new Counter();
}
}

class Counter{
static int count=0;

Counter(){
count++;
System.out.println(count);
}
Output
1
public static void main(String args[]){
2

Counter c1=new Counter(); 3


Counter c2=new Counter();
Counter c3=new Counter();
}
}

9
Example
class VariablesTypes {
int a;
public int b;
protected int c;
private int d;

static int e;

public int sum(int x, int y) {


int z = x + y;
return z;
}
}
*** (a, b ,c, d) are considered Instance Variables because they are defined inside the class
and outside any function or block.
the variables ( x, y, z ) are considered Local Variables because they are defined inside the
function.
e is considered class variable because its type is Class.

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.

Following is the syntax of a constructor −


class ClassName {
ClassName( ) {
}
}

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

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}

This would produce the following result


100 100
Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a
method, just declare them inside the parentheses after the constructor's name.

11
Example
Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

This would produce the following result −


10 20

Example:
Person.java

public class Person {


String name;
String gender;
String job;
int age;

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 {

public static void main(String[] args) {

Person p1 = new Person("Mohamad", "Male", "Programmer", 21);


Person p2 = new Person("Rose", "Female", "Secretary", 22);
Person p3 = new Person("Ahmad", "Male", "Doctor", 34);
Person p4 = new Person("Rabih", "Male", "Engineer", 27);

Person p5 = new Person();

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

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

14
Example
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result −
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2

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.

Java Packages & API (Application Programming Interface)


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.

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

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

17
System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + 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 {

public static void main(String[] args) {

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.*;

A Simple Case Study


For our case study, we will be creating two classes. They are Employee and
EmployeeTest.

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;

// This is the constructor of the class Employee


public Employee(String name) {
this.name = name;
}

// Assign the age of the Employee to the variable age.


public void empAge(int empAge) {
age = empAge;
}

/* Assign the designation to the variable designation.*/


public void empDesignation(String empDesig) {
designation = empDesig;
}

/* Assign the salary to the variable salary.*/


public void empSalary(double empSalary) {
salary = empSalary;
}

/* Print the Employee details */


public void printEmployee() {
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
Processing starts from the main method. Therefore, in order for us to run this Employee
class there should be a main method and objects should be created. We will be creating
a separate class for these tasks.

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

// Invoking methods for each object created


empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();

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

You might also like