0% found this document useful (0 votes)
33 views

Java - Unit I

1) Java is an object-oriented programming language and platform that is designed to be portable and secure. It achieved portability through the use of bytecode and a Java Virtual Machine (JVM) that can run that bytecode on multiple platforms. 2) Java was created in 1991 by James Gosling at Sun Microsystems to be used for digital devices but became widely popular for developing web applications. It addressed issues of portability and security on the Internet through its design. 3) Java code is compiled to bytecode that runs on a JVM, allowing the same code to run on different platforms. Servlets allowed Java code to run server-side, simplifying web programming and addressing issues the Internet faced.

Uploaded by

Naturæl Ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Java - Unit I

1) Java is an object-oriented programming language and platform that is designed to be portable and secure. It achieved portability through the use of bytecode and a Java Virtual Machine (JVM) that can run that bytecode on multiple platforms. 2) Java was created in 1991 by James Gosling at Sun Microsystems to be used for digital devices but became widely popular for developing web applications. It addressed issues of portability and security on the Internet through its design. 3) Java code is compiled to bytecode that runs on a JVM, allowing the same code to run on different platforms. Servlets allowed Java code to run server-side, simplifying web programming and addressing issues the Internet faced.

Uploaded by

Naturæl Ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

1

Object Oriented Programming using JAVA


UNIT I

The History and Evolution of Java


What is Java
1. Java technology is both a programming language and a platform.
2. Java is a high level, robust, secured and object-oriented programming language.

Java programming language:

The Java programming language is a high-level and object-oriented language that


can be characterized by all of the following buzzwords / features:

i) Simple vii) Portable


ii) Object oriented viii) Interpreted
iii) Distributed ix) High Performance
iv) Multithreaded x) Robust
v) Dynamic xi) Secure
vi) Architecture Neutral

Java Platform:

Any hardware or software environment in which a program runs is known as a platform.


Since Java has its own runtime environment (JRE-Java Runtime Environment) and API, it
is called platform.

The Java platform has two components – API and Java Virtual Machine

The Java Virtual Machine :

It is an abstract machine and it is the base for the


Java platform and is ported onto various hardware-
based platforms.

The Java Application Programming Interface (API) :

The API is a large collection of ready-made software


components that provide many useful capabilities. It
is grouped into libraries of related classes and
interfaces; these libraries are known as packages.
2

The Creation of Java


Java was originally developed to develop a language for digital devices such as set-top
boxes.

Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun
Microsystems Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995.

Primary Motivation(s) for Java creation:


1. The primary motivation was the need for a platform-independent (architecture-
neutral/portable) language that could be used to create software to be
embedded in various consumer electronic devices, such as microwave ovens
and remote controls.
2. The second important factor is the World Wide Web / Internet.
a) Java is used to develop web based programs / Internet programming.
b) The Internet consists of a diverse, distributed universe populated with various
types of computers, operating systems, and CPUs.
Platform Independence or Architecture Neutral or Portable:
(Write Once, Run Anywhere)
a) Java is a Platform Independent language. Java sometimes called as “Write Once,
Run Anywhere (WORA)” language.
b) Java achieves platform independence through bytecode and JVM.

Java Program Execution:


1. In the Java programming language, all source code is first written in plain text files
ending with the .java extension.
2. Those source files are then compiled into .class files by the javac compiler.
3. A .class file does not contain code that is native to your processor; it instead
contains bytecodes — the machine language of the Java Virtual Machine (Java
VM).
3

4. The java launcher tool then runs your application with an instance of the Java Virtual
Machine.
5. Through the JVM, the same application is capable of running on multiple platforms.

Bytecode:

Bytecode is a highly optimized set of


instructions designed to be executed
by the Java run-time system, which is
called the Java Virtual Machine (JVM).

Java is platform independent but


JVM is platform dependent:

JVM is platform independent because


JVM is designed to each platform
separately.

Java’s magic: bytecode

1) Translating a Java program into bytecode makes it much easier to run a program in
a wide variety of environments because only the JVM needs to be implemented for
each platform.

2) Although the details of the JVM will differ from platform to platform, all understand
the same Java bytecode.

3) A Java program is executed by the JVM also helps to make it secure. Because the
JVM is in control, it can contain the program and prevent it from generating side
effects outside of the system.

Java’s Lineage (Ancestry or pedigree)


4

Java is related to C++, which is a direct descendant of C.

 Much of the character of Java is inherited from these two languages.

 From C, Java derives its syntax.

 Many of Java’s object oriented features were influenced by C++.

