SlideShare a Scribd company logo
24BKCC201 – Java
Programming
UNIT - 1
Java Introduction: Principles of Object oriented language - Java
Essentials - Java Virtual Machine - Java Features - Program Structure -
Java Improvements - Difference between Java and C++ - Installation of
JDK 1.7 - Integrated Development Environment - Java Programming
constructs: Variables - Primitive Data Types – Identifier – Literals –
Operators – Expressions - Precedence Rules and Associativity -
Primitive type conversion and casting - Flow of Control.
Java
• Java is a popular and powerful language
• Java is an pure object oriented programming language with a built – in
API (Application Programming Interface) that can handle GUI
(Graphical User Interface).
• GUI is used to create applications or applets
• Java Provides rich set of APIs apart from being platform independent.
• Java Syntax is similar to C and C++
• Major difference between java and other languages is that it does not
have pointers
History of Java
• Java was developed specifically for the world wide web
• Java as it was initially developed was intended for the web
• Java was improved to be a standard programming language for internet applications
• Bill Joy – Vice President at Sun Microsystems – Main person to conceive the idea
of a programming Language that later became java
• 1970 – Bill Joy wanted to design a language that contains best features of languages
like MESA and C
• Bill Joy found that C++ programming was inefficient for rewriting Unix Operating
System.
• In 1991 – it was this desire to invent a better programming language that made joy
in the direction of Suns’ Mammoth project called stealth project
History of Java
• In 1991, January Formal team of persons bill joy, James Gosling,
Mike Sheradin, Patrick Naughton planned to meet for Stealth Project.
• Stealth project is about developing consumer electronic devices
that could all be controlled by hand held remote controls
• James Gosling was made responsible for suggesting a proper
programming language for a project
• Initially james through of C++, due to inadequacy it is not suggested
• James Gosling took first step towards the development of an
independent language by extending and modifying c++.
History of Java
• The Name OAK was suggested initially staring at an oak tree outside
his office window.
• Name has been already patented by other programming language
• Due to copy right violation – OAK was Dropped
• After few days and so many brain storming sessions ,during a trip to
local coffee shop named as Java
• In USA Java is a slang represents coffee.
• Coffee produced on the islands of java in Indonesia
Principles of Object oriented language
• Object Oriented Programming Language follow certain principles
such as
• Class
• Object
• Abstraction
• Inheritance
• Encapsulation
• Polymorphism
Class
• Class is defined as the blueprint for an object
• Class serves as a plan or a template.
• Class is a collection of objects of similar type
• The description of a number of similar objects is also called as a class
• An object is not created by just defining a class. It has to be created explicitly
• Classes are logical in nature
• Example1: furniture does not have any existence but tables and chairs do exist
• Example2: Fruit Mango*
• A class is also defined as a new data type, a user defined type which contains two things
• Data members
• Methods
Objects
• Objects are defined as the instances of a class
• Objects are the basic run time entities
• Example: table, chair are all instances of the class furniture
• Objects of a class will have same attributes and behavior which are defined in that class.
• The only difference is value of attributes of an object may vary.
• Objects may be physical, conceptual or software.
• Objects have unique identity, state and behavior
• There are several types of objects
• Creator objects: Humans, Employees, Students, Animals
• Physical Objects: Car, bus, plane
• Objects in computer system: Monitor, Keyboard, Mouse, CPU, Memory
Abstraction
• Can you classify the following items
• Elephant
• Television
• Table
• CD Player
• Chair
• Tiger
• How many classes do you identify here?
Abstraction
• Grouping similar items like elephant and tiger and focused on the
generic characteristics rather than specific characteristics
• This is called abstraction
• “Act of Representing only the essential features without including
the background details called data abstraction”
• Everything in this world can be classified as living and non living
things, which is the highest level of abstraction
Abstraction
• Well Known another analogy for abstraction is a car
• We drive car without knowing the internal details about how
engine works and how the car stops on applying brakes.
• We are happy with the abstraction provided to us EX: Brakes,
steering etc.. And we interact with them.
• In Programming , we manage complexity by concentrating only on
the essential characteristics and suppressing implementation details.
Inheritance
• Inheritance is the way to adopt the characteristics of one class into another
class.
• There are 2 types of classes
• Base class
• Sub class
• There exist a parent-child relationship among the classes
• When a class inherits another class it has all the properties of the base class
and it adds some new properties of its own.
• We can categorize vehicles into car, bus. Scooter, ships, planes etc
• The class of animals are divided into mammals, amphibians, birds and so on
Inheritance
• The principle of dividing a class into subclasses is that each subclasses
share common characteristics with the class from where they are
inherited or derived.
• Car, Scooters, Planes and ships all have an engine and speedometer.
• Each subclass has its own characteristic feature
• Eg: Motorcycles have disk braking system, while planes have hydraulic
braking system
• A car can run only on the surface, while a plane can fly in air and a ship
sails over water
Inheritance
Vehicle
Water Vehicle
Air Vehicle
Road Vehicle
Bus Motor Vehicle Aeroplane Boat
Inheritance
• Inheritance aids in reusability
• When we create a class, it can be distributed to other programmers
which they can use in their programs. This is called reusability.
• If some one wants to program for a calculator, he can use predefined
class for arithmetic operations. This is similar to using library functions
in procedural language.. He can derive a child class from a parent class.
• A Programmer can use a base class with or without modifying. He can
derive a child class from a parent class and then add some additional
features to his class.
Method 1
Method 2
Method 3
Encapsulation
• Encapsulation is one of the feature of object oriented methodology
• Process of binding the data procedures into objects to hide them from
the outside world is called encapsulation
Data
Accessing Data
Encapsulation
• Encapsulation provides power to restrict anyone from directly
altering the data.
• Encapsulation is also called as data hiding
• The data is hidden from outside world and as a result it is protected.
• The details that are not useful for other objects should be hidden
from them. This is called encapsulation
Polymorphism
• Polymorphism means many forms
• Same thing used in different forms
• Two types:
• Run time Polymorphism
• Compile Time Polymorphism
• Run time Polymorphism: It is also known as dynamic binding or late binding –
used to determine which method to invoke at run time.
• Binding of method call to its method is done at run time and hence the term late binding
• Compile Time Polymorphism: compiler decides which method will be executed
• The binding of method call to the method is done at compile time.
• Decision is made early, so it is called early binding
Polymorphism
• Compile time polymorphism in java is implemented by overloading
and run time polymorphism by overriding.
• Overloading: Method has same name and different arguments
• void getdata(int a, int b)
• void getdata(int a, int b, int c)
• Overriding: Method is defined in subclass with same name and
same arguments as that or parent class.
• Parent class: void getdata(int a, int b)
• Child class: void getdata(int a, int b)
Polymorphism
• Compile time polymorphism is also implemented by operator
overloading which is available in C++ but not in java.
• Operator overloading: Same operator used for different purposes.
• Ex: + can be used for addition also for adding two strings
Java Essentials
• Java is a platform independent, object oriented programming language
• Java encompass the following features:
• A High Level Language: Java is a high level language – Looks similar to c and
C++ but offers many unique features.
• Java Bytecode: Byte code in java is an intermediate code generated by
the compiler, that is executed by the JVM
• Java Virtual Machine(JVM): JVM acts as an interpreter for bytecode,
which takes byte code as an input and executes it
• Java is designed to be architecturally neutral so that it can run on
multiple platforms.
Java Essentials
• To achieve cross architectural capabilities, java compiler generates
architecturally neutral byte code instructions.
• Java code can be easily interpreted on any machine and easily
translated into native machine code on the fly.
• JRE includes JVM, class libraries and other supporting files
• JRE = JVM + Core Java API Libraries
• JDK = JRE + Development Tools like compilers
• JDK comes with many versions
• A run time bundle is also provided as a part of JDK
Java Programming - UNIT - 1, Basics OOPS, Differences
Java Essentials
• Tools such as javac (Compiler) and java (interpreter) and other following tools
Java Virtual Machine - JVM
• Heart of java is JVM
• Programming languages compiles the source code directly into machine code,
suitable for microprocessor architecture
• The difference with java is that it uses bytecode, an intermediate code
• Java bytecode executes on a virtual machine.
• Actually there wasn’t hardware implementation of this microprocessor available
when java was first released. Instead the processor architecture is emulated by
software known as the virtual machine.
• The virtual machine is an emulation of a real java processor. – a machine
within a machine
• The virtual machine runs on the top of the operating system
Java Programming - UNIT - 1, Basics OOPS, Differences
Java Programming - UNIT - 1, Basics OOPS, Differences
Program Structure
• Java application consists of a collection of classes.
• A class is a template.
• An object is defined as an instance of the class
• Each instance(Objects) contains the members specified in the class.
• Field is one that holds a value
• Method defines operations on the fields and values that are passes as
arguments to the method.
First Java Program
Class example /* example.java */
{
public static void main(String args[])
{
System.out.println(“Sample Program”);
}
}
Program Structure
• public – it is an access specifier used to specify that the code can be
called from anywhere. Main is declared as public
• static – It is declared static because it allows main() to be called
without having to instantiate the class. JVM Need not create an
instance of the class(i.e object of the class) for calling main method
• Void – It does not return a value. The keyword void simply tells the
compiler that main() does not return anything back to the caller (i.e
JVM)
• String args[] – it holds optional command line arguments passed to
the class through the java command line.
Versions of java
• 1995 version 1.0:
– The Java development kit was released for free by the sun
– 8-Packages 212-Classes
– Microsoft and other companies licensed Java
• 1997 version 1.1:
– 23-Packages 504-Classes
– Improvement include better event handling inner classes ,
improved JVM.
– Microsoft developed its own 1.1 compatible Java Virtual
Machine for Internet Explorer
– Many browsers in use are still compatible only with 1.1
Versions of java…
1999 version 1.2:
-It is also called as the Java 2 platform
-59 Packages -1520 Classes
-Code & tools distributed as the SDK
-A Java foundation class based on swings for
improved graphics and user interfaces
-Collection API included list sets and hash map
Versions of java…
. 2000 VERSION 1.3:
- 76 Packages - 1842 Classes
- Java Sound (API for Digital & MIDI Sound)
•2002 VERSION 1.4:
- 135 Packages - 2991 Classes
- Improved XML support etc..,
•2004 VERSION 5.0 (1.5):
- 165 Packages - over 3000 Classes
- Faster startup metadata formatted Output
- Generic to operate on objects of various types
Versions of java…
2006 Java SE 6:
– Scripting language support
2011 Java SE 7:
– JVM Support for dynamic language
– String in switch
– Allowing underscores in numeric literals
2014 Java SE 8:
– for Each() method in Iterable interface.
- default and static methods in Interfaces.
- Functional Interfaces and Lambda Expressions.
Versions of java…
2017 Java SE 9:
-Stream API Improvements
-Multi-Resolution Image API
FUTURE EXPECTED UPDATES:
– Application Data-Class Sharing: ...
– Garbage Collector Interface
Java and C
Java is a lot like C but the major difference between Java and C is that Java is
an object-oriented language and mechanism to define classes and objects.
Java does not include the C unique statement keywords goto, sizeof, and
typedef.
Java does not contain the data types struct, union and enum.
Java does not define the type modifiers keywords auto, extern, register,
signed and unsigned.
 Java does not support an explicit pointer type.
