Вы находитесь на странице: 1из 65

Big Data Training Day 1

Introducton to Java

Deloitte Consulting LLP

1. Introduction to Java
What is Java?
Features of Java
Java Architecture
Implementing a simple Hello World Java Application
Variables, Java primitive Data types, Operators and Logical constructs

2. Objects, Classes and Packages

Object Oriented Concepts (Over view)
Classes and Objects
Creating Classes
Implementing Methods
Introduction to Packages and Java class path
Instance and Static Members
Introduction to Eclipse



3. Questions

Introduction to Java
What is Java?

Java is a general-purpose, object-oriented programing language that

is specifically designed to have as few implementation dependencies
as possible

It is intended to let application developers "write once, run anywhere"

(WORA), meaning that code that runs on one platform does not
need to be recompiled to run on another

Java was created in 1991 by James Gosling et al. of Sun Microsystems.

Initially called Oak, in honor of the tree outside Gosling's window, it was renamed as the Java programming
language in 1995 by Sun Microsystems.




Features of Java



Simple, Object Oriented

Primary characteristics of the Java programming language include a simple language

that can be programmed without extensive programmer training.
The Java programming language is designed to be object oriented from the ground up.

Architecture Neutral and


Java language is designed to be portable meaning same java program can run on many
different platform with-out any modification


Java technology is designed to operate in distributed environments, which means that

security is of paramount importance. Applications written in the Java programming
language are secure from intrusion by unauthorized code/virus attacks.

High Performance

The Java platform achieves superior performance by adopting a scheme by which the
interpreter can run at full speed without checking the run time environment. The Java
interpreter can execute Java bytecodes directly on any machine to which the interpreter
and run-time system have been ported


The Java platform supports multithreading at the language level with the addition of
sophisticated synchronization primitives. Applications can be created which allows
creating multiple threads in order to perform parallel processing of the task


Java technology is designed to operate in distributed environments



The Java programming language is a high-level language that can be characterized by all of the following features:

Java Architecture Java development life cycle

In the Java programming language, all source code is first written in plain text files ending with the .java extension.

Those source files are then compiled into .class files by the Java compiler (javac). A. class file does not contain code that is
native to your processor; it instead contains byte codes-- the machine language of the Java Virtual Machine

Why is Java called Platform Independednt?



Platform independent means that the code remains the same irrespective of the platform involved. Java has something called a
virtual machine called JVM or Java Virtual Machine. What happens in case of Java is that the JVM once installed on any platform
like windows or OS X can run the java code without any alteration.

Java Platform
A platform is the hardware or software environment in which a program runs.
The Java platform has two components:


Java Virtual Machine

Base for the Java platform and is ported onto various hardware-based

Java Application Programming

Interface (API)

large collection of ready-made software components that provide many useful




The API and Java Virtual Machine insulate the program from the underlying hardware.

Java Virtual Machine(JVM)

The Java Virtual Machine Specification defines an
abstract -- rather than a real machine which runs
all Java program.
An imaginary machine that is implemented by
emulating software on a real machine
Java was designed to allow application programs to
be built that could be run on any platform without
having to be rewritten or recompiled by the
programmer for each separate platform.
A Java virtual machine makes this possible
because it is aware of the specific instruction
lengths and other particularities of the platform



Java Virtual Machine is available on many different

operating systems, the same .class files are
capable of running on Microsoft Windows, the
Solaris TM Operating System (Solaris OS), Linux, or

Sample Hello World Application