Java vs C vs C++
Aspects C C++ Java
Developed Year 1972 1979 1991
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
Paradigms Procedural Object Oriented Object Oriented
Platform Dependent Dependent Independent
Dependency
Header files Supported Supported Use Packages
(import)
Pointers Supported Supported No Pointers
Storage Allocation Uses malloc, calloc Uses new , delete uses garbage
collector

Multi-threading Not Supported Not Supported Supported


Exception Handling No Exception Supported Supported
handling
Destructors No Constructor or Supported Not Supported
Destructor
Inheritance No Inheritance Supported Multiple Inheritance
not Supported
Overloading No Overloading Supported Operator
Overloading not
Supported

C compile time vs Java Compile Time


5

C++ compiler &


Linker usage
file1.cpp file2.cpp filen.cpp
….
Comp Comp Comp
iler iler iler
file1.o file2.o filen.o
….

Linker
application
This C++ compiler
appliction (executabl does not care
e)
runs about
directly on filenames.
top of OS.
Java compiler
6

file1.jav usage filen.jav


file2.jav
a a …. a
Compi Compi Compi
ler ler ler
file1.clas file2.clas filen.clas
s s …. s

Java Runtime Environment


(JRE)
Operating System

How Java changed the Internet / Java’s contribution to the


Internet
Servlets : Java on the Server Side
The Internet helped catapult Java to the forefront of programming and Java, in turn, had a
profound effect on the Internet.

Java helped in the following features:

a) Simplified web programming


b) Applet development
c) Addressed the issues with the Internet : portability and security

a) Simplified Web programming

i. Java is used in client / server programming. Servlet is used in this


programming.
7

ii. A servlet is a small program that executes on the server.


iii. Servlets are used to create dynamically generated content that is then
served to the client.
iv. Because servlets (like all Java programs) are compiled into bytecode and
executed by the JVM, they are highly portable.
v. Example: Online Store

b) Applets

i. An applet is a special kind of Java program that is designed to be transmitted


over the Internet and automatically executed by a Java-compatible web
browser.
ii. The creation of the applet changed Internet programming because it
expanded the universe of objects that can move about freely in cyberspace.
iii. The applet is a dynamic, self-executing program.

c) Portability and Security issues

i. Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it.
ii. The Bytecode made Java code to be portable.
iii. Security : Java achieved the security by confining internet based programs
(applet) to the Java execution environment and not allowing it access to other
parts of the computer

JAVA Buzzwords / Features:


The prime reason behind creation of Java was to bring portability and security feature into
a computer language. Beside these two major features, there were many other features that
played an important role in Java language creation. Those features are:

1. Simple:

a) Java is easy to learn and its syntax is quite simple, clean and easy to understand.
b) It is simple because, Syntax is based on C and C++.
c) Java removed pointers and operator overloading concepts.

2. Object oriented:

a) In Java, everything is an object which has some data and behavior.


b) The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non-objects.
c) Java supports all the OOP features:
i. Class
ii. Object
iii. Encapsulation
8

iv. Inheritance
v. Polymorphism
vi. Abstraction

3. Distributed: Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols. Java has features that enables a program to invoke methods
across a network.

4. Multithreaded: With java’s multi-threaded feature it is possible to write programs that


can do many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications. Benefit of multithreading is that it utilizes same
memory and other resources to execute multiple threads at the same time.

5. Dynamic: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This makes it
possible to dynamically link code in a safe and expedient manner. This is crucial to the
robustness of the Java environment, in which small fragments of bytecode may be
dynamically updated on a running system.

6. Architecture Neutral (Platform Independent):

i. C and C++ are platform dependency languages, But Java is platform independent
language.
ii. Java designers goal was “Write once; run anywhere, any time, forever”(WORA).
Java programs written in one operating system can able to run on any operating
system.
iii. Java compiler generates an architecture-neutral bytecode which makes the compiled
code to be executable on many processors with the presence of Java run time
system (JVM).

7. Portable: Java is a portable language means, we can carry the same Java bytecode to
any platform.

8. Interpreted: Java’s bytecode is interpreted by Java Virtual Machine (JVM). Java’s


bytecode was carefully designed so that it will be easily translated into Native code.

9. High Performance: Java is faster than traditional interpretation since byte code was
carefully designed so that it would be easy to translate directly into native machine code for
very high performance by using a just-in-time compiler (JIT).
9

10. Robust: The ability to create robust programs was given a high priority in the design
of Java.

Some of the reasons for Java is called as a robust language:

i. Strongly Typed Language


a. Java checks the code at compile time.
ii. Automatic Memory Management (Garbage collection)
a. In C/C++, the programmer will manually allocate and free all dynamic
memory. This sometimes leads to problems, because programmer will forget
to free the memory.
b. In Java, memory de-allocation is done automatically through Garbage
Collection.
iii. Error Handling
a. Java provides object-oriented exception handling to handle the errors in java
program.
b. Using exception handling, all run time errors should be managed by the
program.

