You are on page 1of 71

Chapter 1

Introduction to JAVA
Bloom’s Taxonomy
1. Knowledge : Exhibits previously learned material by recalling
facts, terms, basic concepts and answers.
(What is ...? How is ...? Where is ...? When did _______ happen? How did ______
happen? How would you explain ...? Why did ...? How would you describe ...?
When did ...? Can you recall ...? How would you show ...? Can you select ...?
Who were the main ...? Can you list three ...? Which one ...? Who was ...?)
1. Comprehension : Demonstrating understanding of facts and
ideas by organizing, comparing, translating, interpreting, giving
descriptions and stating main ideas.
(How would you classify the type of ...? How would you compare ...? contrast ...?
Will you state or interpret in your own words ...? How would you rephrase
the meaning ...? What facts or ideas show ...? What is the main idea of ...?
Which statements support ...? Can you explain what is happening . . . what is
meant . . .? What can you say about ...? Which is the best answer ...? How
would you summarize ...?)

Department of Computer Science & Engineering


Bloom’s Taxonomy

3. Application : Solving problems by applying acquired knowledge,


facts, techniques and rules in a different way.
(How would you use ...? What examples can you find to ...? How would you solve
_______ using what you have learned ...? How would you organize _______ to
show ...? How would you show your understanding of ...? What approach would
you use to ...? How would you apply what you learned to develop ...? What other
way would you plan to ...? What would result if ...? Can you make use of the facts
to ...? What elements would you choose to change ...? What facts would you
select to show ...? What questions would you ask in an interview with ...?)

Department of Computer Science & Engineering


Topic Learning Outcome

• Explain java object oriented programming concepts-


WebTechnology, DBMS, DM
• Explain java platform features
• Explain primitive data types in Java
• Write java programs using arrays and strings
• Analyze and draw class diagrams using UML notations for the
given scenario

PS : These topics are primitive steps in understanding Object


Oriented Programming.

Department of Computer Science & Engineering


Need for Object Oriented Approach
• Challenges in developing a business application
– Integration of modules/applications
– Extensibility of existing code
– High level of flexibility(to meet business requirement changes) and
illusion of simplicity
• If above challenges are nor addressed it may lead to
software crisis
• Features needed in the business application to meet these
challenges
– Modularity, Extendibility, Reusability, Interoperability, Security
– interoperability is the ability of different information technology
systems and software applications to communicate, exchange data,
and use the information that has been exchanged.
• Challenges can be addressed using object oriented
approach.
Need for Object Oriented Approach
• Properties of a business application
– Clear separation of functionalities
– Exhibits hierarchy
– Composed of sub systems
• These properties can be implemented using object
oriented approach.
1st Principle of object-oriented problem solving

• An object-oriented program is structured as a


community of interacting agents, called objects.
• Each object has a role to play.
• Each object provides a service, or performs an
action, that is used by other members of the
community.
2nd Principle of object-oriented problem solving

• Action is initiated in object-oriented


programming by sending a message to an agent
(an object) responsible for the action.
• The receiver is the object to whom the message
is sent.
• The receiver will perform some method to satisfy
the request.
3rd Principle of object-oriented problem solving

• All objects are instances of a class.


• The method invoked by an object in response to
a message is determined by the class of the
receiver.
• All objects of a given class use the same method
in response to similar messages.
Introduction to Object Oriented Concepts

• Some key features of the Object Oriented programming are:


- Emphasis on data rather than procedure
- Programs are divided into entities known as objects
- Data Structures are designed such that they characterize
objects
- Functions that operate on data of an object are tied together
in data structures
- Data is hidden and cannot be accessed by external functions
- Objects communicate with each other through functions
- New data and functions can be easily added whenever
necessary
- Follows bottom up design in program design
Introduction to Object Oriented Concepts
What are the characteristics of Object Oriented programming
language?
Encapsulation – Encapsulation is capturing data and keeping it safely
and securely from outside interfaces.

Inheritance- This is the process by which a class can be derived from


a base class with all features of base class and some of its own. This
increases code reusability.

Polymorphism- This is the ability to exist in various forms. For


example an operator can be overloaded so as to add two integer
numbers and two floats.

Abstraction- The ability to represent data at a very conceptual level


without any details.
Department of Computer Science & Engineering
Java: History
• The invention of the microprocessor
revolutionized computers

