You are on page 1of 62

KG College of Arts and Science

Affiliated by Bharathiar University and Accredited by NAAC


KGiSL Campus, Saravanampatti, Coimbatore, Tamilnadu, India.

Department of Computer Applications

Subject Name : Java Programming

Subject Code : 33B

Class : II BCA‘B’

Semester : III

Prepared by : J.S.Kavithamani
Assistant Professor
Department of Computer Applications
KG College of Arts and Science
Unit – I
Fundamentals of Object-Oriented Programming
& Java Evolution
•Java is a general-purpose, concurrent, object-oriented,
class-based, and the runtime environment(JRE) which
consists of JVM which is the cornerstone of the Java
platform.
•It is used for:
INTRODUCTIO • Mobile applications (specially Android apps)
N TO JAVA • Desktop applications
• Web applications
• Web servers and application servers
• GamesDatabase connection
• And much, much more!
• Java works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in
the world
• It is easy to learn and simple to use
• It is open-source and free
Why Use • It is secure, fast and powerful

Java? • It has a huge community support (tens of millions of


developers)
• Java is an object oriented language which gives a clear
structure to programs and allows code to be reused,
lowering development costs
• As Java is close to C++ and C#, it makes it easy for
programmers to switch to Java or vice versa
• Java is a programming language
developed by James Gosling
with other team members named
Mike Sheridan and Patrick
Naughton also called as Green
History of Java Team in 1995 for Sun
Microsystems.
• It is an object-oriented language similar to C++, but with
advanced and simplified features. Java is free to access
and can run on all platforms.
• Java is: –
• Concurrent where you can execute many statements
instead of sequentially executing it.
• Class-based and an object-oriented programming
language.
What is • Independent programming language that follows the
Java? logic of “Write once, Run anywhere” i.e. the compiled
code can run on all platforms which supports java.
• Simple: Java has made life easier by removing all the complexities such
as pointers, operator overloading as you see in C++ or any other
programming language.

• Portable: Java is platform independent which means that any application


Features of written on one platform can be easily ported to another platform.

Java • Object-oriented: Everything is considered to be an “object” which


possess some state, behavior and all the operations are performed using
these objects. 

• Secured: All the code is converted in bytecode after compilation, which


is not readable by a human. and java does not use an explicit pointer and
run the programs inside the sandbox to prevent any activities from
untrusted sources. It enables to develop virus-free, tamper-free
systems/applications.
• Dynamic: It has the ability to adapt to an evolving
environment which supports dynamic memory allocation
due to which memory wastage is reduced and
performance of the application is increased.
• Distributed: Java provides a feature which helps to
Features of create distributed applications. Using Remote Method
Invocation (RMI), a program can invoke a method of
Java another program across a network and get the output. You
can access files by calling the methods from any machine
on the internet.
• Robust: Java has a strong memory management system.
It helps in eliminating error as it checks the code
during compile and runtime.
• High Performance: Java achieves high
performance through the use of bytecode
which can be easily translated into native
machine code. With the use of JIT (Just-In-
Time) compilers, Java enables high
performance. 
Features of • Interpreted: Java is compiled to bytecodes,
Java which are interpreted by a Java run-time
environment. 
• Multithreaded: Java supports multiple
threads of execution (a.k.a., lightweight
processes), including a set of synchronization
primitives. This makes programming with
threads much easier.
JVM (Java Virtual Machine)
• It is an abstract machine. It is a specification that
provides a run-time environment in which Java
bytecode can be executed. It follows three
notations:

Components • Specification: It is a document that describes the


in Java implementation of the Java virtual machine. It is
provided by Sun and other companies.

• Implementation: It is a program that meets the


requirements of JVM specification.

• Runtime Instance: An instance of JVM is created