11. Secure: Java is secured because:

i. No explicit pointers.
ii. Java Programs run inside virtual machine environment.

Evolution of Java
Java continued to evolve at an explosive pace.

It has dynamic history. Since the beginning, Java has been at the center of a culture of
innovation.
10

Java Version Release History


Version Description / Features / Enhancements
Java 1.0 / JDK1.0 Initial Version Release
Java1.1/ JDK 1.1 Added AWT,JDBC,RMI,Javabeans etc
Java 2 / J2SE 1.2 Swings,Collection framework, JIT compiler in JVM
(Java 2 Standard
Edition)
J2SE 1.3 Smaller set of changes added to the existing functionality
J2SE 1.4 ASSERT keyword,Chained exceptions, Regular Expressions,Image
I/O API for reading and writing images
J2SE 5 Generics,Annotations,Autoboxing and auto-unboxing, Enumerations,
Enhanced for loop, Variable-length arguments(varargs),static import,
Formatted I/O,Concurrency utilities.
Java SE 6 (Java Synchroization and compiler performance optimizations, Garbage
Platform Standard collection algorithms
Edition)
Java SE 7 / JDK 7 Try-with-resources,Type interface, Underscores in numeric
literals,Binary integer literals, A String can control a Switch
statement, Parallel programming, Multi Catch Exception
Java SE 8 / JDK 8 New feature – lambda expression, java.util.stream, Enhanced
Security

Java Conceptual Diagram


Below is the High-level conceptual diagram of Java language.

JDK
JRE
JVM
JIT
11

JRE (Java Runtime Environment)


The Java Runtime Environment (JRE) provides

1) the libraries,

2) the Java Virtual Machine,

3) and other components to run applets and applications written in the Java
programming language.

4) In addition, two key deployment technologies are part of the JRE:

 Java Plug-in : It enables applets to run in popular browsers;

 Java Web Start : It deploys standalone applications over a network.

5) The JRE does not contain compilers or debuggers for developing applets and
applications.

JRE = The Libraries + JVM + Java Plug-in + Java Web Start + Other components

JDK (Java Development Kit)


1) The JDK is a superset of the JRE,
2) and contains everything that is in the JRE, plus tools such as the compilers and
debuggers necessary for developing applets and applications.
JDK = JRE + compilers + debuggers + etc.
12

JVM (Java Virtual Machine)


1) JVM is an Interpreter for bytecode.

2) The Java virtual machine is an abstract computing machine that has an instruction
set and manipulates memory at run time.

3) The Java Virtual Machine is responsible for the hardware- and operating system-
independence of the Java SE platform, the small size of compiled code (bytecodes),
and platform security.

4) JVM includes dynamic compilers – Just In Time Compilers (JIT) that adaptively
compile Java bytecodes into optimized machine instructions.

Internal Architecture of the JVM


13

1. class loader subsystem: a mechanism for loading types (classes and interfaces)

2. Execution engine: a mechanism responsible for executing the instructions


contained in the methods of loaded classes.

3. Run Time Data areas: The Virtual machine organizes the memory it needs to
execute a program into several runtime data areas.
i. Method area: All the class data has been placed on to the method area.
ii. Heap: All objects the program instantiates is placed onto the heap.
iii. Java Stacks: A Java stack stores the state of Java (not native) method
invocations for the thread.
iv. PC registers: The value of the pc register indicates the next instruction to
execute.
v. Native Method stacks: Native methods are the methods written in a
language other than the Java programming language. These are the stacks
created for other languages functions or operating system functions.

JIT (Just-In-Time Compiler)


1) Java is a interpreted language, so it is considered as a slow language when
compared with compiled languages.
2) But Hot-spot technology of Java was introduced to boost performance of the Java
language.
3) HotSpot provides a Just-In-Time (JIT) compiler for bytecode.
4) When a JIT compiler is part of the JVM, selected portions of bytecode are compiled
into executable code in real time, on a piece-by-piece, demand basis.
5) Not all sequences of bytecode are compiled—only those that will benefit from
compilation.
6) The remaining code is simply interpreted.
7) The just-in-time approach still yields a significant performance boost.

Object Oriented Programming (OOP)


Programming Paradigms
There are two ways of writing programs:

1) Process oriented model (Procedure oriented programming)


2) Object oriented programming
14

Process oriented model OOP

Organizes a program around its code. Organizes a program around its data (that is, objects).

A program is written as a series of linear A program is written as a collection of classes and


steps. objects

Program contains procedures. Program contains classes, objects.

Ex: C uses this approach Ex: Java uses this approach.