Intel microprocessor

Commodore Pet microcomputer


Java: History (3)

• It was believed that the logical next step for


microprocessors was to have them run
intelligent consumer electronics
Java History (4)

•Sun Microsystems funded an internal research


project “Green” to investigate this opportunity.
– Result: A programming language called “Oak”
Java History (5)
– Problem: There was already a programming
language called Oak.
– The “Green” team met at a local coffee shop to
come up with another name...
•Java!
Java: History (6)
•The concept of intelligent devices
didn’t catch on.
•Project Green and work on the
Java language was nearly
canceled.
Java: History (7)

•The popularity of the Internet resulted in Sun’s


re-focusing of Java on computers.
•Prior to the advent of Java, web pages allowed
you to download only text and images.
Your computer at home Server containing a
running a web browser web page

User clicks on a link

Images and text get downloaded


Java: History (8)

• Java enabled web browsers allowed for the


downloading of programs (Applets).
• Java is still used in this context today:
–Your
Facebook (older version)
computer at home
running a web browser
Server containing a
web page

– Hotmail (older version)


User clicks on a link

Java Applet downloaded

Java version of the Game of Life: http://www.bitstorm.org/gameoflife/


Features Of JAVA

• Java is simple
• Java is object-oriented
• Java is distributed
• Java is interpreted
• Java is robust
• Java is secure
• Java is architecture-neutral
• Java is portable
• Java’s has high performance
• Java is multithreaded
• Java is dynamic
Java Virtual machine (JVM)
• JVM is a component of the java system that interprets and
executes the instructions in our class files.
• It is a software, staying on top of operating system such as UNIX
, WINDOWs etc.,
• It helps java to create high level of portability by hiding the
difference between the Operating System implementations.

• How JVM works?


– Java programs are compiled into byte code.
– JVM interprets and converts java byte code into machine code in order
to execute on a CPU.
– Most web browsers has an integrated JVM to run applets.
JAVA Run Time Environment
JVM Tasks

• Main JVM tasks include

– Loading classes
– Object creations of java classes
– Garbage collection
– Security Responsibility
Exploring JVM
Exploring JVM
• The JVM consists of
– Method area
– Heap
– One or more stacks

• When JVM loads a class file, it puts its information in the


method area. The information consists of the byte code that
implements almost every method in the java system.
• As the program runs, all objects instantiated are stored in the
HEAP.
• The stack area is used to store activation records as program
runs.
Heap memory and Stack Memory

• Heap The JVM has a heap that is the runtime data area
from which memory for all class instances and arrays
are allocated. It is created at the JVM start-up.
• By default, the maximum heap size is 64 Mb.
• Heap memory for objects is reclaimed by an automatic
memory management system which is known as a
garbage collector. The heap may be of a fixed size or
may be expanded and shrunk, depending on the
garbage collector's strategy.
• The stack is a place in the computer memory where
all the variables that are declared and initialized
before run time are stored.
• [The heap is the section of computer memory where
all the variables created or initialized at run time are
stored ]
Contents of memory Blocks at Run Time
Registers
• The registers of the java virtual machine are just like
the registers inside a real computer.
• FRAME: Pointer to execution environment of current
method.
• VARS: Pointer to the first local variable of current
method.
• STACKS
– JVM is stack based
– The stack is used to supply parameters to byte codes and
methods, and to retrieve results back from them.
– Each stack frame contains three sets of data: the local
variables for the method call, its execution environment, and
its operand stack.
Just In Time Compiler (JIT)
Every time JIT compiler interprets byte code, it will keep the binary
code in log and optimize it. Next time when the same method is
called, the optimized code will run. Sum experiments shows
that, java programs using JIT could be as fast as compiled C
program.

Java Compiler Java Virtual


Machine

Compiled
Byte JIT Compiler
Optimized Code
& Kept in Log

Native Machine
Code

Machine
Java: Write Once, Run Anywhere
• Consequence of Java’s history:
platform-independence

Click on link to Applet

Mac user running Safari


Web page stored on Unix serv
Virtual machine translates byte code to
native Mac code and the Applet is run Byte code is downloaded

Windows user running Internet Explorer


Byte code
(part of web
page)
Java: Write Once, Run Anywhere
• Consequence of Java’s history:
platform-independent