whenever you write a java command on the
command prompt and run the class.
• JRE (Java Runtime Environment)
• JRE refers to a runtime environment in
which Java bytecode can be executed. It
implements the JVM (Java Virtual Machine)
Components and provides all the class libraries and other
in Java support files that JVM uses at runtime. So
JRE is a software package that contains what
is required to run a Java program. Basically,
it’s an implementation of the JVM which
physically exists. 
JDK(Java Development Kit)
• It is the tool necessary to:-
• Compile
• Document
Components • Package Java programs.
in Java • The JDK completely includes JRE which
contains tools for Java programmers. The Java
Development Kit is provided free of charge.
Along with JRE, it includes an interpreter/loader,
a compiler (javac), an archiver (jar), a
documentation generator (Javadoc) and other
tools needed in Java development. In short, it
contains JRE + development tools.
Differences between C, C++ and Java

Metrics C C++ Java

Object-Oriented Pure Object Oriented


Programming Paradigm Procedural language
Programming (OOP) Oriented

Origin Based on assembly language Based on C language Based on C and C++

Developer Dennis Ritchie in 1972 Bjarne Stroustrup in 1979 James Gosling in 1991

Interpreted language
Translator Compiler only Compiler only
(Compiler + interpreter)

Platform Dependency Platform Dependent Platform Dependent Platform Independent


Differences between C, C++ and Java

Executed by JVM (Java


Code execution Direct Direct
Virtual Machine)

Approach Top-down approach Bottom-up approach Bottom-up approach

File generation .exe files .exe files .class files

Support header files