Procedure oriented model Object oriented model

proce metho
dure d
metho Object
d data
proce
dure metho
Global
proce d
metho Object
data
dure d data
proce metho
dure d
metho Object
d data

OOP principles / components


Definition: OOP is a programming methodology that helps organize complex programs
through the use of inheritance, encapsulation, and polymorphism.

Components:
1. Classes
2. Objects
3. Abstraction
15

4. Encapsulation (Data Encapsulation)


5. Inheritance
6. Polymorphism
7. Access Levels
8. Interfaces
9. Packages

Three OOP Principles


1. Encapsulation
2. Inheritance
3. Polymorphism

Class: A class defines the structure and behavior (data and code) that will be shared by a
set of objects. A class is a structure that defines the data and the methods (functions in
other languages) to work on that data.

In Java, all program data is wrapped in a class.

import java.lang.System;
class ExampleProgram
{
public static void main(String[] args)
{
System.out.println(“Hello World");
}
}

Object: An instance of a class is called as an Object.

1) There can be any number of objects of a given class in memory at any one time.
2) Software objects are conceptually similar to real-world objects.
3) Objects consist of state and behavior.
4) An object stores its state in fields (variables in some programming languages) and
exposes its behavior through methods (functions in some programming languages).
16

A software object A bicycle modeled as a software object

Abstraction:

a) An essential element of object-oriented programming is abstraction.


b) Abstraction is defined as hiding the complexities of the system.
c) A powerful way to manage abstraction is through the use of hierarchical
abstractions (classifications).
d) Humans manage complexity through abstraction.
e) For example, people do not think of a car as a set of tens of thousands of individual
parts. They think of it as a well-defined object with its own unique behavior.

Hierarchical classifications

CAR

Steering Seat belts


Brakes Sound

MP3 player
Radio
CD Player
17

Three OOP Principles

1. Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.

i. Encapsulation is sometimes called as Information hiding.


ii. In Java, the basis of encapsulation is the class.
iii. Using Access Modifiers (private, public), the members of the class can be
protected from misuse by the outside classes.
iv. private members can only accessed by the members of the class.
v. public members can be accessed by any members of the class or outside members
of the class.
vi. Programs should interact with object data only through the object’s methods.
vii. Benefits of Encapsulation are: reuse and reliability.

Example:
18

class Bicycle
{
int cadence = 0; Member
int speed = 0; variables (OR)
int gear = 1; Instance
Member
variables memb
methods (OR)
void changeGear(int newValue) ers
methods
{
gear = newValue;
}
}
class BicycleDemo
{
public static void main(String[] args)
{
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

bike1.changeGear(2);
bike2.changeGear(5);
}
}

2. Inheritance:
Inheritance is the process by which one object acquires the properties of another object.

i. Inheritance defines relationships among classes in an object-oriented language.


19

ii. Inheritance allows classes to inherit commonly used state and behavior from other
classes.
iii. It supports the concept of hierarchical classification.
iv. Benefits are : Code reuse and Decrease of Program size
v. In the Java programming language, all classes descend from java.lang.Object, that
is, Object is the superclass for all classes.

Example:
a) Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear).

b) Yet each also defines additional features that make them different: tandem bicycles
have two seats and two sets of handlebars; road bikes have drop handlebars; some
mountain bikes have an additional chain ring, giving them a lower gear ratio.

Superclass

subclasses

Syntax for creating subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration, use
the extends keyword, followed by the name of the class to inherit from:

Also contains the same fields and


methods as Superclass Bicycle, but
that code will not appear.
20

class MountainBike extends Bicycle {

// new fields and methods defining


// a mountain bike would go here

Subclass = Same attributes of super class + any attributes of subclass

 In the Java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number
of subclasses.

3. Polymorphism: Polymorphism in Greek, meaning “many forms”.

Definition:
Polymorphism in java is a concept by which we can perform a single action by
different ways.

a) In JAVA, More generally, the concept of polymorphism is often expressed by the


phrase “one interface, multiple methods.”
b) We can perform polymorphism in java by method overloading and method
overriding.

Types of Polymorphism:

There are two types of polymorphism in java:


1. Compile time polymorphism and
2. Runtime polymorphism.

Example

i. You might have a program that requires three types of stacks.


ii. One stack is used for integer values, one for floating point values, and one for
characters.
iii. The algorithm that implements each stack is the same, even though the data being
stored differs.
iv. In a non–object-oriented language, you would be required to create three different
sets of stack routines, with each set using different names.
v. However, because of polymorphism, in Java you can specify a general set of stack
routines that all share the same names.

FIRST JAVA Program - Description


This is called as
Multi Line Comment
21