/** * The HelloWorldApp class implements an application that * simply
displays "Hello World!" to the standard output. ***/
public class HelloWorld {
public static void main(String[] args) {

System.out.println(Hello World);

This is a class level


Implementation of
HeloWorld class.



This is the main method.

When you run the class
using java command on
command prompt this
method gets invoked.

A variable is an item of data named by an identifier
To give a variable a type and a name, write a variable declaration, which generally looks like this.

data-type name
Example int countOfApples = 5;
A variable's data type determines the values the variable can contain and the operations that can be performed on it.



In addition to the name and type that you explicitly give a variable, a variable has a scope. The section of code where the
variable's simple name can be used is the variable's scope.

Primitive Data Types

The following table lists, by keyword, all the primitive data types supported by the Java platform, their sizes/format, and
a brief description of each





Byte-length integer

8-bit two's complement


Short integer

16-bit two's complement



32-bit two's complement


Long Integer

64-bit two's complement


Single-precision floating point

32-bit IEEE 754


Double-precision floating point

64-bit IEEE 754


A single character

16-bit Unicode character


A boolean value (true or false)

true or false

Real Numbers

- 10 -


Other types

Variable Names
A program refers to a variable's value by the variable's name.
A simple variable name:

It must be a legal identifier.

It must not be a keyword, a boolean literal (true or false), or the reserved word null.

It must be unique within its scope.

Variable names begin with a lowercase letter

Class names begin with an uppercase letter

If a variable name consists of more than one word, the words are joined together, and each word after the first
begins with an uppercase letter (for example, isVisible).

The underscore character ( _ ) is acceptable anywhere in a name, but by convention it is used only to separate
words in constants

- 11 -


Conventions in Java

Variable Scope

A variable's scope is the region of a program within which the variable can be referred to by its simple name. The location of
the variable declaration within your program establishes its scope and places it into one of these four categories:


Member variables

A member variable is a member of a class or an object. It is declared within a

class but outside of any method or constructor

Local variables

A data item known within a block, but inaccessible to code outside the block.
For example, any variable defined within a method is a local variable and can't
be used outside the method

Method parameter

Parameters are formal arguments to methods or constructors and are used to

pass values into methods and constructors. The scope of a parameter is the
entire method or constructor for which it is a parameter

- 12 -


Variable scope

Question: Variables
public class BasicsDemo {
public static void main(String[] args) {
int sum = 0;
for (int current = 1; current <= 10; current++) {
sum += current;

System.out.println("Sum = " + sum);


What is the name of each variable declared in the program? Remember, method parameters are also variables.


What is the data type of each variable?


What is the scope of each variable?

- 13 -


Exercise: Variables
Q. Define two variables at class level. Write a main method which will call a method addition and will add
these two variables.
Learning Tip Try and use various variables defined at different places in your class. Now see when does compiler

- 14 -


throw an error.

Java Operators



Relational Operators

>, >=, <, <= , ==, !=

Instanceof Operator


Arithmetic Operators

+, - ,/, *

String Concatenation Operator

Increment/Decrement Operators

++ / --

Logical Operators

&, |, !, &&, | |

- 15 -


An operator performs a function on one, two, or three operands. Below are some of the java operators.

Java Operators - Relational Operators

A relational operator compares two values and determines the relationship between them




op1 > op2

Returns true if op1 is greater than op2


op1 >= op2

Returns true if op1 is greater than or equal to op2


op1 < op2

Returns true if op1 is less than op2


op1 <= op2

Returns true if op1 is less than or equal to op2


op1 == op2

Returns true if op1 and op2 are equal

- 16 -



Java Operators Arithmetic Operators

The Java programming language supports various arithmetic operators for all floating-point and integer numbers



op1 + op2

Adds op1 and op2; also used to concatenate strings

op1 - op2

Subtracts op2 from op1

op1 * op2

Multiplies op1 by op2

op1 / op2

Divides op1 by op2

op1 % op2

Computes the remainder of dividing op1 by op2

- 17 -



Java Operators - Increment/Decrement Operators



It can be used as a statement by itself, or within an expression
It can be put before or after a variable


adds 1 to a variable

If before a variable (preincrement), it means to add one to the

variable, then use the result

If put after a variable (postincrement), it means to use the current

value of the variable, then add one to the variable

It can be used as a statement by itself, or within an expression

It can be put before or after a variable.

subtracts 1 from a

If before a variable (predecrement), it means to subtract one from

the variable, then use the result.
If put after a variable (postdecrement), it means to use the current
value of the variable, then subtract one from the variable

- 18 -



Java Operators - Examples

int b = 5; ++b;
// b is now 6

int e = 5;
int f = e++;
// e is 6, f is 5
int x = 10; int y = 100;
int z = ++x + y++;
// x is 11, y is 101, z is 111

int b = 5; --b;
// b is now 4
int c = 5; int d = --c;
// c is 4, d is 4
int e = 5; int f = e--;
// e is 4, f is 5
int x =
int y =
int z =
// x is

- 19 -

--x + y--;
9, y is 99, z is 109


int a = 5;
// a is now 6

Logical Operators




Logical NOT

A unary operator (it operates on one



Logical AND

A binary operators (it operates on two



Logical OR

A binary operators (each operates on

two operands)

- 20 -


Boolean expressions can use the following logical operators:

Exercise: Operators
1. Consider the following code snippet:
arrayOfInts[j] > arrayOfInts[j+1]
Which operators does the code contain?
2. Consider the following code snippet.
int i = 10; int n = i++%5;

What are the values of i and n after the code is executed?

- 21 -


What are the final values of i and n if instead of using the postfix increment operator (i++), you use the
prefix version (++i))?

Control-Flow Statements

Statement Type



while, do-while, for

decision making

if-else, switch-case


break, continue, label:, return

- 22 -


The Java programming language provides several control flow statements, which are listed in the
following table.

Loop Type



while (expression) {

Continually execute a block of statements

while a condition remains true

do {
} while (expression);

Instead of evaluating the expression at the

top of the loop, do-while evaluates the
expression at the bottom.



Thus, the statements within the block

associated with a do-while are executed at
least once
for (initialization; termination;
increment) {

The initialization expression initializes the

loop it's executed once at the beginning of
the loop.
The termination expression determines
when to terminate the loop. When the
expression evaluates to false, the loop
Finally, increment is an expression that
gets invoked after each iteration through
the loop.

- 23 -


for loop

If-Else and If-Else If

Control statement




if (expression) {

Enables your program to selectively execute other

statements based on some criteria


if (expression) {
} else {

if you want to perform a different set of statements if

the expression is false then you can use
the else statement

The if - else if statement enables your program to

selectively execute other statements based on some

- 24 -


If-Else If

if (expression) {
} else if (expression) {
} else{

Use the switch statement to conditionally perform statements based on an integer expression or enumerated type
public class SwitchDemo {

public static void main(String[] args)

int month = 8;
switch (month) {
case 1:

System.out.println("January"); break;

case 2:

System.out.println("February"); break;

case 3:

System.out.println("March"); break;

case 4:

System.out.println("April"); break;

case 5:

System.out.println("May"); break;

case 6:

System.out.println("June"); break;

case 7:

System.out.println("July"); break;

case 8:

System.out.println("August"); break;

case 9:

System.out.println("September"); break;

case 10: System.out.println("October"); break;

case 11: System.out.println("November"); break;

case 12: System.out.println("December"); break;
default: System.out.println("Not a month!");break;

- 25 -


The break statement has two forms unlabeled and labeled.

An unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement
immediately following the switch.

You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop.

The labeled form terminates an outer statement, which is identified by the label specified in the break statement.
The break statement terminates the labeled statement; it does not transfer the flow of control to the label.

- 26 -


break Statement

The continue statement is used to skip the current iteration of a for, while, or do-while loop

The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls
the loop, basically skipping the remainder of this iteration of the loop

The labeled form of the continue statement skips the current iteration of an outer loop marked with the given label

You use return to exit from the current method; the flow of control returns to the statement that follows the original
method call

- 27 -


Continue/Return Statement

Exercise: Control-Flow statement

- 28 -


Q : Define an integer array with values from 1 to 10. Write a method to add up these values
and store it in a variable. Then check if the result of addition is less than 100. If it is print
I Learnt Control Flow Statements.

Object Oriented Concepts (Overview)



All real world objects have two things:

For example: Cars have state (current gear, current speed, number of gears) and
behavior (accelerate, slow down, change gear).


Hiding internal details and showing functionality is known as abstraction.

For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.


Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. All members and methods are bundled together.


Polymorphism is the capability of a method to do different things based on the object that it is acting upon.
For example: to draw something e.g. circle or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.


When one object acquires all the properties and behaviors of parent object i.e. known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism.

- 29 -


All object have state and behavior i.e. a particular structure. It is defined by classes.
Is also know as a blue print of an Object.
State is shown by value/s held by variable in a class.
Method in a class exhibits the behavior of a class.


The wrapping of data and function (its behavior ) into

single unit is known as encapsulation.

The data is not accessible to outside world and only

those function which are wrapped in the class can
access it. This insulation of data from direct access by
the program is called data hiding.


Public methods

When a client of a module is not able to know more

than its interface.

Collection of variables and functions.

It allows an object to hide its internal state and the

implementation of the behaviors from the outside world.

- 30 -


Non public methods


Abstraction is the concept of representing something

at high level, without going into too much details. In
terms of programming this would mean defining just
the behavior without going into implementation
details. In other words, it focuses on what and
factors out how something should be done

In java, this can be achieved by using

interfaces and abstract keyword at method
and class level.

Use abstraction if you know something needs to be

in class but it's implementation varies.


- color
- getArea()



- length

- diameter

- getArea()

- getArea()

- 31 -


Objects belonging to different classes which react to the same message (by performing different methods)

Poly means many and morphism means forms


- talk()


- talk()

- talk()

- talk()

- 32 -




Ability of a new class to be created, from an existing class by extending it, is called inheritance. Is-a relationship.

The existing class is called the base or the parent class.

The derived class is called the sub or the child class.

Inheritance creates an IS-A relationship.

The subclass is a more specific version of the original class.

The child class inherits the methods and data defined for the parent class.

Software re-use is at the heart of inheritance.


- 33 -



A Class describes:

Fields that hold the data for each object

Constructors that tell how to create a new object of this class

Methods that describe the actions the object can perform

In addition, a class can have data and methods of its own (not part of the objects)




For example, it can keep a count of the number of objects it has created

Defining member variables

Here is the simplest syntax for defining a class:

class NameOfClass {
// the fields (variables) of the object
// the constructors for the object
// the methods of the object

- 34 -

An objects data is stored in fields (also called member

The member variable describe the state of the object. It can
be defined with ordinary variable declarations:
Here are some variable definitions

String name;
Double amount;
int age = 0;


Defining a Class

Creating classes - Defining Methods and Returning results

A method has the syntax:



method-name ( parameters ) {


Access Modifiersuch as public, private and others you will learn about later.

return typethe data type of the value returned by the method, or void if the method does not return a value.
method namethe rules for field names apply to method names as well, but the convention is a little different.
The parameter list in parenthesisa comma-delimited list of input parameters, preceded by their data types, enclosed by
parentheses, (). If there are no parameters, you must use empty parentheses.


public boolean isAdult( ) {

int magicAge = 21;
return age >= magicAge;

- 35 -


void method
The keyword void is used to indicate that a method doesnt return a value

void printAge( ) {
System.out.println(name + " is " + age + " years old.");

- 36 -


The keyword return is not required in a void method.


Constructor is a special method that gets invoked "automatically" at the time of object creation

Constructor is normally used for initializing objects with default values unless different values are supplied

Constructor has the same name as the class name

Constructor cannot return values

A class can have more than one constructor as long as they have different signature (i.e., different input arguments

Defining Constructor

A constructor is the code to create an object

The syntax for a constructor is:

The parameters are a comma-separated list of variable declarations. We usually need to give information to
constructors and to methods

A parameter is a variable used to hold the incoming information

A parameter must have a name and a type

You supply values for the parameters when you use the constructor or method

The parameter name is only meaningful within the constructor or method in which it occurs.

- 37 -


ClassName(parameters) {

Constructor - Example
public class Counter
int counterIndex;

// Constructor
public Counter() {
counterIndex = 0;
//Methods to update or access counter
public void increase() {
counterIndex = counterIndex + 1;

public void decrease() {

counterIndex = counterIndex -


- 38 -


int getCounterIndex() {
return counterIndex;

Using this keyword

Within an instance method or a constructor, this is a reference to the current object the object whose method or
constructor is being called.

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

public class Point {

public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;

- 39 -


Using this keyword - (contd.)

From within a constructor, you can also use the this keyword to call another constructor in the same class. It is called an
explicit constructor invocation.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
public Rectangle(int width, int height) {
this(0, 0, width, height);
public Rectangle(int x, int y, int width, int height) {

this.x = x;
this.y = y;
this.width = width;
this.height = height;


- 40 -


Access Modifiers

Access level modifiers determine whether other classes can use a particular field or invoke a particular method.

There are two levels of access control:

- At the top level - public, or package-private (no explicit modifier).

- At the member level - public, private, protected, or package-private (no explicit modifier).

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class
has no modifier it is visible only within its own package.

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level
classes, and it has the same meaning.

The private modifier specifies that the member can only be accessed in its own class.

The protected modifier specifies that the member can only be accessed within its own package
Same Class

Same Package

Sub Class

Other Package



no access modifier


- 41 -


Access Modifiers

Creating Objects
A class provides the blueprint for objects. Objects are created from a class.

Point originOne = new Point(23, 94);

Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.


Instantiation: The new keyword is a Java operator that creates the object.


Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Using Objects

Once you've created an object, you can access one of its fields, change one of its fields, or call one of its methods to
perform an action.
Object fields are accessed by their name using below syntax:


- 42 -


Object reference can be used for invoking an object's method using below syntax:

Package is a way to group a related class and interface into one unit to resolve the name conflicts between class names



This tells the compiler that some of the classes and interfaces in your class come from the Graphics package.
To easily distinguish related classes and interfaces based on the package it is located
To determine related classes and interfaces and know where to find classes and interfaces that provide certain functions

e.g. java.awt.Graphics or java.lang.Math

Creating a Package
Add this to the first line of the java file:
package <foldername>;

e.g. package world;

package graphics;
public class Circle extends Graphic implements Draggable {
. . .
- 43 -


If a class does not have this on the first line, that class will belongs to the default package.

Package Example
package com.deloitte.entities;

public class Employee{

string name;
string address;
int employeeId;
boolean isMarried;

public void work(){

Using Packages
To use a class or an interface that's in a different package, you have three choices:
1.Use the fully qualified name of the class or the interface.
2.Import the class or the interface.
3.Import the entire package of which the class or the interface is a member.

- 44 -


You have to set your class path so that the compiler and the interpreter can find the source and class files for your
classes and interfaces.

Exercise: Classes/Objects

- 45 -


Define a class Employee. Define its attributes like first name, last name, address, city,
salary, etc. Write a main method which will take first name and salary information as an
input for 5 such employees. Print on console what is the average salary

Static Members

A class member is declared by using the static modifier.

The runtime system allocates a class variable once per class, regardless of the number of instances created of that

The system allocates memory for a class variable the first time it encounters the class.

All instances of that class share the same copy of the class's class variables.

They can only call other static methods.

They can only access static data.

They cannot refer to "this" or "super in anyway.

Static field1
Static field2

In the example given here, a static field belongs to the

Static field3

class. Thus, no matter how many objects you create

of that class, there will only exist one field located in the
class, and the value of that field is the same,


- 46 -




no matter from which object it is accessed.

Static Example

public class Employee extends Person{

int employeeId;
static int numberOfEmployees;
static public void work(){
//To access static methods

//To access static members

- 47 -



Static Example
class MyClass {

class Comparator {

public static void main(String


public static int max(int a, int b)

if( a > b)

String s1 = "Melbourne";

return a;

String s2 = "Sydney";


String s3

return b;

= "Adelaide";

int a = 10;

int b = 20;
public static String max(String a,
String b)

b)); // which number is big

, s2)); // which city is big

if( a.compareTo (b) > 0)

return a;

, s3)); // which city is big

return b;


- 48 -


Final Class and Final Member

A class which is defined as final can not be sub classed. Hence all methods in a final class are inherently final.
Example :- java.lang.String

Final Member

All methods and variables can be overridden by default in subclasses.

This can be prevented by declaring them as final using the keyword "final" as a modifier.

For example:

final int marks = 100;

This ensures that functionality defined in this method cannot be altered.

Similarly, the value of a final variable cannot be altered.

- 49 -


final void display();

Wrapper classes
The wrapper classes in the Java API serve two primary purposes:

To provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved
for objects, like as being added to Collections, or returned from a method with an object return value.

To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions:
converting primitives to and from String objects, and converting primitives and String objects to and from different bases
(or radix), such as binary, octal, and hexadecimal.

Example for primitive type int, java.lang.Integer is the the wrapper class.

xxxValue() method
When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods.

Integer i2 = new Integer(42); // make a new wrapper object

byte b = i2.byteValue(); // convert i2's value to a byte primitive
short s = i2.shortValue(); // another of Integer's xxxValue methods
double d = i2.doubleValue(); // yet another of Integer's xxxValue methods
xxx Parsexxx(String) method
If you do not need to store a value in a wrapper but just want to perform a quick operation on it, such as converting the
type, you can do it by using an appropriate static method of the appropriate wrapper class. For example, all the wrapper
classes except Character offer a static method that has the following signature:

- 51 -


String s = "123";
int i = Integer.parseInt(s);

String, StringBuffer, StringBuilder

The three classes String, StringBuffer and StringBuilder store and manipulate strings i.e. character data consisting
of more than one characters

Use the following guidelines for deciding which class to use:

- If your text is not going to change, use a string. a String object is immutable.
- If your text will change, and will only be accessed from a single thread, use a string builder.
- If your text will change, and will be accessed from multiple threads, use a string buffer.

Creating a String Object

The most direct way to create a string is to write:
String greeting = "Hello world!";
In this case, "Hello world!" is a string literala series of characters in your code that is enclosed in double quotes.

Whenever it encounters a string literal in your code, the compiler creates a String object with its valuein this case,
Hello world!
You can create String objects by using the new keyword and a constructor. The String class has thirteen constructors
that allow you to provide the initial value of the string using different sources, such as an array of characters :

- 52 -


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };

String helloString = new String(helloArray);

Useful methods in java.lang.String

String Length: You can use with strings is the length() method, which returns the number of characters contained In the
string object.

Concatenating Strings: The String class includes a method for concatenating two strings:

This returns a new string that is string1 with string2 added to it at the end.

Getting Characters and Substrings by Index: You can get the character at a particular index within a string by invoking
the charAt() method. The index of the first character is 0, while the index of the last character is length()-1.
For example, the following code gets the character at index 9 in a string:

String anotherPalindrome = "Niagara. O roar again!";

char aChar = anotherPalindrome.charAt(9);
Substring: If you want to get more than one consecutive characters from a string, you can use the substring method.

String substring(int beginIndex, int endIndex)

String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
String substring(int beginIndex)

String startingroar = anotherPalindrome.substring(11);

- 53 -


String anotherPalindrome = "Niagara. O roar again!";

Useful methods in java.lang.String contd.

String trim(): Returns a copy of this string with leading and trailing white space removed.

String toLowerCase(): Returns a copy of this string converted to lowercase

String toUpperCase(): Returns a copy of this string converted to uppercase

int indexOf(int ch): Returns the index of the first occurrence of the specified character.

int lastIndexOf(int ch): Returns the index of the last occurrence of the specified character.

- 54 -


String replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.


Write a program that computes your initials from your full name and displays them.


An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example,
"parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that
figures out whether one string is an anagram of another string. The program should ignore white space and


Write a program to identify if given string a palindrome string.

- 56 -


Exercise : String function

As a program is executed, data is dynamically allocated and assigned to structures and objects since memory is
limited , we need to conserve memory whenever possible.

A good practice is to reclaim any previously allocated memory when no longer in use.

Some programming languages leave this up to the programmer (C, C++ etc.), while others alleviate this problem by
providing a garbage collection facility.

The JVM runs a garbage collector service in a separate thread of execution when a program is run on the JVM

The garbage collector periodically checks for unused allocated memory, and reclaims it for re-allocation later on in the

- 57 -


Garbage Collection (GC)

Lifetime of Objects

An object is considered alive if :

- there is a reference to the object on the JVM stack
- there is a reference to the object in a local variable, on the stack, or in a static field

- if a field of an alive object contains a reference to the object

- if the JVM keeps an internal reference to the object (e.g. for supporting native methods)

If an object is not deemed alive be these rules, it is considered dead, and is ready to be garbage collected

- 58 -



Java logging APIs help the applications to save the text to a central place to report on errors or to provide additional
information about your program.

This logging API allows to configure how messages are written by which class with which priority.

The java.util.logging package contain all the logging related classes.

java.util.logging provides the logging capabilities via the class Logger.

Creating a logger

import java.util.logging.Logger;

private final static Logger LOGGER =

This will return a handle on the logger for MyClass.

- 31 -


Logging Levels

Logging levels indicate the severity of the message.

There are 7 different levels of logging defined by the API.

SEVERE (highest)



You can set the levels for logging by using the following statement.

This will set the logging level to Info. You can also set the levels to ALL or OFF to enable all or none respectively. The
logger class has different methods to log messages at different levels.

- 32 -



The log manager is responsible for creating and managing the logger and the maintenance of the configuration.

We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String
name, Level level) method.

Example - LogManager.getLogManager().setLevel("logging", Level.FINE)

package test;
class MyClass {
public void myMethod() {
Logger logger = Logger.getLogger("com.mycompany.MyClass");
// This method should be used when an exception is encountered
try {
// Test with an exception throw new IOException();
} catch (Throwable e)
// Log the exception
logger.log(Level.SEVERE, "Uncaught exception", e);
} // When a method is throwing an exception, this method
should be used
Exception ex = new IllegalStateException();
logger.throwing(this.getClass().getName(), "myMethod", ex);
- 34 -


Logging Example


Create a shape class. Create its 3 subclasses Rectangle, circle and triangle. Write methods to calculate their areas.
Also, write a main method, which will take which type to calculate area for (triangle, square and rectangle) as an input
and will print the area on the console.

Use the concepts learnt so far during the course

Abstract classes


- 35 -


Exception handling.

Eclipse as an integrated development environment (IDE) for Java. Eclipse gives suggestions while you code which
enhances the development speed.

The Eclipse IDE can be extended with additional software components. Eclipse calls these software components as

Eclipse requires an installed Java Runtime. Please make sure Java is installed on your machine before installing

To start Eclipse double-click on the file eclipse.exe (Microsoft Windows) or eclipse (Linux / Mac) in the directory where
you unpacked Eclipse. The system will prompt you for a workspace. The workspace is the place where you store your
Java projects (more on workspaces later). Select an empty directory and press Ok.

- 59 -


Introduction to Eclipse

Eclipse UI Overview

The workspace is the physical location (file path) you are working in. You can choose the workspace during startup of
Eclipse or via the menu ( File Switch Workspace Others) . All your projects, source files, images and other
artifacts will be stored and saved in your workspace.

The Eclipse IDE comes with several default Perspectives. For Java development you usually use the Java
Perspective, but Eclipse has many more predefined Perspectives, e.g. Debug, Git Repositories, CVS Repositories.

Eclipse allows you to switch to various perspective via the menu Window Open Perspective Other

- 60 -


Eclipse IDE Perspectives:

- 61 -


Eclipse Java perspective overview


Create java project.


Create a package.


Create a new class.


Running Java program.

- 62 -


Exercise: How to use Eclipse

Copyright 2011 Deloitte Development LLC. All rights reserved.