Java does not have a preprocessor and therefore we cannot use # define,
#include, and # ifdef statements.
Java does not support any mechanism for defining variable arguments to
functions.
Java requires that the functions with no arguments must be declared with
empty parenthesis and not with the void keyword as done in C.
 Java add new operators such as instanceof and >>>.
 Java adds labelled break and continue statements.
 Java adds many features required for object-oriented programming.
Java and C++
Java is a true object-oriented language while C++ is basically C with object-oriented
extension.
Listed below are some major c++ features that were intentionally committed from
Java or significantly modified.
Java does not support operator overloading.
Java does not have temple classes as in C++.
Java does not support multiple inheritence of classes. This is accomplished using a
new feature called "interface".
Java does not support global variables. Every variable and method is declared within a
class and forms parts of that class.
Java does not use pointers.
Java has replaced the destructors function with a finalize() function.
There are no header files in Java.
Java compared to C++
Toolkits and platforms
 Below Figure describes all major releases of Java to date starting with version 1.0 and
ending with version 1.4.
Applications, applets, and servlets
 First, you can use Java to create applications. This figure shows an application that uses a graphical user
interface, or GUI, to get user input and perform a calculation. Application is a program that run in window.
 Applet is a special type of program that runs within web browser after it has been retrieved from
internet or intranet. One of the unique characteristics of Java is that you can use it to create a special type
of web-based application known as an applet. For instance, this figure shows an applet that works the
same way as the application above it. The main difference between an application and an applet is that an
applet can be stored in an HTML page and can run inside a Java-enabled browser. As a result, you can
distribute applets via the Internet or an intranet.
 The Enterprise Edition of the Java 2 Platform can be used to create a special type of server-side
application known as a servlet. Servlets can access enterprise databases and make that data available via
the web.
Java and Internet
Java is strongly associated with the internet because of the fact that the
first application program written in java was HotJava, a Web browser to
run applets on Internet.
Internet users can use Java to create applet programs and run them
locally using a "Java-enabled browser" such as HotJava.
Internet users can also set up their Web sites containing Java applets that
could be used by Superhighway has made Java a unique programming
language for the Internet.
In fact, due to this, Java is popularly known as internet language.
Java and World Wide Web
World Wide Web (WWW) is an open-ended information retrieval system designed to be used in
the Internet’s distributed environment. This system contains what are known as Web page that
provide both information and controls.
Unlike a menu driven system where we are guided through a particular direction using a
decision tree structure, the Web system is open-ended and we can navigate to a new
documents in any direction as shown in fig. 2.3. This is made possible with the help of a language
called Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find,
retrieve, manipulate and display documents worldwide.
Java was meant to be used in distributed environments such as Internet. Since, both the web and
Java share the same philosophy, Java could be easily incorporated into the Web and systems.
Before Java , the World Wide Web Was limited to the display of still images and texts. However,
the incorporation of Java into Web pages has made it capable of supporting animation, graphics,
games and a wide a range of special effects. With the support of Java, the web has become more
interactive and dynamic. On the other hand, with the support of Web, we can run a Java program
on someone else’s computer across the Internet.
Java communicates with a Web page through a special tag called <APPLET>.
Java Programming - UNIT - 1, Basics OOPS, Differences
The figure shows the following communications steps:
1. The user sends a request for an HTML document to the remote computer’s Web server. The Web
server is a program that accepts a request, processes the request, and sends the required documents.
2. The HTML document is returned to the user’s browser. The document contains the APPLET tag,
which identifies the applet.
3. The corresponding applet bytecode is transferred to the user’s computer. This bytecode had been
previously created by the Java compiler using the Java source code file for that applet.
4. The Java-enabled browser on the user’s computer interprets the bytecodes and provides output.
5. The user may have further interaction with the applet but with no further downloading from the
provider’s Web server. This is because the bytecode contains all the information necessary to
interpret the applet.
Web Browsers
They allow us to retrieve the information spread
across the Internet and display it using the
hypertext markup language (HTML). Example of
Web browser, among others, include:
• HotJava
• Netscape Navigator
• Internet Explorer
HotJava
 HotJava is the Web browser from Sun Microsystems that enables the display of