/* This is a simple Java program.


Call this file "Hello.java".
*/
class Hello { This is called as Single
// this is main method Line Comment
public static void main(String args[])
{
System.out.println(“Hello”);
}

class : class keyword is used to declare classes in Java.


public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a static function
you do not have to create an Object of the class. The main() method here is called by JVM,
without creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the method
which is executed, hence all the logic must be inside the main() method. If a java class is
not having a main() method, it causes compilation error.
System.out.println: This is used to print anything on the console like printf in C language.

Steps to Compile and Run our first Java program

Step 1: Open a text editor and write the code as above.


Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java
program assuming it is saved in D:\
Step 4: Type javac Hello.java and press Enter to compile your code.
D:\>javac Hello.java
This command will call the Java Compiler asking it to compile the specified file. If there are
no errors in the code the command prompt will take you to the next line.
Step 5: Now type java Hello on command prompt to run your program.
D:\>java Hello
Step 6: You will be able to see Hello printed on your command prompt.
22

Code blocks (or) blocks of code


i. Java allows two or more statements to be grouped into blocks of code, also called
code blocks.
ii. Code blocks can be created by enclosing the statements between opening and
closing curly braces.
iii. Once a block of code has been created, it becomes a logical unit that can be used
any place that a single statement can.

Example:

/* Demonstrate a block of code.

Call this file "BlockTest.java"


*/

class BlockTest {
public static void main(String args[]) {
if(x < y) If X is less than Y then both
{ // begin a block statements inside the block
x = y; will be executed.
y = 0;
} // end of block
}
}

Lexical Issues (or) Atomic Elements of Java


23

Java programs are a collection of –


1) whitespace
2) identifiers
3) literals
4) comments
5) operators
6) separators and
7) keywords

whitespace
a) Java is a free-form language – do not need to follow any indentation rules.
b) In Java, whitespace is a space, tab, or newline.

Identifiers
a) Identifiers are used to name classes, variables, and methods.
b) An identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
c) Java is case-sensitive language.

Valid Identifiers: Invalid Identifiers

AvgTemp 2count
Count high-temp
A4 Not/ok
$test
This_is_ok

Literals

A constant value in Java is created by using a literal representation of it.

Example:

integer literal 100


floating-point literal 98.6
character literal ‘X’
String literal “This is a test”

Integer Literals

3 bases are used to represent integer literals –


1) Decimal (base 10)
Ex: 1, 2, 3 and 42

2) Octal (base 8) - denoted by a leading zero


Ex: 05

3) Hexadecimal (base 16) - denoted by a leading zero-x (0x or 0X)


24

Ex: ox7f

Floating-point Literals

1) Represented in –
a) Standard notation -> 2.0, 3.14
b) Scientific notation -> 6.022E23, 314159E-05
2) Floating point literals in Java default to double precision.
3) To specify a float literal, we must append an F or f to the constant.
4) Hexadecimal floating point literals are also supported.
Ex: 0x12.2P2

Boolean Literals

It contains only two logical values - true or false. These values do not convert into any
numerical representation.

Character Literal
1) A literal character is represented inside a pair of single quotes.
2) All of the visible characters can be directly entered inside the quotes, such as 'a', 'z',
and '@'.
3) For characters that are impossible to enter directly, there are several escape
sequences.
Ex: ‘\’’ for single-quote character
‘\n’ for the new line character
4) Characters can be represented in Octal and Hexadecimal notation
Octal
backslash followed by the three-digit number. For example, ' \141' is the letter 'a'.
Hexadecimal
a backslash-u ( \u), then exactly four hexadecimal digits. For example, ' \u0061'

Escape Sequence Description


\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character (xxxx)
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace

String Literal

String literals in Java are specified by enclosing a sequence of characters between a pair of
double quotes.
25

Example:

"Hello World"
"two\nlines"
" \"This is in quotes\""

Comments

There are 3 types of comments defined by Java.

1) Single-line comments starts with //

Example: // Test program

2) Multi-line comments begins with /* and ends with */

Example : /* Program for Multiplication


*/

3) Documentation comment begins with a /** and ends with a */

Example : /**
First Java Program
*/

Separators

In Java, there are a few characters that are used as separators.

Symbol Name Purpose


( ) Parentheses Used in method parameters, expressions, casting
{ } Braces Array initializer, block of code, classes and methods
[ ] Brackets Declare array types and used when dereferencing array
values
; Semicolon Terminates statements.
, Comma Variable declarations, inside a for statement
. Period Used to separate package names from subpackages and
classes. Also used to separate a variable or method from a
reference variable.
.. Colons Used to create a method or constructor reference. (Added by
.. JDK 8.)

The Java Keywords :

Keywords are the reserved words which can not be used as identifiers in program.
26

