Anda di halaman 1dari 65

Big Data Training Day 1

Introducton to Java

Deloitte Consulting LLP

Agenda
1. Introduction to Java
What is Java?
Features of Java
Java Architecture
JVM
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

-2-

Java_Day1_v1.pptx

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.

-3-

Java_Day1_v1.pptx

History

Features of Java

Feature

Description

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


Portable

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

Secure

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

Multi-threaded

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

Distributed

Java technology is designed to operate in distributed environments

-4-

Java_Day1_v1.pptx

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?

-5-

Java_Day1_v1.pptx

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

Description

Java Virtual Machine

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

Java Application Programming


Interface (API)

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


capabilities

-6-

Java_Day1_v1.pptx

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

-7-

Java_Day1_v1.pptx

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
MacOS

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


comment.

Implementation of
HeloWorld class.

-8-

Java_Day1_v1.pptx

This is the main method.


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

Variables
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.

-9-

Java_Day1_v1.pptx

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

Keyword

Description

Size/Format

Integers
byte

Byte-length integer

8-bit two's complement

short

Short integer

16-bit two's complement

Int

Integer

32-bit two's complement

long

Long Integer

64-bit two's complement

float

Single-precision floating point

32-bit IEEE 754

double

Double-precision floating point

64-bit IEEE 754

char

A single character

16-bit Unicode character

boolean

A boolean value (true or false)

true or false

Real Numbers

- 10 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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:

Description

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 -

Java_Day1_v1.pptx

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

1.

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

2.

What is the data type of each variable?

3.

What is the scope of each variable?

- 13 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

throw an error.

Java Operators

Type

Operator

Relational Operators

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

Instanceof Operator

Instanceof

Arithmetic Operators

+, - ,/, *

String Concatenation Operator

Increment/Decrement Operators

++ / --

Logical Operators

&, |, !, &&, | |

- 15 -

Java_Day1_v1.pptx

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

Usage

Description

>

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_Day1_v1.pptx

Operator

Java Operators Arithmetic Operators

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

Usage

Description

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_Day1_v1.pptx

Operator

Java Operators - Increment/Decrement Operators

Operator

Usage

Description
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
variable

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_Day1_v1.pptx

--

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 -

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

Java_Day1_v1.pptx

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

Logical Operators

Operator

Name

Description

Logical NOT

A unary operator (it operates on one


operand)

&&

Logical AND

A binary operators (it operates on two


operands)

||

Logical OR

A binary operators (each operates on


two operands)

- 20 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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

Keyword

looping

while, do-while, for

decision making

if-else, switch-case

branching

break, continue, label:, return

- 22 -

Java_Day1_v1.pptx

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

Looping
Loop Type

Syntax

Description

while (expression) {
statement
}

Continually execute a block of statements


while a condition remains true

do {
statement(s)
} while (expression);

Instead of evaluating the expression at the


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

while

do-while

Thus, the statements within the block


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

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
terminates.
Finally, increment is an expression that
gets invoked after each iteration through
the loop.

- 23 -

Java_Day1_v1.pptx

for loop

If-Else and If-Else If

Control statement

Syntax

Description

if

if (expression) {
statement(s)
}

Enables your program to selectively execute other


statements based on some criteria

if-else

if (expression) {
statement(s)
} else {
statement(s)
}

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
criteria

- 24 -

Java_Day1_v1.pptx

If-Else If

if (expression) {
statement(s)
} else if (expression) {
statement(s)
} else{
statement(s)
}

Switch-case
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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

Continue/Return Statement

Exercise: Control-Flow statement

- 28 -

Java_Day1_v1.pptx

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)


Class

Object

All real world objects have two things:


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

Abstraction

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.

Encapsulation

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

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.

Inheritance

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 -

Java_Day1_v1.pptx

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.

Encapsulation

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.

Class

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 -

Java_Day1_v1.pptx

Non public methods

Abstraction

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.

Abstract
method