interactive content on the Web, using the Java language. HotJava is writing
entirely in Java and demonstrates the capabilities of the Java programming
language.
 When the Java language was first developed and ported to the Internet, no
browsers were available that could run Java applets.
 Although we can view a Web page that includes Java applets with a regular
browser, we will not gain any of Java’s benefits. HotJava is currently available for
SPARC/Solaris platform as well windows 95 and Window NT. Its biggest draw is
that was the biggest Web browser to provide support for the Java language,
 thus making the Web more dynamic and interactive.
•Netscape Navigator
• Netscape Navigator, from Netscape Communications Corporation, is
a general-purpose browser that can run Java applets.
• With versions available for Windows 95, NT, Solaris and Apple
Macintosh, Netscape navigator is one of the most widely used
browsers today.
• Netscape Navigator has many useful features such as visual display
about downloading process and indication of the number bytes
downloaded. It also supports JavaScripts, a scripting language used
in HTML documents.
•Internet Explorer
• Internet Explorer is another popular browser developed Microsoft for
Window 95 and NT Workstations.
• Both the Navigator and Explorer use tool bars, icons, menus and
dialog boxes for easy navigation.
• Explorer uses a just-in-time (JIT) compiler which greatly increases the
speed of execution.
Java Support Systems
Table 2.2 list the systems necessary to support
Java for delivering information on the Internet.
Java Environment
Java environment includes a large number of development tools and
hundreds of classes and methods.
The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are parts of the
Java Standard Library (JSL), also known as the Application
Programming Interface (API).
Java Developing Kit
• The Java Developing Kit comes with a collection of
tools that are used for developing and running Java
programs. They includes:
table 2.3 list these tools and their descriptions.
 The way these tools are applied to build and run application programs
is illustrated in fig .2.1.
 To create a Java program, we need to create a source code file using a
text editor.
 The source code is then compiled using the Java compiler Javac and
executed using the Java interpreter Java.
 The Java debugger jdk is used to find errors, if any, in the source code.
 A compiled Java program can be converted into a source code with
the help of Java disassembler Javap.
Application Programming Interface
 The Java Standard Library (or API) includes hundreds of classes and
methods grouped into several functional packages. Most
commonly used packages are:
 • Language Support Package: A collection of classes and methods
required for implementing basic features of Java.
 • Utilities Packages: A collection of classes to provide utility
functions such as date and time functions.
 • Input/Out Package: A collection of classes required for input/
output manipulation.
 • Networking Package: A collection of classes for communicating
with other computers via Internet.
 • AWT Package: The Abstract Window Tools Kit packages contains
classes that implements platform-independent graphical user
interface.
 • Applet Package: This includes a set of classes that allows us to
create Java applets.
Advantages of Using Java
Java technology will help you do the following:
Get started quickly: Although the Java programming language is a powerful object-oriented
language, it's easy to learn, especially for programmers already familiar with C or C++.
 Write less code: program written in the Java programming language can be four times smaller than
the same program in C++.
Write better code: The Java programming language encourages good coding practices, and its
garbage collection helps you avoid memory leaks. Its object orientation, its Java Beans component
architecture, and its wide-ranging, easily extendible API let you reuse other people's tested code and
introduce fewer bugs.
Develop programs more quickly: Your development time may be as much as twice as fast versus
writing the same program in C++.
Avoid platform dependencies with 100% Pure Java: You can keep your program portable by avoiding
the use of libraries written in other languages.
Write once, run anywhere: Because 100% Pure Java programs are compiled into machine-
independent byte codes, they run consistently on any Java platform.
How Java compiles and interprets code:
Description
 Any text editor can save and edit the source code for a Java application. Source code files use the java
extension.
 The Java compiler translates source code into a platform-independent format known as Java bytecodes. Files
that contain Java bytecodes use the class extension.
 The Java interpreter executes Java bytecodes. Since Java interpreters exist for all major operating systems, Java
bytecodes can be run on most platforms.
 Any computer with a Java interpreter can be considered an implementation of a Java virtual machine (JVM).
 Some web browsers like Netscape and the Internet Explorer contain Java interpreters. This lets applets run
within these browsers. However, both Netscape and the Internet Explorer only provide older versions of the
Java interpreter.
 Sun provides a tool known as the Java plug-in that allows the Netscape and Internet Explorer browsers to use
the most current version of the Java virtual machine.
INSTALLATIONOF JDK 1.6
A summary of the directories and files of the JDK:
Java Programming - UNIT - 1, Basics OOPS, Differences
Some Important Term
 JRE(Java Runtime Environment):
 The JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the
Java technology packages, which includes basic language classes, GUI component classes, and so on.
 runs code compiled for a JVM and performs class loading (through the class loader), code verification (through the
bytecodeverifier) and finally code execution.
 The jre directory contains the Java interpreter, or Java Runtime nvironment (JRE), that’s needed to run Java
applications once they’ve been compiled.
• Java virtual machine (JVM):
• Any machine that has a Java interpreter installed
on it can be considered an implementation of a
Java virtual machine (JVM).
Class Loader:
 responsible for loading all classes needed for the Java program.
Bytecodeverifier:
 tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights
to objects.
Garbage collection thread:
 responsible for freeing any memory that can be freed. This happens automatically during the lifetime of the Java
program.
 programmer is freed from the burden of having to deallocatethat memory themselves.
How Code Security Is Maintained In Java?
 Ans:Code Security Is maintained By Following Term.
(1)JRE
(2)Class Loader
(3)Bitecodeverifier
JAVAPROGRAMSTRUCTURE:
• As all other programming languages, Java also has a structure.
• The first line of the C/C++ program contains include statement. For example, <stdio.h> is the header file that contains
functions, like printf (), scanf () etc. So if we want to use any of these functions, we should include this header file in C/ C+
+ program.
• Similarly in Java first we need to import the required packages. By default java.lang.* is imported. Java has several such
packages in its library. A package is a kind of directory that contains a group of related classes and interfaces. A class or
interface contains methods.
• Since Java is purely an Object Oriented Programming language, we cannot write a Java program without having at least one
class or object. So, it is mandatory to write a class in Java program. We should use class keyword for this purpose and then
write class name.
• In C/C++, program starts executing from main method similarly in Java, program starts executing from main method. The
return type of main method is void because program starts executing from main method and it returns nothing.
 Since Java is purely an Object Oriented Programming language, without
creating an object to a class it is not possible to access methods and
members of a class. But main method is also a method inside a class,
since program execution starts from main method we need to call main
method without creating an object.
 Static methods are the methods, which can be called and executed
without creating objects.
 Since we want to call main () method without using an object, we should
declare main ()method as static.
 JVM calls main () method using its Classname.main () at the time of
running the program.
 JVM is a program written by Java Soft people (Java development team)
and main () is the method written by us. Since, main () method should
be available to the JVM, it should be declared as public. If we don’t
declare main () method as public, then it doesn’t make itself available to
JVM and JVM cannot execute it.
 JVM always looks for main () method with String type array as parameter
otherwise JVM cannot recognize the main () method, so we must
provide String type array as parameter to main () method.
 A class code starts with a {and ends with a}. A class or an object contains variables