i. There are 50 keywords currently defined in the Java language.


ii. The keywords const and goto are reserved but not used.
iii. true, false, and null are also reserved. These are the values defined by Java. We
may not use these words for the names of variables, classes, and so on.

abstract continue for new switch


Assert default Goto package synchronized
Boolean do If private this
Break double implements protected throw
Byte else import public throws
Case enum instanceof return transient
Catch extends Int short try
Char final interface static void
Class finally Long strictfp volatile
Const float native super while

The Java class Libraries (API)


1) Java class libraries provide much of the functionality that comes with Java.
2) Java language is a combination of the Java language itself, plus its standard
classes.
3) Java environment relies on several built-in class libraries that contain many built-in
methods that provide support for Input / Output, String handling, networking,
graphics and Graphical User Interface (GUI).
4) Java has very rich and large Application Programming Interface (API) content.

Example:

println() and print() methods are built-in methods and available through System.out.

System is a predefined class and out is an output stream associated with system.

Data Types, Arrays and Variables


Data Types
27

Java is a Strongly Typed Language -

a) Every variable has a type, every expression has a type, and every type is strictly
defined.
b) All assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility.
c) There are no automatic conversions of conflicting types as in some languages.
d) The Java compiler checks all expressions and parameters to ensure that the types
are compatible.

Primitive Data Types and Ranges


1) Primitive types are also called as Simple types. The primitive types represent single
values.

2) A primitive can be one of eight types:

char, boolean, byte, short, int, long, double, or float.

2) Primitive variables can be declared as class variables (static), instance variables,


method parameters, or local variables.

byte b;

boolean myBooleanPrimitive;

int x, y, z; // declare three int primitives


28

3) The number types (both integer and floating point types) are all signed, meaning they can
be negative or positive.

4) The leftmost bit (the most significant digit) is used to represent the sign, where a 1 means
negative and 0 means positive. The rest of the bits represent the value, using two's
complement notation.

Type Bits Bytes Minimum Range Maximum Range

byte 8 1 -128 (- 27) 127 (27-1)

short 16 2 -32768 (-215) 32767 (215-1)

int 32 4 -231 231-1

long 64 8 -263 263-1

float 32 4 4.9e–324 1.8e+308

double 64 8 1.4e–045 3.4e+038

char 16 2 0 65535

boolean: The boolean data type has only two possible values: true and false.

Characters (char)

a) In Java, the data type used to store characters is char.


b) char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. In
Java, char is 16 bit.
c) Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages.
d) At the time of Java's creation, Unicode required 16 bits. Thus, in Java char is a 16-bit
type. The range of a char is 0 to 65,536. There are no negative chars.

Example
29

Example for char data type


// Demonstrate char data type.

class CharDemo
{ Output:
public static void main(String args[]) {
char ch1, ch2; ch1 and ch2 : X Y
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

// char variables behave like integers.


class CharDemo2
{ Output:
public static void main(String args[])
{ ch1 contains X
char ch1;
ch1 is now Y
ch1 = 'X';
System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1


System.out.println("ch1 is now " + ch1);
}
}

Example for double data type


// Compute the area of a circle.
class Area { Output:
public static void main(String args[]) {
double pi, r, a; Area of circle is
r = 10.8; // radius of circle 366.436224
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area

System.out.println ("Area of circle is ” + a);


}
}

Example for boolean data type


30

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
boolean b;
Output:
b = false;
System.out.println("b is " + b); b is false
b = true;
System.out.println("b is " + b); b is true

This is executed.
// a boolean value can control the if statement
if(b) 10 > 9 is true
System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value


System.out.println("10 > 9 is " + (10 > 9));
}
}

Reference Types

reference

1) A reference variable is used to refer to (or access) an object.


2) Class types, array types and interface types are called as references.
3) Reference variables can be declared as static variables, instance variables, method
parameters, or local variables.

Object o;
Pen p1;
String s1, s2, s3; // declare three String vars.

Example

class A
{
int i;
void m1() {
System.out.println(“Hello”);
}

class Test
{
31

public static void main(String args[])


{
A obj; // reference
obj = new A(); // object
}
}

Variables :

Variables are the identifiers of the memory location, which used to store the data temporary
for later use.

Declaring a Variable:

a) In Java, all variables must be declared before they can be used.


b) The basic form of a variable declaration is shown here:

type identifier [ = value ][, identifier [= value ] …];

Here, type is the data type or class name or interface name.

c) To declare more than one variable of the specified type, use a comma-separated list.

Example:

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization:

Java allows variables to be initialized dynamically, using any expression valid at the time
the variable is declared.