Mac user running Safari


Web page stored on Unix serv

Click on link to Applet


Byte code is downloaded

Windows user running Internet Explorer


Virtual machine translates byte code to
native Windows code and the Applet is run
Java: Write Once, Run Anywhere

• Java has been used by large and reputable


companies to create serious stand-alone
applications.
• Example:
– Eclipse1: started as a programming environment
created by IBM for developing Java programs. The
program Eclipse was itself written in Java.

1 For more information:


Compiled Programs With Different
Operating Systems

Windows
compiler

Executable (Windows)

Mac OS
Computer compiler
program
Executable (Mac)

UNIX
compiler

Executable (UNIX)
A High Level View Of Translating/Executing Java Programs

Stage 1: Compilation

Filename.java Java compiler Filename.class


(javac)

Java program Java bytecode


(generic binary)
JVM Security Capability

• JVM has many capabilities to keep the security of the


computer system.
• “SAND BOX”: Prohibit a JAVA applet
– Reading or writing to the local disk.
– Making a network connection to any host, except the host
from which the applet came.
– Creating a new process.
– Calling a any native methods.
JAVA Development Kit

•Java 7+ JDK (Java Development Kit), Standard


Edition includes:
– JDK (Java development kit) – for developing Java
software (creating Java programs.
– JRE (Java Runtime environment) – only good for
running pre-created Java programs.
•Java Plug-in – a special version of the JRE designed to run
through web browsers.
Java Development Kit

Text Editor

Java
Source javadoc HTML Files
Code

Javac

Java class Header


javah
File Files

java jdb

Java
Program
output
Introduction: java programming
• Configuration of Java program execution environment
– PATH : Environment variable
• Java program structure
• Program = code + data
• Data types
– Primitive types: Integer type, floating, char, logical
– Non-primitive types : array, string, class and interface
• Code: Programming constructs
– Key words: 50
– Control statements
– Iterative statements
– Operators: Logical, relational and arithmetic
• Coding standards: Pascal and Camel notation
• Reading input to java programs: command Line, Scanner
object
• Array in java
Introduction: java programming : Key words
abstract default implements this
assert do import true
boolean double instanceof throw
break else int throws
byte enum interface while
case extends long return
catch false new short
char final null static
class finally package
const float private
continue for super
Introduction: java programming: Data types
Integer Type Memory in bytes
byte 1
short 2
int 4
long 8
Floating Type
float 4
double 8
Textual
char 2 (Unicode character)
Logical
Boolean 1
Introduction: java programming: Coding standards
• Set of guidelines
– Enhance the readability and clarity of the program
– Make it easy to debug and maintain the program
• Class name: Should follow Pascal Case
i. First letter should be Upper case
ii. First letter of each internal word should be
capitalized (if it is present)
• Instance variable, Reference Variable & method
name(camel notation) i. First letter should be
lower case
ii. . First letter of each internal word should be
capitalized (if it is present)
Introduction: java programming: program structure
[package statement;]
[import statements;]
[Interface definition]
[class definition]
class class_name // starter class
{
public static void main(String[] args)
{
// code
}
}
Introduction: java programming: Example
// starter class or test program
class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello world”);
}
}
Introduction: java programming: Reading input from console
class CmdArgumentsDemo
{
public static void main(String[] args)
{
// prints first element
System.out.println(args[0]);

for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
//foreach version in java
/*
for(String s: args)
{
System.out.println(s);
}*/
}
}
Introduction: java programming: Assignment
Write a java program to read two numbers from
user and display sum. Use command line
arguments
Introduction: java programming: Arrays
An array is a collection of similar data in
contiguous locations of memory and referred by
single name.
Arrays can be used to store data belonging to
primitive data types and reference types.
Arrays are created dynamically in java

Types of array
One dimensional array
Multi-Dimensional (2D array)
Introduction: java programming: Creating array
One dimensional
First method
type[] array_name=new type[size];
Example: int[] marks=new int[5];

Initialize:
marks[0]=15; int x= marks[0];
marks[1]=20; // write a java program
marks[2]=16;
marks[3]=17;
marks[4]=20;
marks[5]=18;
Introduction: java programming: Creating array
Array elements will be stored dynamically in the heap
Array elements will be initialized to default values of respective
type if not explicitly initialized