and methods (functions). We can create any number of variables and methods inside
the class. This is our first program, so we had written only one method called main ().
 Our aim of writing this program is just to display a string “Hello world”. In Java, print ()
method is used to display something on the monitor.
 A method should be called by using objectname.methodname (). So, to call print ()
method, create an object to PrintStream class then call objectname.print () method.
 An alternative is given to create an object to PrintStream Class i.e. System.out. Here,
System is the class name and out is a static variable in System class. out is called a
field in System class. When we call this field a PrintStream class object will be created
internally. So, we can call print() method as: System.out.print (“Hello world”);
 println () is also a method belonging to PrintStream class. It throws the cursor to the
next line after displaying the result.
 In the above Sample program System and String are the classes present in java.lang
package.
Comments
 Comments are description about the aim and features of the program.
 Comments increase readability of a program.
 Three types of comments are there in Java:
 · Single line comments: These comments start with //
e.g.: // this is comment line
 · Multi line comments: These comments start with /* and end with */
e.g.: /* this is comment line*/
 · Java documentation comments: These comments start with /** and
end with */
These comments are useful to create a HTML file called API
(application programming Interface) document. This file contains
description of all the features of software.
Java documentation comments(Example)
 Example 3-1: FirstSample.java
/* This is my the first program in Java
I am enjoying Java.
*/
public class FirstSample
{
public static void main (String [] args)
{
System.out.println("Welcome to the world of Java");
}
}
Escape Sequence
• Java supports all escape sequence which is supported by C/ C++.
• A character preceded by a backslash () is an escape sequence and has
special meaning to the compiler. When an escape sequence is
encountered in a print statement, the compiler interprets it accordingly.
How to create identifiers
• As you code a Java program, you need to create
and use identifiers.
keyword
• A keyword is a word that’s reserved by the Java
language. As a result, you can’t use keywords as
identifiers.
IDE – Integrated Development Environment
• Eclipse
• DrJava
• Jcreator
• NetBeans
Java Programming constructs
• Variables:
• Variable is a symbolic name refers to a memory location used to
store values that can change during the execution of the program
• int watts = 100;
Primitive Data Types
• Primitive data types are the basic building blocks of any programming
language.
• There are eight primitive data types in java
• byte
• Short
• Int
• long
• float
• double
• char
• boolean
Primitive Data Types
• Byte – It is a 1 byte (8 bit) ranges from -128 to 127
• Short – It is 2 byte (16 bit) ranges from -32768 to 32767
• Int – It is a 4 byte (32 bit) ranges from -2,147,483,648 to +2,147,483,647
• Long – It is an 8 – byte (64 bit) ranges from -9223372036854775808 to -
9223372036854775807
• Float – it is a single precision ( 32 bit – floating point) ranges from
1.401298464324817e-45f to 3.402823476638528860e+38f
• Double – this is double precision 64 bit floating point ranges from
4.94065645841246544e-324 to 1.79769313486231570e(+) 308
• Char – single 16bit Unicode character, It ranges from ‘ u000’ to ufff’
• Boolean – true or false
Literals
• A literal is a value that can be passed to a variable or constant in a program
• Literals can be numeric , boolean, character, string notations or null
literals.
• Numeric Literals: It can be represented in binary, decimal, octal or hexa
decimal notations.
• Binary Literals: There are combination of 0’s and 1’s. Binary Literals can be
assigned to variables in java.
• Binary Literals must be prefixed with 0b or 0B
• Char bin1 = 0b101000 // value in bin 1 will be P
• Char bin2 = 0b101001 // value in bin 2 will be Q
Numeric Literal
• Octal Literals: Value must be prefixed with a zero and only digit
from 0 to 7 are allowed.
• Ex: int x =011; // value in x is 9
• Char y=0150;// value in y will be h
• Hexa Decimal: It is prefixed with 0x or 0X the digit from 0 through 9
and a through f
• Ex: int y=0x0001 // value in y is 1
char x = 0x45 // value in x will be E
Literals
• Integer Literals: All integer literals are of type int
• If long int
• Ex: long l = 2345678L;
• Floating Literals: These are double type by default.
• We need to attach suffix of F or f
• Ex: float f =23.6F;
• Char Literals: A single character is enclosed in single quotes.
• You can also use the prefix u;
• Char c = ‘a’
Literals
• Boolean literals: it is specified as either true or false. By default it
takes the value false’
• Boolean first=true;
• String Literals: It consists of zero or more characters within double
quotes
String s = “This is a string Literal”;
• Null Literals: It is assigned to object reference variables
S= null;
Operators
• An Operator performs an action on one or more operands
• An operator that performs an action on one operand is called unary Operators
• An operator that performs an action on two operands is called a binary operator
• Java Provides
• Arithmetic
• Relational
• Logical
• Assignment ( = )
• Shift
• Conditional
• Bitwise
• Member Access Operator
Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Java Programming - UNIT - 1, Basics OOPS, Differences
Shift Operator
• Signed Left Shift Operator (<<)
• Signed Right Shift Operator (>>)
• Unsigned Right Shift Operator (>>>)
• Binary equivalent of 5 is 0101.
• Assume that the statement is as follows:
• x<<4, let y be 4
Java Programming - UNIT - 1, Basics OOPS, Differences
Unary Operators
Increment and Decrement Operators:
(--X, ++X) – Prefix
(X--, X++) – Postfix
Answer: 232
#include <stdio.h>
int main()
{
int x=2;
int y=++x;
int z= --x;
}
Ternary Operator or Conditional Operator
• String greater = x< y ? “y is greater”: “x is greater”;
Expressions
• Expression is a combination of operators and /or operands
• Java Expressions are used to create objects, arrays, pass values to
methods and call them, assigning values to variables.
• Int m=2, n=3, o=4;
• Int y= m * n * o;
Java Programming - UNIT - 1, Basics OOPS, Differences
Primitive Type Conversion and Casting
In java Type conversions are performed automatically, when the type of
the expression on the right hand side of an assignment operation can be
safely promoted to the type of the variable on the left hand side of the
assignment
char
Byte-> short-> int -> long->float->double
Conversions that are implicit in nature are termed as widening
conversions
Primitive Type Conversion
• byte b =20;
• Int i=b;
• Type conversion or promotion also takes place while evaluating the
expressions involving arithmetic operators
• int i =10; int variable
• double d = 20; int literal assigned to a double variable
• D = i + d; automatic conversion into double
Primitive Type Conversions
• short z = b*s; invalid
• int i=b*s; valid
• float f=3; legal
• float f=3.0 illegal
• float f = 3.0f legal
Casting
• Casting is also known as narrowing of conversions (reverse of
widening conversion)
• Byte <- short <- int<-long-<float-<double Narrowing
Conversion
• If you want to assign bigger values to smaller, for such situations
called Casting can be done.
• Casting is not implicit in nature
int i = (int) (8.0 / 3.0);
Flow of Control
• Control flow statements help programmers make decisions about which
statement to execute and to change the flow of execution in a program.
• The four categories of control flow statements available in java are
conditional statements, loops, exception and branch
1. Conditional Statements (if else if switch)
2. Loops (for while do-while)
3. Branching Mechanism (break, label, continue)
4. Exception

More Related Content

Similar to Java Programming - UNIT - 1, Basics OOPS, Differences (20)

Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentals
AnsgarMary
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Soumya Suman
 
object oriented programming unit one ppt
object oriented programming unit one pptobject oriented programming unit one ppt
object oriented programming unit one ppt
isiagnel2
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
Hemlathadhevi Annadhurai
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
CPP19 - Revision
CPP19 - RevisionCPP19 - Revision
CPP19 - Revision
Michael Heron
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
Sujit Majety
 