class DynInit {
public static void main(String args []) {
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = a + b;

System.out.println ("C value is ” + c);


}
}
32

The Scope(Visibility) and Lifetime of Variables

Scope:
a) A scope determines what objects are visible to other parts of your program.
b) It also determines the lifetime of those objects.

In Java, there are two major scopes:


i. Scope defined by a Class
ii. Scope defined by a Method

Scope defined by a Method (or) block scope

a) The scope defined by a method begins with its opening curly brace and ends with
closing curly brace.
b) Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
c) Every block defines a new scope.
d) Scopes can be nested:
i. objects declared in the outer scope will be visible to the code within
the inner scope.
ii. Objects declared within the inner scope will not be visible outside it.
iii. We cannot declare a variable to have the same name as one in an
outer scope.

// Demonstrate block scope and Nested scope

class Scope {
public static void main(String args[]) {
int x; // known to all code within main

x = 10;
{ // start new scope
int y = 20; // known only to this block

// x and y both known here.


System.out.println("x and y: " + x + " " + y);
x = y * 2;
}

// y = 100; // Error! y not known here

// x is still known here.


System.out.println ("x is ” + x);
}
}
33

// Nested scope – Outer scope and inner scope with same variable
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Lifetime of a variable

a) The lifetime of a variable is confined to its scope.


b) Variables are created when their scope is entered, and destroyed when their scope
is left. This means that a variable will not hold its value once it has gone out of
scope.
c) If a variable declaration includes an initializer, then that variable will be reinitialized
each time the block in which it is declared is entered.

// Demonstrate lifetime of a variable.

class LifeTime {
public static void main(String args[]) {
int x;

for(x = 0; x < 3; x++) {


int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1

y = 100;
System.out.println("y is now: " + y);
}
}
}

Type Conversion and Casting

1) Assigning a value of one type to a variable of another type is known as Type


conversion.
2) In Java, Type conversions will occur in two places :
a. In Assignments
b. In Expressions

3) In Java, Type conversion is classified into two types:


34

a. Automatic / Widening conversion / Implicit conversion (Between


compatible types)

b. Casting / Narrowing conversion / Explicit conversion (Between


Incompatible types)

Type Conversion in Assignments

1. Automatic Conversions / Widening conversion / Implicit conversion

1) When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
i. The two types are compatible.
ii. The destination type is larger than the source type.
2) For widening conversions, the numeric types, including integer and floating-point
types, are compatible with each other.
3) There are no automatic conversions from the numeric types to char or boolean.
4) Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.

public class Test


{
public static void main(String[] args) Ouput:
{
int i = 100; Int value 100
long L = i; //no explicit type casting required Long value 100
float f = L; //no explicit type casting required Float value 100.0
char ch = 100; //no explicit type casting required Char value d

System.out.println("Int value "+i);


System.out.println("Long value "+L);
System.out.println("Float value "+f);
System.out.println("Char value "+ch);
}
}

2. Explicit conversion or Casting or Narrowing conversion


35

1) To create a conversion between two incompatible types, we must use a cast.


2) A cast is simply an explicit type conversion.
3) The general form of Casting is –

(target-type) value
Note:
 When a floating-point value is assigned to an integer type then truncation will occur.
 If the size of the value is too large to fit into the target integer type, then that value
will be reduced modulo (the remainder of an integer division by the) target
type’s range.

// Demonstrate casting
class Casting {
public static void main(String args[]) {
byte b; Output:
int I = 257;
double d = 323.142; Conversion of int to byte.

System.out.println("\n Conversion of int to byte."); I and b: 257 1


b = (byte) I;
System.out.println("I and b: " + I + " " + b); Conversion of double to int.

System.out.println("\n Conversion of double to int."); d and I: 323.142 323


I = (int) d;
System.out.println("d and I :" + d + " " + I); Conversion of double to byte.

System.out.println("\n Conversion of double to byte."); d and b: 323.142 67


b = (byte) d;
System.out.println("d and b: " + d + " " + b);
}
}

Type Conversion in Expressions

Automatic Type Promotion in Expressions

Java’s Type Promotion Rules

1. All byte, short, and char values are promoted to int.


2. If one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands are double, the result is double.

Example:
Output:
byte b = 50;
Compilation Error (because, in expression,
byte is promoted to int so, the result also int)
36

b = b * 2;

Example
class Test {
public static void main(String args[]) {
byte b = 42;
char c = 'a'; Output:
short s = 1024;
int i = 50000; 235.2 + 515 - 126.3616
float f = 5.67f;
double d = .1234; result = 623.8384122070313

double result = (f * b) + (i / c) - (d * s);

System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));

System.out.println("result = " + result);


}
}