Pre-processor directives Supported (#header, #define) Use Packages (import)
(#include, #define)

keywords Support 32 keywords Supports 63 keywords 50 defined keywords


Differences between C, C++ and Java

Datatypes (union,
Supported Supported Not supported
structure)

Supported except Multiple


Inheritance No inheritance Supported
inheritance

Support Function Operator overloading is not


Overloading No overloading
overloading (Polymorphism) supported

Pointers Supported Supported Not supported

Allocation Use malloc, calloc Use new, delete Garbage collector


Differences between C, C++ and Java

Exception Handling Not supported Supported Supported

Templates Not supported Supported Not supported

No constructor neither
Destructors Supported Not supported
destructor

Multithreading/ Interfaces Not supported Not supported Supported

Database connectivity Not supported Not supported Supported

Storage Classes Supported ( auto, extern ) Supported ( auto, extern ) Not supported
• we created a Java file called MyClass.java, and
we used the following code to print "Hello
World" to the screen:

MyClass.java
public class MyClass {
  public static void main(String[]
Java Syntax args) {
    System.out.println("Hello
World");
  }
}

• Every line of code that runs in Java must be
inside a class. In our example, we named
the class MyClass. A class should always
start with an uppercase first letter.
Example • Note: Java is case-sensitive: "MyClass" and
explained "myclass" has different meaning.
• The name of the java file must match the
class name. When saving the file, save it
using the class name and add ".java" to the
end of the filename.
Java Tokens
A smallest individual unit in source code is known as Token

Java Tokens

Keywords Identifiers Literals Operators Seperators


Keywords are special tokens in the language which have reserved use in the language.  Keywords
may not be used as identifiers in Java — you cannot declare a field whose name is a  keyword,
for instance.
Java has 50 keywords among which 48 are in use but 2 (goto and const) are currently not in use 
Here is a list of keywords in the Java programming language. You cannot use any of the  following
as identifiers in your programs. The keywords const and goto are reserved, even  though they
are not currently used. true, false, and null might seem like keywords, but they are  actually
literals; you cannot use them as identifiers in your programs.

* not used abstract continue for new switch


** added in assert*** default goto* package synchronized
1.2 boolean do if private this
*** added in break double implements protected throw
1.4 byte else import public throws
case enum**** instanceof return transient
**** added in
5.0 catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
Identifiers are the names of variables, methods, classes, packages and interfaces.

• Don’t use a keyword


• Don’t use a space
• Don’t use a special symbol other than ( _ and $ )
• Cannot start with digit
• Any length

• If only a single word then use a lowercase


• If more than one word then start first word with lowercase and other words start with first
letter as Capital
For example:
int balance=500; //Single word
int bankBalance=500; //Multiple Words
•Every word start with first letter as Capital
For example:
class Balance{}
class BankBalance{}

•Use lowercase
For example:
package pack1;
package mypack1;

• Use Uppercase and Underscore for separating the words


For example:
int PI=3.14;
int MAX_VALUE=100;
Fixed value assigned to variables or used in expressions is known as Literals

• Integer Literals: for example: 1, -2, 8523, -2105 etc.

Data Type Size Range


byte 1 Byte -27 to 27 -1
short 2 Bytes -215 to 215 -1
int 4 Bytes -231 to 231 -1
long 8 Bytes -263 to 263 -1

• Floating Literals: for example: 1.02, -2.689, 8523.369, 2105 etc.

Data Type Size Range


float 4 Byte -3.4 * 1038 to 3.4 * 1038
double 8 Bytes -1.7 * 10308 to 1.7 * 10308
• Character Literals: for example: ‘A’, ‘B’, ‘@’, ‘&’ etc.

Data Type Size Range


char 2 Bytes All Unicode characters

• String Literals: for example: “Hello”, “Gurpreet Singh”, “ACET” etc.

Data Type Size Range


String 2 * No. of characters As much memory available

• Boolean Literals: true and false.

Data Type Size Range


boolean 1 Byte true or false

• Null Literals: null can be assigned to any reference type


Operators operates on operands. For example: In expression a+b
is operator
, a & b are operands and +
• Arithmetic Operator: +, - , *, /, %. For example:
5+4 will result in 9 5-4 will result in 1 5*4 will result in 20 5/4 will result in 1

5%4 will result in 1 (remainder) -5%4 will result in -1 5%-4 will result in 1 -5%-4 will result in -1

Note: Sign of result in % operator depends on the sign of dividend(numerator)

•Relational Operator: <, >, <=, >=, ==, != Output will be either true or false
5>6 will result in false
5>=6 will result in false (either greater than or equal to)
5<6 will result in true
5<=6 will result in true (either less than or equal to)
5==6 will result in false (equal to)
5!=6 will result in true (not equal to)
•Assignment Operator: = Assign the value on left hand side to right hand side. For example:
A=10+5, will assign 15 to A

• Logical Operator: returns true or false


Logical AND (&&) A B A&&B A||B !A
Logical OR (||) true true true true false
Logical NOT (!) true false false true false
false true false true true
false false false false true

• Increment/Decrement Operator: increases or decreases the value by 1


Pre-increment & Pre-decrement: ++a, --a
Post-increment & Post-decrement: a++, a--
•Bitwise Operator: Performs operations on bits A B A&B A|B A^B !A
Bitwise AND(&) 0 0 0 0 1 1
Bitwise OR(|)
0 1 0 1 0 1
Bitwise XOR(^)
Bitwise Complement or Not (!) 1 0 0 1 0 0
1 1 1 1 1 0

• Shift Operator: shift the bits to left or right


Left Shift(<<): shifts the bits to left and fill the vacant spaces with 0
Unsigned Right Shift(>>>): shifts the bits to right and fill the vacant spaces with 0
Signed Right Shift(>>): shifts the bits to right and fill the vacant spaces with leftmost bit, i.e. if
leftmost bit is 0 then fill with 0, and if the leftmost bit is 1 then fill with 1
• Conditional(Ternary) Operator:
Syntax: condition(relational expression) ? Expression 1 : Expression 2
If condition evaluates to true then result will be Expression 1 otherwise Expression 2
{ } used to define block or to declare array with static elements
[ ] used to declare array variable
( ) used to define/call function or used in expressions
; used to terminate a statement
, used to separate variables in declaration
. used to access data members and member functions of an object or
class
Java Basics
Structure of a Java Class

public class MyClass


{

}
Structure of a Java Class

public class MyClass


{

}
Structure of a Java Class

public class MyClass


{

}
Structure of a Java Class

public class MyClass


{
public void myMethod()
{

}
}
Structure of a Java Class

public class MyClass


{
public void myMethod()
{

}
}
Structure of a Java Class

public class MyClass


{
public void myMethod()
{

}
}
Structure of a Java Class

public class MyClass


{
public void myMethod()
{

}
}
Structure of a Java Class

public class MyClass


{
public void act()
{
move(5);
if( atWorldEdge() ) {
turn(12);
}
}
}
Structure of a Java Method Call

move(5);
Structure of a Java Method Call

atWorldEdge()
Structure of a Java Method Call

if( atWorldEdge() )
Structure of an If-Structure

if( condition ) {

true branch

}
Structure of an If-Structure

if( condition ) {

true branch

}
Structure of an If-Structure

if( condition ) {

true branch

} else {

false branch

}
    JAVA PROGRAMMING  

Introduction to JAVA
Contents
• What is JAVA?
• What is OOP?
• Why Java?
• Characteristics of JAVA
• Overview of Java.
• The difference between Java and C++?
• A Simple JAVA Program
What is JAVA?
• Developed by Sun Microsystems (James
Gosling)
• A general-purpose Object-Oriented language
• Based on C/C++
• Designed for easy Web/Internet applications
• Widespread acceptance
What is Object Oriented Programming?
Object-oriented programming is a method of implementation in
which programs are organized as cooperative collections of
objects, each of which represents an instance of some class, and
whose classes are all members of one or more hierarchy of classes
united via inheritance relationships.
Principles of OOP
•All object-oriented programming languages provide
mechanisms that help you implement the object-
oriented model.

• They are:
• Encapsulation
• Inheritance
• Polymorphism
Data Encapsulation
Encapsulation is the mechanism that binds together code and the
data it manipulates, and keeps both safe from outside interference
and misuse.

class Account {
int x=10;
float withdraw();
void deposit(float amount); float
balance;
}
Advantages of Encapsulation
• Protection
• Consistency
• Allows change
Inheritance
•Inheritance is the process by which one object acquires the
properties of another object.

•A class that is derived from another class is called a subclass


(also a derived class, extended class, or child class).

•The class from which the subclass is derived is called a super


class (also a base class or a parent class).

•A class which is a subtype of a more general class is said to


be inherited from it.
Inheritance cont’d
•The sub-class inherits the base class’ data members and
member functions.

•A sub-class has all data members of its base-class plus its


own.

•A sub-class has all member functions of its base class (with


changes) plus its own.
Polymorphism
•Polymorphism refers to a programming language's ability to
process objects differently depending on their data type or
class.
• Generally, the ability to appear in many forms.

• More specifically, it is the ability to redefine methods for


derived classes.

•For example, given a base class shape, polymorphism


enables the programmer to define different area methods for
any number of derived classes, such as circles, rectangles
and triangles. No matter what shape an object is, applying
the area method to it will return the correct results.
Why Java?

Java is the Internet programming language.

Java enables users to develop and deploy


applications on the Internet for servers, desktop
computers, and small hand-held devices.

11
Java, Web, and Beyond
• Java Applets

• Java Web Applications

•Java can also be used to develop applications for


hand-held devices such as Palm and cell phones

12
Characteristics 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 Performance
•Java Is Multithreaded
•Java Is Dynamic

13
Java Disadvantages

• Slower than compiled language such as C

• an experiment in 1999 showed that Java was 3 or


4 times slower than C or C++
James Gosling
•James Gosling is generally
credited as the inventor of the
Java programming language

•He was the first designer of Java


and implemented its original
compiler and virtual machine

•He is also known as the Father of


Java.
Brief History of Java
• In 1990, Sun Microsystems began an internal project known as the
Green Project to work on a new technology.

•In 1992, the Green Project was spun off and its interest directed
toward building highly interactive devices for the cable TV industry.
This failed to materialize.

•In 1994, the focus of the original team was re-targeted, this time to
the use of Internet technology. A small web browser called HotJava
was written.
•Oak was renamed to Java after learning that Oak had already been
trademarked.
A Simple Java Program

//This program prints Welcome to Java!


public class Welcome
{
public static void main(String[]
args)
{
System.out.println("Welco
me to Java!");
}
}

39
Compiling Java Source Code
Java was designed to run object programs on any
platform.
With Java, you write the program once, and compile the
source program into a special type of object code, known as
bytecode.

The byte-code can then run on any computer with a Java Virtual
Machine, as shown below.
Java Bytecode
Java Virtual Machine is a software Java Virtual
Machine
that interprets Java byte-code.
Any
Computer

40

You might also like