C++ in object oriented programming
C++ in object oriented programmingC++ in object oriented programming
C++ in object oriented programming
Saket Khopkar
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
Fraz Bakhsh
 
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.pptJava Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
akashsachu221
 
The Developers World
The Developers WorldThe Developers World
The Developers World
Ronald Northrip
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
shashi shekhar
 
introduction to object orinted programming through java
introduction to object orinted programming through javaintroduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
java full 1 (Recovered).docx
java full 1 (Recovered).docxjava full 1 (Recovered).docx
java full 1 (Recovered).docx
SATHYAKALAKSKPRCASBS
 
Letest
LetestLetest
Letest
Prakash Poudel
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
Prakash Poudel
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 
java completed units.docx
java completed units.docxjava completed units.docx
java completed units.docx
SATHYAKALAKSKPRCASBS
 
java full 1.docx
java full 1.docxjava full 1.docx
java full 1.docx
SATHYAKALAKSKPRCASBS
 
java full.docx
java full.docxjava full.docx
java full.docx
SATHYAKALAKSKPRCASBS
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentals
AnsgarMary
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Soumya Suman
 
object oriented programming unit one ppt
object oriented programming unit one pptobject oriented programming unit one ppt
object oriented programming unit one ppt
isiagnel2
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
Hemlathadhevi Annadhurai
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
Sujit Majety
 
C++ in object oriented programming
C++ in object oriented programmingC++ in object oriented programming
C++ in object oriented programming
Saket Khopkar
 
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.pptJava Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
akashsachu221
 
introduction to object orinted programming through java
introduction to object orinted programming through javaintroduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
Prakash Poudel
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 

Recently uploaded (20)

Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Ad