Shape
<Abstract>
- color
- getArea()

Rectangle

Circle

- length

- diameter

- getArea()

- getArea()

- 31 -

Java_Day1_v1.pptx

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

Poly means many and morphism means forms

Animal
<Abstract>

- talk()

Dog

- talk()

- talk()

Fox
- talk()

- 32 -

Java_Day1_v1.pptx

Cat

Inheritance

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.

Parent

- 33 -

Java_Day1_v1.pptx

Child

Classes
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)

Class

Instantiation

Object

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


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

Java_Day1_v1.pptx

Defining a Class

Creating classes - Defining Methods and Returning results


A method has the syntax:

<access-modifier>

<return-type>

method-name ( parameters ) {

method-variables
code
}

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.

Example:

public boolean isAdult( ) {


int magicAge = 21;
return age >= magicAge;

- 35 -

Java_Day1_v1.pptx

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.");
return;
}

- 36 -

Java_Day1_v1.pptx

The keyword return is not required in a void method.

Constructor

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
syntax)

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 -

Java_Day1_v1.pptx

ClassName(parameters) {
//code
}

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 -

1;

}
- 38 -

Java_Day1_v1.pptx

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;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

- 39 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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

public

protected

no access modifier

private

- 41 -

Java_Day1_v1.pptx

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);
1.

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

2.

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

3.

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:

objectReference.fieldName;

- 42 -

Java_Day1_v1.pptx

Object reference can be used for invoking an object's method using below syntax:
objectReference.methodName(argumentList);

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

import

java.awt.Graphics;

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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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
class.

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.

Class
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,

Object

- 46 -

Object

Object

Java_Day1_v1.pptx

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

Employee.work();
//To access static members

- 47 -

Java_Day1_v1.pptx

Employee.numberOfEmployees

Static Example
class MyClass {

class Comparator {

public static void main(String


args[])

public static int max(int a, int b)

if( a > b)

String s1 = "Melbourne";

return a;

String s2 = "Sydney";

else

String s3

return b;

= "Adelaide";

int a = 10;

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

System.out.println(Comparator.max(a,
b)); // which number is big

System.out.println(Comparator.max(s1
, s2)); // which city is big

if( a.compareTo (b) > 0)


return a;
else

System.out.println(Comparator.max(s1
, s3)); // which city is big

return b;

}
}

}
- 48 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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


String helloString = new String(helloArray);
System.out.println(helloString);

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:

string1.concat(string2);
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 -

Java_Day1_v1.pptx

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 -

Java_Day1_v1.pptx

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

1.

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

2.

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
punctuation.

3.

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

- 56 -

Java_Day1_v1.pptx

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
program.

- 57 -

Java_Day1_v1.pptx

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_Day1_v1.pptx

Logging

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 =


Logger.getLogger(MyClass.class.getName());
This will return a handle on the logger for MyClass.

- 31 -

Java_Day2.pptx

Logging Levels

Logging levels indicate the severity of the message.

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


SEVERE (highest)

WARNING
INFO
CONFIG
FINE

FINER
FINEST

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

LOGGER.setLevel(Level.INFO);
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 -

Java_Day2.pptx

LogManager

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 -

Java_Day2.pptx

Logging Example

Assignment

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


Inheritance
Abstract classes

Logging

- 35 -

Java_Day2.pptx

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
"plug-ins".

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

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 -

Java_Day1_v1.pptx

Introduction to Eclipse

Eclipse UI Overview
Workspace:

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 -

Java_Day1_v1.pptx

Eclipse IDE Perspectives:

- 61 -

Java_Day1_v1.pptx

Eclipse Java perspective overview

1.

Create java project.

2.

Create a package.

3.

Create a new class.

4.

Running Java program.

- 62 -

Java_Day1_v1.pptx

Exercise: How to use Eclipse

Copyright 2011 Deloitte Development LLC. All rights reserved.

Anda mungkin juga menyukai