Introducton to Java
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-
Java_Day1_v1.pptx
3. Questions
Introduction to Java
What is Java?
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
Java language is designed to be portable meaning same java program can run on many
different platform with-out any modification
Secure
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
-4-
Java_Day1_v1.pptx
The Java programming language is a high-level language that can be characterized by all of the following features:
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
-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
Base for the Java platform and is ported onto various hardware-based
platforms
-6-
Java_Day1_v1.pptx
The API and Java Virtual Machine insulate the program from the underlying hardware.
-7-
Java_Day1_v1.pptx
System.out.println(Hello World);
}
Implementation of
HeloWorld class.
-8-
Java_Day1_v1.pptx
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.
Keyword
Description
Size/Format
Integers
byte
Byte-length integer
short
Short integer
Int
Integer
long
Long Integer
float
double
char
A single character
boolean
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 not be a keyword, a boolean literal (true or false), or the reserved word null.
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
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
- 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.
3.
- 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
+, - ,/, *
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.
Usage
Description
>
>=
<
<=
==
op1 == op2
- 16 -
Java_Day1_v1.pptx
Operator
The Java programming language supports various arithmetic operators for all floating-point and integer numbers
Usage
Description
op1 + op2
op1 - op2
op1 * op2
op1 / op2
op1 % op2
- 17 -
Java_Day1_v1.pptx
Operator
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
subtracts 1 from a
variable
- 18 -
Java_Day1_v1.pptx
--
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
&&
Logical AND
||
Logical OR
- 20 -
Java_Day1_v1.pptx
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;
- 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
decision making
if-else, switch-case
branching
- 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
}
do {
statement(s)
} while (expression);
while
do-while
- 23 -
Java_Day1_v1.pptx
for loop
Control statement
Syntax
Description
if
if (expression) {
statement(s)
}
if-else
if (expression) {
statement(s)
} else {
statement(s)
}
- 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 {
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;
}
- 25 -
Java_Day1_v1.pptx
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
- 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
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
Class
Public methods
- 30 -
Java_Day1_v1.pptx
Abstraction
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)
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 child class inherits the methods and data defined for the parent class.
Parent
- 33 -
Java_Day1_v1.pptx
Child
Classes
A Class describes:
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
class NameOfClass {
// the fields (variables) of the object
// the constructors for the object
// the methods of the object
}
- 34 -
String name;
Double amount;
int age = 0;
Java_Day1_v1.pptx
Defining a Class
<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:
- 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
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
A class can have more than one constructor as long as they have different signature (i.e., different input arguments
syntax)
Defining Constructor
The parameters are a comma-separated list of variable declarations. We usually need to give information to
constructors and to methods
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;
}
1;
}
- 38 -
Java_Day1_v1.pptx
int getCounterIndex() {
return counterIndex;
}
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
- 39 -
Java_Day1_v1.pptx
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.
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.
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
Creating a Package
Add this to the first line of the java file:
package <foldername>;
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;
- 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
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.
Class
Static field1
Static field2
Static field3
Object
- 46 -
Object
Object
Java_Day1_v1.pptx
Static Example
Employee.work();
//To access static members
- 47 -
Java_Day1_v1.pptx
Employee.numberOfEmployees
Static Example
class MyClass {
class Comparator {
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
System.out.println(Comparator.max(s1
, s3)); // which city is big
return b;
}
}
}
- 48 -
Java_Day1_v1.pptx
Final Member
This can be prevented by declaring them as final using the keyword "final" as a modifier.
For example:
- 49 -
Java_Day1_v1.pptx
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.
- 51 -
Java_Day1_v1.pptx
String s = "123";
int i = Integer.parseInt(s);
The three classes String, StringBuffer and StringBuilder store and manipulate strings i.e. character data consisting
of more than one characters
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
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:
Java_Day1_v1.pptx
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.
- 56 -
Java_Day1_v1.pptx
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
Lifetime of Objects
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.
Creating a logger
import java.util.logging.Logger;
- 31 -
Java_Day2.pptx
Logging Levels
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.
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.
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
- 61 -
Java_Day1_v1.pptx
1.
2.
Create a package.
3.
4.
- 62 -
Java_Day1_v1.pptx