Java Programming - UNIT - 1, Basics OOPS, Differences

  • 2. UNIT - 1 Java Introduction: Principles of Object oriented language - Java Essentials - Java Virtual Machine - Java Features - Program Structure - Java Improvements - Difference between Java and C++ - Installation of JDK 1.7 - Integrated Development Environment - Java Programming constructs: Variables - Primitive Data Types – Identifier – Literals – Operators – Expressions - Precedence Rules and Associativity - Primitive type conversion and casting - Flow of Control.
  • 3. Java • Java is a popular and powerful language • Java is an pure object oriented programming language with a built – in API (Application Programming Interface) that can handle GUI (Graphical User Interface). • GUI is used to create applications or applets • Java Provides rich set of APIs apart from being platform independent. • Java Syntax is similar to C and C++ • Major difference between java and other languages is that it does not have pointers
  • 4. History of Java • Java was developed specifically for the world wide web • Java as it was initially developed was intended for the web • Java was improved to be a standard programming language for internet applications • Bill Joy – Vice President at Sun Microsystems – Main person to conceive the idea of a programming Language that later became java • 1970 – Bill Joy wanted to design a language that contains best features of languages like MESA and C • Bill Joy found that C++ programming was inefficient for rewriting Unix Operating System. • In 1991 – it was this desire to invent a better programming language that made joy in the direction of Suns’ Mammoth project called stealth project
  • 5. History of Java • In 1991, January Formal team of persons bill joy, James Gosling, Mike Sheradin, Patrick Naughton planned to meet for Stealth Project. • Stealth project is about developing consumer electronic devices that could all be controlled by hand held remote controls • James Gosling was made responsible for suggesting a proper programming language for a project • Initially james through of C++, due to inadequacy it is not suggested • James Gosling took first step towards the development of an independent language by extending and modifying c++.
  • 6. History of Java • The Name OAK was suggested initially staring at an oak tree outside his office window. • Name has been already patented by other programming language • Due to copy right violation – OAK was Dropped • After few days and so many brain storming sessions ,during a trip to local coffee shop named as Java • In USA Java is a slang represents coffee. • Coffee produced on the islands of java in Indonesia
  • 7. Principles of Object oriented language • Object Oriented Programming Language follow certain principles such as • Class • Object • Abstraction • Inheritance • Encapsulation • Polymorphism
  • 8. Class • Class is defined as the blueprint for an object • Class serves as a plan or a template. • Class is a collection of objects of similar type • The description of a number of similar objects is also called as a class • An object is not created by just defining a class. It has to be created explicitly • Classes are logical in nature • Example1: furniture does not have any existence but tables and chairs do exist • Example2: Fruit Mango* • A class is also defined as a new data type, a user defined type which contains two things • Data members • Methods
  • 9. Objects • Objects are defined as the instances of a class • Objects are the basic run time entities • Example: table, chair are all instances of the class furniture • Objects of a class will have same attributes and behavior which are defined in that class. • The only difference is value of attributes of an object may vary. • Objects may be physical, conceptual or software. • Objects have unique identity, state and behavior • There are several types of objects • Creator objects: Humans, Employees, Students, Animals • Physical Objects: Car, bus, plane • Objects in computer system: Monitor, Keyboard, Mouse, CPU, Memory
  • 10. Abstraction • Can you classify the following items • Elephant • Television • Table • CD Player • Chair • Tiger • How many classes do you identify here?
  • 11. Abstraction • Grouping similar items like elephant and tiger and focused on the generic characteristics rather than specific characteristics • This is called abstraction • “Act of Representing only the essential features without including the background details called data abstraction” • Everything in this world can be classified as living and non living things, which is the highest level of abstraction
  • 12. Abstraction • Well Known another analogy for abstraction is a car • We drive car without knowing the internal details about how engine works and how the car stops on applying brakes. • We are happy with the abstraction provided to us EX: Brakes, steering etc.. And we interact with them. • In Programming , we manage complexity by concentrating only on the essential characteristics and suppressing implementation details.
  • 13. Inheritance • Inheritance is the way to adopt the characteristics of one class into another class. • There are 2 types of classes • Base class • Sub class • There exist a parent-child relationship among the classes • When a class inherits another class it has all the properties of the base class and it adds some new properties of its own. • We can categorize vehicles into car, bus. Scooter, ships, planes etc • The class of animals are divided into mammals, amphibians, birds and so on
  • 14. Inheritance • The principle of dividing a class into subclasses is that each subclasses share common characteristics with the class from where they are inherited or derived. • Car, Scooters, Planes and ships all have an engine and speedometer. • Each subclass has its own characteristic feature • Eg: Motorcycles have disk braking system, while planes have hydraulic braking system • A car can run only on the surface, while a plane can fly in air and a ship sails over water
  • 15. Inheritance Vehicle Water Vehicle Air Vehicle Road Vehicle Bus Motor Vehicle Aeroplane Boat
  • 16. Inheritance • Inheritance aids in reusability • When we create a class, it can be distributed to other programmers which they can use in their programs. This is called reusability. • If some one wants to program for a calculator, he can use predefined class for arithmetic operations. This is similar to using library functions in procedural language.. He can derive a child class from a parent class. • A Programmer can use a base class with or without modifying. He can derive a child class from a parent class and then add some additional features to his class.
  • 17. Method 1 Method 2 Method 3 Encapsulation • Encapsulation is one of the feature of object oriented methodology • Process of binding the data procedures into objects to hide them from the outside world is called encapsulation Data Accessing Data
  • 18. Encapsulation • Encapsulation provides power to restrict anyone from directly altering the data. • Encapsulation is also called as data hiding • The data is hidden from outside world and as a result it is protected. • The details that are not useful for other objects should be hidden from them. This is called encapsulation
  • 19. Polymorphism • Polymorphism means many forms • Same thing used in different forms • Two types: • Run time Polymorphism • Compile Time Polymorphism • Run time Polymorphism: It is also known as dynamic binding or late binding – used to determine which method to invoke at run time. • Binding of method call to its method is done at run time and hence the term late binding • Compile Time Polymorphism: compiler decides which method will be executed • The binding of method call to the method is done at compile time. • Decision is made early, so it is called early binding
  • 20. Polymorphism • Compile time polymorphism in java is implemented by overloading and run time polymorphism by overriding. • Overloading: Method has same name and different arguments • void getdata(int a, int b) • void getdata(int a, int b, int c) • Overriding: Method is defined in subclass with same name and same arguments as that or parent class. • Parent class: void getdata(int a, int b) • Child class: void getdata(int a, int b)
  • 21. Polymorphism • Compile time polymorphism is also implemented by operator overloading which is available in C++ but not in java. • Operator overloading: Same operator used for different purposes. • Ex: + can be used for addition also for adding two strings
  • 22. Java Essentials • Java is a platform independent, object oriented programming language • Java encompass the following features: • A High Level Language: Java is a high level language – Looks similar to c and C++ but offers many unique features. • Java Bytecode: Byte code in java is an intermediate code generated by the compiler, that is executed by the JVM • Java Virtual Machine(JVM): JVM acts as an interpreter for bytecode, which takes byte code as an input and executes it • Java is designed to be architecturally neutral so that it can run on multiple platforms.
  • 23. Java Essentials • To achieve cross architectural capabilities, java compiler generates architecturally neutral byte code instructions. • Java code can be easily interpreted on any machine and easily translated into native machine code on the fly. • JRE includes JVM, class libraries and other supporting files • JRE = JVM + Core Java API Libraries • JDK = JRE + Development Tools like compilers • JDK comes with many versions • A run time bundle is also provided as a part of JDK
  • 25. Java Essentials • Tools such as javac (Compiler) and java (interpreter) and other following tools
  • 26. Java Virtual Machine - JVM • Heart of java is JVM • Programming languages compiles the source code directly into machine code, suitable for microprocessor architecture • The difference with java is that it uses bytecode, an intermediate code • Java bytecode executes on a virtual machine. • Actually there wasn’t hardware implementation of this microprocessor available when java was first released. Instead the processor architecture is emulated by software known as the virtual machine. • The virtual machine is an emulation of a real java processor. – a machine within a machine • The virtual machine runs on the top of the operating system
  • 29. Program Structure • Java application consists of a collection of classes. • A class is a template. • An object is defined as an instance of the class • Each instance(Objects) contains the members specified in the class. • Field is one that holds a value • Method defines operations on the fields and values that are passes as arguments to the method.
  • 30. First Java Program Class example /* example.java */ { public static void main(String args[]) { System.out.println(“Sample Program”); } }
  • 31. Program Structure • public – it is an access specifier used to specify that the code can be called from anywhere. Main is declared as public • static – It is declared static because it allows main() to be called without having to instantiate the class. JVM Need not create an instance of the class(i.e object of the class) for calling main method • Void – It does not return a value. The keyword void simply tells the compiler that main() does not return anything back to the caller (i.e JVM) • String args[] – it holds optional command line arguments passed to the class through the java command line.
  • 32. Versions of java • 1995 version 1.0: – The Java development kit was released for free by the sun – 8-Packages 212-Classes – Microsoft and other companies licensed Java • 1997 version 1.1: – 23-Packages 504-Classes – Improvement include better event handling inner classes , improved JVM. – Microsoft developed its own 1.1 compatible Java Virtual Machine for Internet Explorer – Many browsers in use are still compatible only with 1.1
  • 33. Versions of java… 1999 version 1.2: -It is also called as the Java 2 platform -59 Packages -1520 Classes -Code & tools distributed as the SDK -A Java foundation class based on swings for improved graphics and user interfaces -Collection API included list sets and hash map
  • 34. Versions of java… . 2000 VERSION 1.3: - 76 Packages - 1842 Classes - Java Sound (API for Digital & MIDI Sound) •2002 VERSION 1.4: - 135 Packages - 2991 Classes - Improved XML support etc.., •2004 VERSION 5.0 (1.5): - 165 Packages - over 3000 Classes - Faster startup metadata formatted Output - Generic to operate on objects of various types
  • 35. Versions of java… 2006 Java SE 6: – Scripting language support 2011 Java SE 7: – JVM Support for dynamic language – String in switch – Allowing underscores in numeric literals 2014 Java SE 8: – for Each() method in Iterable interface. - default and static methods in Interfaces. - Functional Interfaces and Lambda Expressions.
  • 36. Versions of java… 2017 Java SE 9: -Stream API Improvements -Multi-Resolution Image API FUTURE EXPECTED UPDATES: – Application Data-Class Sharing: ... – Garbage Collector Interface
  • 37. Java and C Java is a lot like C but the major difference between Java and C is that Java is an object-oriented language and mechanism to define classes and objects. Java does not include the C unique statement keywords goto, sizeof, and typedef. Java does not contain the data types struct, union and enum. Java does not define the type modifiers keywords auto, extern, register, signed and unsigned.  Java does not support an explicit pointer type. Java does not have a preprocessor and therefore we cannot use # define, #include, and # ifdef statements. Java does not support any mechanism for defining variable arguments to functions. Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.  Java add new operators such as instanceof and >>>.  Java adds labelled break and continue statements.  Java adds many features required for object-oriented programming.
  • 38. Java and C++ Java is a true object-oriented language while C++ is basically C with object-oriented extension. Listed below are some major c++ features that were intentionally committed from Java or significantly modified. Java does not support operator overloading. Java does not have temple classes as in C++. Java does not support multiple inheritence of classes. This is accomplished using a new feature called "interface". Java does not support global variables. Every variable and method is declared within a class and forms parts of that class. Java does not use pointers. Java has replaced the destructors function with a finalize() function. There are no header files in Java.
  • 40. Toolkits and platforms  Below Figure describes all major releases of Java to date starting with version 1.0 and ending with version 1.4.
  • 41. Applications, applets, and servlets  First, you can use Java to create applications. This figure shows an application that uses a graphical user interface, or GUI, to get user input and perform a calculation. Application is a program that run in window.  Applet is a special type of program that runs within web browser after it has been retrieved from internet or intranet. One of the unique characteristics of Java is that you can use it to create a special type of web-based application known as an applet. For instance, this figure shows an applet that works the same way as the application above it. The main difference between an application and an applet is that an applet can be stored in an HTML page and can run inside a Java-enabled browser. As a result, you can distribute applets via the Internet or an intranet.  The Enterprise Edition of the Java 2 Platform can be used to create a special type of server-side application known as a servlet. Servlets can access enterprise databases and make that data available via the web.
  • 42. Java and Internet Java is strongly associated with the internet because of the fact that the first application program written in java was HotJava, a Web browser to run applets on Internet. Internet users can use Java to create applet programs and run them locally using a "Java-enabled browser" such as HotJava. Internet users can also set up their Web sites containing Java applets that could be used by Superhighway has made Java a unique programming language for the Internet. In fact, due to this, Java is popularly known as internet language.
  • 43. Java and World Wide Web World Wide Web (WWW) is an open-ended information retrieval system designed to be used in the Internet’s distributed environment. This system contains what are known as Web page that provide both information and controls. Unlike a menu driven system where we are guided through a particular direction using a decision tree structure, the Web system is open-ended and we can navigate to a new documents in any direction as shown in fig. 2.3. This is made possible with the help of a language called Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide. Java was meant to be used in distributed environments such as Internet. Since, both the web and Java share the same philosophy, Java could be easily incorporated into the Web and systems. Before Java , the World Wide Web Was limited to the display of still images and texts. However, the incorporation of Java into Web pages has made it capable of supporting animation, graphics, games and a wide a range of special effects. With the support of Java, the web has become more interactive and dynamic. On the other hand, with the support of Web, we can run a Java program on someone else’s computer across the Internet. Java communicates with a Web page through a special tag called <APPLET>.
  • 45. The figure shows the following communications steps: 1. The user sends a request for an HTML document to the remote computer’s Web server. The Web server is a program that accepts a request, processes the request, and sends the required documents. 2. The HTML document is returned to the user’s browser. The document contains the APPLET tag, which identifies the applet. 3. The corresponding applet bytecode is transferred to the user’s computer. This bytecode had been previously created by the Java compiler using the Java source code file for that applet. 4. The Java-enabled browser on the user’s computer interprets the bytecodes and provides output. 5. The user may have further interaction with the applet but with no further downloading from the provider’s Web server. This is because the bytecode contains all the information necessary to interpret the applet.
  • 46. Web Browsers They allow us to retrieve the information spread across the Internet and display it using the hypertext markup language (HTML). Example of Web browser, among others, include: • HotJava • Netscape Navigator • Internet Explorer
  • 47. HotJava  HotJava is the Web browser from Sun Microsystems that enables the display of interactive content on the Web, using the Java language. HotJava is writing entirely in Java and demonstrates the capabilities of the Java programming language.  When the Java language was first developed and ported to the Internet, no browsers were available that could run Java applets.  Although we can view a Web page that includes Java applets with a regular browser, we will not gain any of Java’s benefits. HotJava is currently available for SPARC/Solaris platform as well windows 95 and Window NT. Its biggest draw is that was the biggest Web browser to provide support for the Java language,  thus making the Web more dynamic and interactive.
  • 48. •Netscape Navigator • Netscape Navigator, from Netscape Communications Corporation, is a general-purpose browser that can run Java applets. • With versions available for Windows 95, NT, Solaris and Apple Macintosh, Netscape navigator is one of the most widely used browsers today. • Netscape Navigator has many useful features such as visual display about downloading process and indication of the number bytes downloaded. It also supports JavaScripts, a scripting language used in HTML documents.
  • 49. •Internet Explorer • Internet Explorer is another popular browser developed Microsoft for Window 95 and NT Workstations. • Both the Navigator and Explorer use tool bars, icons, menus and dialog boxes for easy navigation. • Explorer uses a just-in-time (JIT) compiler which greatly increases the speed of execution.
  • 50. Java Support Systems Table 2.2 list the systems necessary to support Java for delivering information on the Internet.
  • 51. Java Environment Java environment includes a large number of development tools and hundreds of classes and methods. The development tools are part of the system known as Java Development Kit (JDK) and the classes and methods are parts of the Java Standard Library (JSL), also known as the Application Programming Interface (API).
  • 52. Java Developing Kit • The Java Developing Kit comes with a collection of tools that are used for developing and running Java programs. They includes: table 2.3 list these tools and their descriptions.
  • 53.  The way these tools are applied to build and run application programs is illustrated in fig .2.1.  To create a Java program, we need to create a source code file using a text editor.  The source code is then compiled using the Java compiler Javac and executed using the Java interpreter Java.  The Java debugger jdk is used to find errors, if any, in the source code.  A compiled Java program can be converted into a source code with the help of Java disassembler Javap.
  • 54. Application Programming Interface  The Java Standard Library (or API) includes hundreds of classes and methods grouped into several functional packages. Most commonly used packages are:  • Language Support Package: A collection of classes and methods required for implementing basic features of Java.  • Utilities Packages: A collection of classes to provide utility functions such as date and time functions.  • Input/Out Package: A collection of classes required for input/ output manipulation.  • Networking Package: A collection of classes for communicating with other computers via Internet.  • AWT Package: The Abstract Window Tools Kit packages contains classes that implements platform-independent graphical user interface.  • Applet Package: This includes a set of classes that allows us to create Java applets.
  • 55. Advantages of Using Java Java technology will help you do the following: Get started quickly: Although the Java programming language is a powerful object-oriented language, it's easy to learn, especially for programmers already familiar with C or C++.  Write less code: program written in the Java programming language can be four times smaller than the same program in C++. Write better code: The Java programming language encourages good coding practices, and its garbage collection helps you avoid memory leaks. Its object orientation, its Java Beans component architecture, and its wide-ranging, easily extendible API let you reuse other people's tested code and introduce fewer bugs. Develop programs more quickly: Your development time may be as much as twice as fast versus writing the same program in C++. Avoid platform dependencies with 100% Pure Java: You can keep your program portable by avoiding the use of libraries written in other languages. Write once, run anywhere: Because 100% Pure Java programs are compiled into machine- independent byte codes, they run consistently on any Java platform.
  • 56. How Java compiles and interprets code:
  • 57. Description  Any text editor can save and edit the source code for a Java application. Source code files use the java extension.  The Java compiler translates source code into a platform-independent format known as Java bytecodes. Files that contain Java bytecodes use the class extension.  The Java interpreter executes Java bytecodes. Since Java interpreters exist for all major operating systems, Java bytecodes can be run on most platforms.  Any computer with a Java interpreter can be considered an implementation of a Java virtual machine (JVM).  Some web browsers like Netscape and the Internet Explorer contain Java interpreters. This lets applets run within these browsers. However, both Netscape and the Internet Explorer only provide older versions of the Java interpreter.  Sun provides a tool known as the Java plug-in that allows the Netscape and Internet Explorer browsers to use the most current version of the Java virtual machine.
  • 59. A summary of the directories and files of the JDK:
  • 61. Some Important Term  JRE(Java Runtime Environment):  The JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on.  runs code compiled for a JVM and performs class loading (through the class loader), code verification (through the bytecodeverifier) and finally code execution.  The jre directory contains the Java interpreter, or Java Runtime nvironment (JRE), that’s needed to run Java applications once they’ve been compiled.
  • 62. • Java virtual machine (JVM): • Any machine that has a Java interpreter installed on it can be considered an implementation of a Java virtual machine (JVM).
  • 63. Class Loader:  responsible for loading all classes needed for the Java program. Bytecodeverifier:  tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objects. Garbage collection thread:  responsible for freeing any memory that can be freed. This happens automatically during the lifetime of the Java program.  programmer is freed from the burden of having to deallocatethat memory themselves. How Code Security Is Maintained In Java?  Ans:Code Security Is maintained By Following Term. (1)JRE (2)Class Loader (3)Bitecodeverifier
  • 64. JAVAPROGRAMSTRUCTURE: • As all other programming languages, Java also has a structure. • The first line of the C/C++ program contains include statement. For example, <stdio.h> is the header file that contains functions, like printf (), scanf () etc. So if we want to use any of these functions, we should include this header file in C/ C+ + program. • Similarly in Java first we need to import the required packages. By default java.lang.* is imported. Java has several such packages in its library. A package is a kind of directory that contains a group of related classes and interfaces. A class or interface contains methods. • Since Java is purely an Object Oriented Programming language, we cannot write a Java program without having at least one class or object. So, it is mandatory to write a class in Java program. We should use class keyword for this purpose and then write class name. • In C/C++, program starts executing from main method similarly in Java, program starts executing from main method. The return type of main method is void because program starts executing from main method and it returns nothing.
  • 65.  Since Java is purely an Object Oriented Programming language, without creating an object to a class it is not possible to access methods and members of a class. But main method is also a method inside a class, since program execution starts from main method we need to call main method without creating an object.  Static methods are the methods, which can be called and executed without creating objects.  Since we want to call main () method without using an object, we should declare main ()method as static.  JVM calls main () method using its Classname.main () at the time of running the program.  JVM is a program written by Java Soft people (Java development team) and main () is the method written by us. Since, main () method should be available to the JVM, it should be declared as public. If we don’t declare main () method as public, then it doesn’t make itself available to JVM and JVM cannot execute it.  JVM always looks for main () method with String type array as parameter otherwise JVM cannot recognize the main () method, so we must provide String type array as parameter to main () method.
  • 66.  A class code starts with a {and ends with a}. A class or an object contains variables and methods (functions). We can create any number of variables and methods inside the class. This is our first program, so we had written only one method called main ().  Our aim of writing this program is just to display a string “Hello world”. In Java, print () method is used to display something on the monitor.  A method should be called by using objectname.methodname (). So, to call print () method, create an object to PrintStream class then call objectname.print () method.  An alternative is given to create an object to PrintStream Class i.e. System.out. Here, System is the class name and out is a static variable in System class. out is called a field in System class. When we call this field a PrintStream class object will be created internally. So, we can call print() method as: System.out.print (“Hello world”);  println () is also a method belonging to PrintStream class. It throws the cursor to the next line after displaying the result.  In the above Sample program System and String are the classes present in java.lang package.
  • 67. Comments  Comments are description about the aim and features of the program.  Comments increase readability of a program.  Three types of comments are there in Java:  · Single line comments: These comments start with // e.g.: // this is comment line  · Multi line comments: These comments start with /* and end with */ e.g.: /* this is comment line*/  · Java documentation comments: These comments start with /** and end with */ These comments are useful to create a HTML file called API (application programming Interface) document. This file contains description of all the features of software.
  • 68. Java documentation comments(Example)  Example 3-1: FirstSample.java /* This is my the first program in Java I am enjoying Java. */ public class FirstSample { public static void main (String [] args) { System.out.println("Welcome to the world of Java"); } }
  • 69. Escape Sequence • Java supports all escape sequence which is supported by C/ C++. • A character preceded by a backslash () is an escape sequence and has special meaning to the compiler. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.
  • 70. How to create identifiers • As you code a Java program, you need to create and use identifiers.
  • 71. keyword • A keyword is a word that’s reserved by the Java language. As a result, you can’t use keywords as identifiers.
  • 72. IDE – Integrated Development Environment • Eclipse • DrJava • Jcreator • NetBeans
  • 73. Java Programming constructs • Variables: • Variable is a symbolic name refers to a memory location used to store values that can change during the execution of the program • int watts = 100;
  • 74. Primitive Data Types • Primitive data types are the basic building blocks of any programming language. • There are eight primitive data types in java • byte • Short • Int • long • float • double • char • boolean
  • 75. Primitive Data Types • Byte – It is a 1 byte (8 bit) ranges from -128 to 127 • Short – It is 2 byte (16 bit) ranges from -32768 to 32767 • Int – It is a 4 byte (32 bit) ranges from -2,147,483,648 to +2,147,483,647 • Long – It is an 8 – byte (64 bit) ranges from -9223372036854775808 to - 9223372036854775807 • Float – it is a single precision ( 32 bit – floating point) ranges from 1.401298464324817e-45f to 3.402823476638528860e+38f • Double – this is double precision 64 bit floating point ranges from 4.94065645841246544e-324 to 1.79769313486231570e(+) 308 • Char – single 16bit Unicode character, It ranges from ‘ u000’ to ufff’ • Boolean – true or false
  • 76. Literals • A literal is a value that can be passed to a variable or constant in a program • Literals can be numeric , boolean, character, string notations or null literals. • Numeric Literals: It can be represented in binary, decimal, octal or hexa decimal notations. • Binary Literals: There are combination of 0’s and 1’s. Binary Literals can be assigned to variables in java. • Binary Literals must be prefixed with 0b or 0B • Char bin1 = 0b101000 // value in bin 1 will be P • Char bin2 = 0b101001 // value in bin 2 will be Q
  • 77. Numeric Literal • Octal Literals: Value must be prefixed with a zero and only digit from 0 to 7 are allowed. • Ex: int x =011; // value in x is 9 • Char y=0150;// value in y will be h • Hexa Decimal: It is prefixed with 0x or 0X the digit from 0 through 9 and a through f • Ex: int y=0x0001 // value in y is 1 char x = 0x45 // value in x will be E
  • 78. Literals • Integer Literals: All integer literals are of type int • If long int • Ex: long l = 2345678L; • Floating Literals: These are double type by default. • We need to attach suffix of F or f • Ex: float f =23.6F; • Char Literals: A single character is enclosed in single quotes. • You can also use the prefix u; • Char c = ‘a’
  • 79. Literals • Boolean literals: it is specified as either true or false. By default it takes the value false’ • Boolean first=true; • String Literals: It consists of zero or more characters within double quotes String s = “This is a string Literal”; • Null Literals: It is assigned to object reference variables S= null;
  • 80. Operators • An Operator performs an action on one or more operands • An operator that performs an action on one operand is called unary Operators • An operator that performs an action on two operands is called a binary operator • Java Provides • Arithmetic • Relational • Logical • Assignment ( = ) • Shift • Conditional • Bitwise • Member Access Operator
  • 81. Bitwise AND: & Bitwise OR: | Bitwise XOR: ^
  • 83. Shift Operator • Signed Left Shift Operator (<<) • Signed Right Shift Operator (>>) • Unsigned Right Shift Operator (>>>) • Binary equivalent of 5 is 0101. • Assume that the statement is as follows: • x<<4, let y be 4
  • 85. Unary Operators Increment and Decrement Operators: (--X, ++X) – Prefix (X--, X++) – Postfix Answer: 232 #include <stdio.h> int main() { int x=2; int y=++x; int z= --x; }
  • 86. Ternary Operator or Conditional Operator • String greater = x< y ? “y is greater”: “x is greater”;
  • 87. Expressions • Expression is a combination of operators and /or operands • Java Expressions are used to create objects, arrays, pass values to methods and call them, assigning values to variables. • Int m=2, n=3, o=4; • Int y= m * n * o;
  • 89. Primitive Type Conversion and Casting In java Type conversions are performed automatically, when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment char Byte-> short-> int -> long->float->double Conversions that are implicit in nature are termed as widening conversions
  • 90. Primitive Type Conversion • byte b =20; • Int i=b; • Type conversion or promotion also takes place while evaluating the expressions involving arithmetic operators • int i =10; int variable • double d = 20; int literal assigned to a double variable • D = i + d; automatic conversion into double
  • 91. Primitive Type Conversions • short z = b*s; invalid • int i=b*s; valid • float f=3; legal • float f=3.0 illegal • float f = 3.0f legal
  • 92. Casting • Casting is also known as narrowing of conversions (reverse of widening conversion) • Byte <- short <- int<-long-<float-<double Narrowing Conversion • If you want to assign bigger values to smaller, for such situations called Casting can be done. • Casting is not implicit in nature int i = (int) (8.0 / 3.0);
  • 93. Flow of Control • Control flow statements help programmers make decisions about which statement to execute and to change the flow of execution in a program. • The four categories of control flow statements available in java are conditional statements, loops, exception and branch 1. Conditional Statements (if else if switch) 2. Loops (for while do-while) 3. Branching Mechanism (break, label, continue) 4. Exception