Arrays
1. In Java, arrays are objects.
2. An array is a container object that holds a fixed number of values of a single type.
3. Arrays can hold either primitives or object references, but the array itself will
always be an object on the heap memory.
4. Arrays offer a convenient means of grouping related information.
5. In Java all arrays are dynamically allocated.
6. We can access a specific element in the array by specifying its index within square
brackets. All array indexes start at zero.

Types of Arrays

2 types of arrays exist:

a) One-Dimensional arrays
37

b) Multidimensional arrays

One-Dimensional arrays
Syntax:

type var-name [ ];
var-name = new type [size];

Declaring an Array of Primitives

int [ ] key; // Square brackets before name (recommended)


int key [ ]; // Square brackets after name (legal but less readable)

Declaring an Array of Object References

String [ ] s1; // Recommended


String s1 [ ]; // Legal but less readable

Note:

It is never legal to include the size of the array in your declaration.


Ex:
int[5] scores; // this code won’t compile.

Creating, Initializing, and Accessing an Array

1) Arrays are created or constructed by using new on the array type.


2) To create an array object, Java must know how much space to allocate on the heap,
so we must specify the size of the array at creation time.
3) The size of the array is the number of elements the array will hold.

Creating One-Dimensional Arrays :

int[ ] months;
months = new int[12];

Initializing an array:

months[0] = 1; // initialize first element


months[1] = 2; // initialize second element
months[1] = 2; // and so forth

Accessing an array:

Each array element is accessed by its numerical index:


System.out.println("Element 1 at index 0: " + months[0]);
System.out.println("Element 2 at index 1: " + months[1]);
38

System.out.println("Element 3 at index 2: " + months[2]);

Default values for Array elements

The elements in the array allocated by new will automatically be initialized to


i. Zero for numeric types
ii. false for boolean
iii. null for reference types
iv. ‘\u0000’ for char types

// Demonstrate a one-dimensional array.


class Array
{
public static void main(String args[])
{
int month_days[]; // declares an array of integers
month_days = new int[12]; // allocates memory for 12 integers

month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

array initializer

 Arrays can be initialized when they are declared.


 An array initializer is a list of comma-separated expressions surrounded by curly
braces.
 There is no need to use new.
 The Java run-time system will check to be sure that all array indexes are in the
correct range.
 If we try to access elements outside the range of the array (negative numbers or
numbers greater than the length of the array), we will get a run-time error.

class Array
{
39

public static void main(String args[])


{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

Multidimensional arrays

1. In Java, multidimensional arrays are actually arrays of arrays.

int twoD[ ][ ] = new int[4][5]; -> an array of arrays of int.

Right index determines column

[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]

Left index
determines row [1] [0] [1] [1] [1] [2] [1] [3] [1] [4]

[2] [0] [2] [1] [2] [2] [2] [3] [2] [4]

[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]

2. In Java, When we allocate memory for a multidimensional array, we need only


specify the memory for the first (leftmost) dimension. We can allocate the
remaining dimensions separately.

int twoD[ ][ ] = new int[4][ ];


twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

// Demonstrate a two-dimensional array.

class TwoDArray { p
public static void main(String args[]) {
int twoD[ ][ ]= new int[4][5]; Output:

01234
56789
10 11 12 13 14
15 16 17 18 19
40

int i, j, k = 0;

for(i=0; i<4; i++)


for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}

for(i=0; i<4; i++) {


for(j=0; j<5; j++)
System.out.println(twoD[i][j] + " ");
System.out.println();
}
}
}

Example:

Write a Java Program to print the following output

0
1 2
3 4 5
6 7 8 9

class TwoDAgain
{
public static void main(String args[])
{
int twoD[ ][ ] = new int[4][ ];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];

int i, j, k = 0;

for(i=0; i<4; i++)


for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}

for(i=0; i<4; i++)


{
41

for(j=0; j<i+1; j++)


System.out.print(twoD[i][j] + " ");
System.out.println();
}

}
}

Three dimensional arrays

It requires three dimensions.

int threeD[ ][ ][ ] = new int[3][4][5];

Strings

1) String is not a primitive type.


2) String defines an object.
3) The String type is used to declare string variables.
4) We can also declare arrays of strings.
5) A quoted string constant can be assigned to a String variable.
6) A variable of type String can be assigned to another variable of type String.
7) We can use an object of type String as an argument to println( ).

String str = "this is a test";


str is an object reference of type
System.out.println(str);
String.

Pointers
1) C and C++ supports pointers.
2) But, Java does not support or allow pointers
3) Java is designed in such a way that as long as we stay within the confines of the
execution environment, we never need to use a pointer.
4) There would not be any benefit using pointers.
5) In Java, memory management is handled by Garbage Collector.

UNIT – I END

You might also like