ITE 1122 - Fundamental Structures of Programming - 1
ITE 1122 - Fundamental Structures of Programming - 1
programming-1
Agenda
Basic Syntax
Object and Classes
Basic Datatypes
Variable Types
Modifier Types
Basic Syntax
public class MyFirstJavaProgram {
When we consider a Java program, it can be defined as a
/* This is my first java program.
collection of objects that communicate via invoking each * This will print 'Hello World' as the output
other's methods */
Class − A class can be defined as a template/blueprint that • Using any Java IDE type above code and
describes the behavior/state that the object of its type save, compile and run the program.
supports. • You will be able to see ' Hello World '
printed on the window
Methods − A method is basically a behavior. A class can
contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.
Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name
of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form the
name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to
the end of the name (if the file name and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java’
public static void main(String args[]) − Java program processing starts from the main() method which is a
mandatory part of every Java program.
Basic Syntax
The following list shows the reserved words in Java. These reserved words may not be used as constant
or variable or any other identifier names.
volatile while
Object and Classes
If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state public class Dog {
and a behavior. String breed;
int age;
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. String color;
void barking() {
Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via }
methods.
void hungry() {
So in software development, methods operate on the internal state of an object and the object-to-object communication is }
done via methods. void sleeping() {
}
A class is a blueprint from which individual objects are created. }
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.
public class Puppy {
Object and Classes int puppyAge;
very class has a constructor. If we do not explicitly write a public Puppy(String name) {
// This constructor has one parameter, name.
constructor for a class, the Java compiler builds a default System.out.println("Name chosen is :" + name );
constructor for that class. }
Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory.
Reference/Object Data Types - Reference variables are created using defined constructors of the classes.
They are used to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
Basic Datatypes
Primitive Description Minimum Maximum Default Example
Data Type
byte 8-bit signed two's complement 128 (-2^7) 127 (inclusive)(2^7 -1) 0 byte a = 100,
integer byte b = -50
short 16-bit signed two's complement -32,768 (-2^15) 32,767 (inclusive) (2^15 -1) 0 short s = 10000, short
integer r = -20000
int 32-bit signed two's complement - 2,147,483,648 (-2^31) 2,147,483,647(inclusive) (2^31 -1) 0 int a = 100000, int b = -
integer. 200000
long 64-bit signed two's complement -9,223,372,036,854,775,808(-2^63) 9,223,372,036,854,775,807 (inclusive) 0L long a = 100000L, long
integer (2^63 -1) b = -200000L
double double-precision 64-bit IEEE default data type for decimal 0.0d d1 = 123.4
754 floating point values
boolean one bit of information true and false false boolean one = true
char single 16-bit Unicode character '\u0000' (or 0) '\uffff' (or 65,535 inclusive) char letterA = 'A'
Basic Datatypes
Java Literals - A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation.
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8)
number systems as well.
E.g. : int decimal = 100; int octal = 0144; int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes.
Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied to the
variable
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method,
constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method,
constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
When a space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is
destroyed.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an
object's state that must be present throughout the class.
The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these
variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is
null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when
instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
Variable Types - Class variables
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final,
and static. Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or
private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the
class.
Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is
null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
Static variables can be accessed by calling with the class name ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not
public and final, the naming syntax is the same as instance and local variables.
Variable Types - Instance variables and Class variables
import java.io.*;
public class Employee {
import java.io.*;
// this instance variable is visible for any child class. public class Employee {
public String name;
// salary variable is visible in Employee class only. // salary variable is a private static
private double salary;
variable
// The name variable is assigned in the constructor. private static double salary;
public Employee (String empName) {
name = empName;
} // DEPARTMENT is a constant
// The salary variable is assigned a value. public static final String DEPARTMENT =
public void setSalary(double empSal) { "Development ";
salary = empSal;
}
public static void main(String args[]) {
// This method prints the employee details.
public void printEmp() { salary = 1000;
System.out.println("name : " + name ); System.out.println(DEPARTMENT +
System.out.println("salary :" + salary);
} "average salary:" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika"); }
empOne.setSalary(1000);
empOne.printEmp();
}
Java provides a number of access modifiers to set access levels for
Modifier Types
classes, variables, methods and constructors. The four access levels are
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected)
Java provides a number of non-access modifiers to achieve many other
functionality.
The static modifier for creating class methods and variables.
The final modifier for finalizing the implementations of classes, methods,
and variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
Default Access Modifier - No Keyword Private Access Modifier - Private Public Access Modifier - Public
Protected Access Modifier - Protected
Modifier Types - Java – Access Types
Description Example
Static methods do not use any instance variables of any object of the for (int i = 0; i < 500; ++i) {
class they are defined in. Static methods take all the data from new InstanceCounter();
parameters and compute something from those parameters, with no }
reference to variables. System.out.println("Created " + InstanceCounter.getCount() +
" instances");
Class variables and methods can be accessed using the class name }
The Static Modifier followed by a dot and the name of the variable or method. }
Modifier Types - Java – non Access Types
Description Example
Final Variables
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an different public class Test {
object. final int value = 10;
However, the data within the object can be changed. So, the state of // The following are examples of declaring constants:
the object can be changed but not the reference. public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
With variables, the final modifier often is used with static to make
the constant a class variable. public void changeValue() {
value = 12; // will give an error
Final Methods }
A final method cannot be overridden by any subclasses. As }
mentioned previously, the final modifier prevents a method from
being modified in a subclass. public class Test {
public final void changeName() {
The main intention of making a method final would be that the // body of method
content of the method should not be changed by any outsider. }
}
Final Classes
The main purpose of using a class being declared as final is to public final class Test {
prevent the class from being subclassed. If a class is marked as final // body of class
The Final Modifier then no class can inherit any feature from the final class. }
Modifier Types - Java – non Access Types
Description Example
Abstract Class
An abstract class can never be instantiated. If a class is declared as
abstract then the sole purpose is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be
extended). If a class contains abstract methods then the class should
be declared abstract. Otherwise, a compile error will be thrown.
An abstract class may contain both abstract methods as well normal abstract class Caravan {
methods. private double price;
private String model;
Abstract Methods private String year;
An abstract method is a method declared without any public abstract void goFast(); // an abstract method
implementation. The methods body (implementation) is provided by public abstract void changeColor();
the subclass. Abstract methods can never be final or strict. }
Any class that extends an abstract class must implement all the public abstract class SuperClass {
abstract methods of the super class, unless the subclass is also an abstract void m(); // abstract method
abstract class. }
If a class contains one or more abstract methods, then the class must class SubClass extends SuperClass {
be declared abstract. An abstract class does not need to contain // implements the abstract method
abstract methods. void m() {
.........
The abstract method ends with a semicolon. Example: public abstract }
The abstract Modifier sample(); }
Modifier Types - Java – non Access Types
Description Example
The synchronized keyword used to indicate that a method can be public synchronized void showDetails() {
The Synchronized accessed by only one thread at a time. The synchronized modifier .......
Modifier can be applied with any of the four access level modifiers. }
This modifier is included in the statement that creates the variable, public transient int limit = 55; // will not persist
The Transient Modifier preceding the class or data type of the variable. public int b; // will persist
Accessing a volatile variable synchronizes all the cached copied of the public void stop() {
variables in the main memory. Volatile can only be applied to instance active = false; // line 2
variables, which are of type object or private. A volatile object reference }
The Volatile Modifier can be null }