15
20
marks
16
stack 17
20

heap
Introduction: java programming: Creating array
• Two dimensional array
type[][] array_name= new type[size][size];
int [][] LabPcs=new int [5][8];

Initialize:
LabPcs[0][0] = 1;
Labpcs[0][1]=2; // Write a java program
length property: it returns size of array.
Introduction: java programming: Creating array
Second method

type array_name={value1, value2, … , valueN};

example:
String deptNames={“AandR”, “BT”,”CSE”, “ISE” };

what is the size of the array?


Introduction: java programming: Creating array
An election is contested for 5 candidates. The
candidates are numbered 1 to 5 and the voting is
done by marking the candidate number on the
ballot paper by 20 peoples. Write a program to
read the ballots and count the votes cast for
each candidate. In case a number read is outside
the range 1 to 5, the ballot should be considered
as a spoilt ballot and the program should also
count the number of spoilt ballots.
Introduction: java programming: Architecture

Java source code .java

Compiler javac

Byte Code
Java interpreter

Platform specific Platform specific Platform specific


Instructions (windows) Instructions (Unix) Instructions (MacOS)

OutPut OutPut OutPut


String
• Java String provides a lot of concepts that can be performed
on a string such as compare, concat, equals, split, length,
replace, compareTo, intern, substring etc.
• In java, string is basically an object that represents sequence
of char values.
• An array of characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
• String s="javatpoint";
• The java String is immutable i.e. it cannot be changed but a
new instance is created.
• String Length
• int length
• String s= new String(“Hello”);
• System.out.println(s.length());
Special String operations

• String concatenation
• String age=“9”;
• String s=“He is”+age+”years old.”;
• System.out.println(s);
• String concatenation with other datatype
• int age = 9;
• String s=“He is “+age+”years old”;
• System.out.println(s);

• String s=“four:”+2+2;
• System.out.println(s);
• displays
four:22
Rather than
four:4
• String comparision
equals() and equalsIgnoreCase()
boolean equals(Object str)
boolean equalsIgnoreCase(String str)
Class equalsDemo{
public static void main(String args[]){
String s1=“Hello”;
String s2=“Hello”;
String s3=“Good-bye”;
String s4=“HELLO”;
System.out.println(s1+ “equals”+s2+”->”+s1.equals(s2));
System.out.println(s1+ “equals”+s3+”->”+s1.equals(s3));
System.out.println(s1+ “equals”+s4+”->”+s1.equals(s4));
System.out.println(s1+ “equals”+s2+”-
>”+s1.equalsIgnoreCase(s4));
}
}
String

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method app
//ends the string at the end
System.out.println(s);//will print Sachin because strings are im
mutable objects
}
}
OUTPUT:Sachin
For mutable class, you can use StringBuffer and StringBuilder
class.
String Buffer

• What is mutable string?


• A string that can be modified or changed is known as mutable string.
StringBuffer and StringBuilder classes are used for creating mutable string.
• It has several methods like
1. append()
2. length()
3. setLength()
4. insert()
5. reverse()
6. replace()
7. capacity()
8. ensureCapacity()
1) StringBuffer append() method

• The append() method concatenates the given


argument with this string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");
//now original string is changed
System.out.println(sb);//prints Hello Java }
}
length() :give number of characters in a string.
class A{
public static void main(String args[]){
String sb=new String("Hello ");
System.out.println(sb.length());
//prints 6
}
}
2) StringBuffer insert() method

• The insert() method inserts the given string with this


string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");
//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method

• The replace() method replaces the given string


from the specified beginIndex and endIndex.
Repalces characters from beginIndex to
endIndex-1.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() method

• The delete() method of StringBuffer class


deletes the string from the specified
beginIndex to endIndex. deletes characters
from beginIndex to endIndex-1.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method

• The reverse() method of StringBuilder class


reverses the current string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);
//prints olleH
}
}
6) StringBuffer capacity() method

• The capacity() method of StringBuffer class


returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the
number of character increases from its current
capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
7) StringBuffer ensureCapacity() method

• The ensureCapacity() method of StringBuffer


class ensures that the given capacity is the
minimum to the current capacity. If it is
greater than the current capacity, it increases
the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will
be (16*2)+2=34.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());/*now (16*2)+2=34 i.e (
oldcapacity*2)+2 */
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}