0% found this document useful (0 votes)
11 views93 pages

Java Fundamentals

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
11 views93 pages

Java Fundamentals

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 93

Fundamentals of

Programming

Prof. Sadashiv Badiger,


Assistant Professor, Computer Department
Review of Object Oriented Programming

● The language like C, Pascal, Fortran, etc are called procedure oriented
programming languages.

● On the other hand language like C++, Java and Python use classes and
objects in their programs and are called object oriented programming
language

● The procedure oriented program a programmer's uses procedure or function


to perform a task
Problems in Procedure Oriented Programming
● The programmer concentrates
on a specific task, and writes a
set of functions to achieve it.
● One function may depends on
another function
● Code size will increases
● Concurrency and Parallelism
Challenges
● Error Handling
● Difficult in Modeling real world
problems
Advantages of Object Oriented Program
Evolution of Java

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.

● Java was developed by Sun Microsystems (which is now


the subsidiary of Oracle) in the year 1995

● James Gosling is known as the father of Java

● Before Java, its name was Oak

James Gosling
Metrics C C++ Java

Programming Procedural Language Object Oriented Pure Object Oriented


Paradigm Programming Programming

Origin Based on Assembly Based on C language Based on C and C++


Language

Developer Dennies Ritchie in Bjarne Stroustrup in James Gosling in 1995


1972 1979

Translator Compiler Compiler (Interpreted language)


Compiler and
Interpreter

Platform Platform dependent Platform dependent Platform Independent


Dependency

Code execution Direct Direct Execute by JVM (Java


virtual Machine)
Metrics C C++ Java

Approach Top-Down Bottom Up Bottom Up

File Generation .exe files .exe files .class files

Preprocessor Support Header Files Supported Use packages (import)


Directives (#include, #define) (#header, #define)

Keywords Supports 32 keywords Supports 63 keywords 50 defined keywords

Data types Supported Supported Not Supported


(union,structure)

Inheritance No inheritance Supported Supported except


multiple inheritance

Pointer Supported Supported Not supported


Metrics C C++ Java

Allocation Use malloc,calloc Use new, delete Garbage Collector

Exception Handling Not supported Supported Supported

Templates Not Supported Supported Not Supported

Multithreading Not Supported Not Supported Supported

Database Not Supported Not Supported Supported


Connectivity

Storage Classes Supported Supported Not Supported


(auto,extern) (auto,extern)
1. Object Oriented
Java is purely an object oriented language. Almost everything in Java is an object. All
programs and data live within objects and classes. ‘Objects’ model Java rather than the
‘processes’. Java comes with an extensible set of classes organized in packages.

we cannot develop an executable program in


Java without making use of the class. This
indicates that Java very strictly applies the
principle of Encapsulation.
2. Java is Simple Language
According to sun microsystem Java is simple because

● Syntax is based on C++, so easier for programmer to learn it after C++


● Removed confusion and rarely used features like

❖ Concept of Explicit Pointers


❖ Storage classes
❖ Preprocessors and header files
❖ Multiple Inheritance
❖ Operator Overloading
❖ Goto Statements

● No need to remove unreferenced object because there is automatic Garbage Collector


in Java
3. Java is Secured Programming Language

Java is the most popular object-oriented programming language. It provides a variety of


salient features that are preferred by the developers. It is the reason that a billion of devices runs
on Java.

Java is secure due to the following reasons:

● Java programs run inside a virtual machine which is known as a sandbox.


● Java does not support explicit pointer.
● Byte-code verifier checks the code fragments for illegal code that can violate access right
to object.
● It provides java.security package implements explicit security.
● It provides library level safety.
● Run-time security check takes place when we load new code.
4. Java is Platform Independent Programming Language
● The most significant feature of Java is
that it provides platform independence
which leads to a facility of portability,
which ultimately becomes its biggest
strength.
● Being platform-independent means a
program compiled on one machine can
be executed on any machine in the
world without any change. Java
achieves platform independence by
using the concept of the BYTE code.
5. Java is Robust Programming Language

The English meaning of Robust is strong. Java is robust because:

● It uses strong memory management.


● There is a lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
● There are exception handling and the type checking mechanism in Java. All these points
make Java robust.

Course Name: Fundamental of Java Programming Course Instructor: Prof. S. R. Badiger, E&TC Dept, BSCOER, Pune
6. Java is Portable Programming Language

● The portability actually comes from architecture-neutrality.

● In C/C++, the source code may run slightly differently on different hardware platforms,

but Java simplifies it.

● You can run Java bytecode on any hardware that has a compliant JVM which can

convert the bytecode according to that particular machine.

● Moreover, any changes and updates made in Operating Systems, Processors and

System resources will not enforce any changes in Java programs.


7. Java is Architecture Neutral Programming Language

● This buzzword means that the program written on one platform or OS is independent of

other platforms or environments and can run on any other Operating System without

recompiling them.

● In other words, it is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-

run-everywhere’ (WORE) approach.

● Byte-code is not dependent on any machine architecture and Java Virtual Machine

(JVM) can easily translate bytecode into a machine-specific code.

● This feature is very useful when we develop applets or download applications from the

Internet.
8. Java is Dynamic Programming Language

● Java is dynamic and extensible means with the help of OOPs, we can add classes and add

new methods to classes, creating new classes through subclasses. This makes it easier for

us to expand our own classes and even modify them.

● Java gives the facility of dynamically linking new class libraries, methods, and objects. It is

highly dynamic as it can adapt to its evolving environment.

● Java even supports functions written in other languages such as C and C++ to be written in

Java programs. These functions are called “native methods”. These methods are

dynamically linked at runtime.


9. Java is Compiled and Interpreted Programming Language

● Usually, a computer language can be either compiled or interpreted. Java integrates the
power of Compiled Languages with the flexibility of Interpreted Languages.
● Java compiler (javac) compiles the java source code into the bytecode.
● Java Virtual Machine (JVM) then executes this bytecode which is executable on many
operating systems and is portable.
● The diagram below shows the above process:
10. Java is High Performance Programming Language

● The performance of Java is impressive for an interpreted language because of its


intermediate bytecode.
● Java provides high performance with the use of “JIT – Just In Time compiler”, in
which the compiler compiles the code on-demand basis, that is, it compiles only that
method which is being called. This saves time and makes it more efficient.
● Java architecture is also designed in such a way that it reduces overheads during
runtime. The inclusion of multithreading enhances the overall execution speed of Java
programs.
● Bytecodes generated by the Java compiler are highly optimized, so Java Virtual
Machine can execute them much faster.
11. Java is Multithreading Programming Language

● A thread is an independent path of execution within a program, executing concurrently.


Multithreaded means handling multiple tasks simultaneously or executing multiple
portions (functions) of the same program in parallel.
● The code of java is divided into smaller parts and Java executes them in a sequential and
timely manner.
Cont…

Advantages:

● The main advantage of multithreading is that the maximum utilization of resources is


possible.
● It doesn’t occupy memory for each thread. It shares a common memory area.
● There is no need to wait for the application to finish one task before beginning
another one.
● There is a decreased cost of maintenance. Also, It is time-saving.
● It improves the performance of complex applications.
12. Java is Distributed Programming Language
● Java is distributed because it encourages users to create distributed applications.
● In Java, we can split a program into many parts and store these parts on different
computers. A Java programmer sitting on a machine can access another program
running on the other machine.
● This feature in Java gives the advantage of distributed programming, which is very
helpful when we develop large projects. Java helps us to achieve this by providing the
concept of RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans).
● Java comes with an extensive library of classes for interacting, using TCP/IP protocols
such as HTTP and FTP, which makes creating network connections much easier than
in C/C++.
● It also enables multiple programmers at many locations to work together on a single
project.
Java and Internet
● Java is strongly associated with internet
because of the fact that the first application
program written in Java was HotJava, a web
program 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 use “Java-enabled
browser” to download an applet located on a
computer anywhere in the internet. And run it
on local computer.
● In fact Java applets made the internet a true
extension of the storage system of local
computer.
JAVA and World Wide Web

● World Wide Web (WWW) is an open-ended


information retrieval system designed to be used in the
internet distributed environment.
● This system consists of what are known as Web
Pages that provides both information and controls.
Web structure of information search
● The web system is open-ended and we can
navigate to a new document in any direction.
● 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.

Web pages contain HTML tags


Cont…
Java uses Applets to communicate with
any web page. The steps involved are

● The user sends requests for a hyperlink


document to a web server of the remote
computer.
● The hyperlink document contains the applet
tag that identifies the applet.
● The Java source code file compiles the
bytecode for that applet and transfers it to
the user’s computer.
● The browser enabled by Java programming
interprets the bytecode and provides the
output to the user.
Web Browsers
● The internet is a vast sea of information represented in many formats and stored on
many computers.
● A large portion of the internet is organized as the world wide web uses hypertext.
● Web Browser are used to navigate through the information found on the net.
● They allow us to retrieve the information spread across the internet and display it using
the hypertext markup language (HTML)
Hyperlink Vs Hypertext

Hyperlink: The hyperlink contains the URL of the webpages. In a general way, a hyperlink is
referenced when a hypertext navigated. These hyperlinks are hidden under the text, image,
graphics, audio, video, and gets highlighted once we hover the mouse over it.

Hypertext: Ted Nelson introduced the term Hypertext in 1956. Hypertext is a text which contains
the visible text to redirect the targeted page(page URL contained by Hyperlink)
Java Support Systems
Support System Description

Internet Local computer should be connected to the Internet


Connection

Web Server A Program that accept request for information and sends the required
documents

Web Browser A Program that provide access to WWW and runs Java applets

HTML A language for creating hypertext for the web

Applet Tag For placing Java applets in HTML Documents

Java Code Java Code is used for defining Java applets

Bytecode Compiled Java Code that is referred to in the APPLET tag and transferred to
the user computer

Proxy Server An intermediate server between the requesting client workstation and
original sever. It is typically implemented for ensuring security.
Java Environment
● Java Environment includes a large number of development tools and hundreds of
classes and methods.
● The development tools are the part of the system known as Java Development Kit
(JDK).
● The class and methods are the part of the Java System Library (JSL), also known as the
Application Programming Interface (API).
Java Development Kit
Java Development Kit comes with a collection of tools that are used for developing and running Java
programs. They include

Tool Description

Enables us to run Java applets (without actually using a Java-compatible


Appletviewe browser)
r
The java compiler which translate Java source code to bytecode files that the
javac interpreter can understand

Java interpreter, which runs applets and applications by reading and


java interpreting bytecode file.

Creates HTML format documentation from java source code files


javadoc
Produce header file for use with native methods
javah
Java disassembler, which enables us to convert bytecode files into a program
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
1. Language Support Package : A Collection of classes and methods required for implementing
basic feature of Java.
2. Utilities Package : A collection of classes to provide utility function such as date and time
functions.
3. Input/Output Packages: A collection of classes required for input/output manipulation.
4. Networking Packages: A collection of classes for communicating with other computer via internet
5. AWT Packages: The abstract Window Toolkit package contains classes that implements platform
independent graphical user interface

6. Applet packages: This includes a set of classes that allows us to create Java Applets
Process of building and Running Java Languages
JVM Architecture
Class Loader
It mainly responsible for three activities

a) Loading : The class loader reads .class file and generate the corresponding
binary data and save in the method area. For each .class file, JVM stores the
following information in method area.
❖ Class and its immediate parent class
❖ Variables and Method information
a) Linking : Linking performs
❖ Verification : Ensure correctness of the JVM
❖ Preparation : JVM allocated memory for class variable
❖ Resolution : It is the process of replacing symbolic reference from
the type with direct references
Cont…

C. Initialization: in this phase all the static variable are assigned with their values
defined in the code and static block. This is executed from top to bottom in a class
and from parent to child in the class hierarchy.
In general there are three class loaders

1. Bootstrap class loader


2. Extension class loader
3. System/Application class loader
JVM Memory
a) Method area: class name, immediate parent class name, methods and
variable information are stored

There is only one method area per JVM and it is shared resource.

b) Heap area: Information of all objects is stored in the heap area. There is also
one heap area per JVM and it is also shared resource
c) Stack area: For every thread JVM creates one runtime stack which is stored in
stack area
d) PC register: Store address of current instructions of thread. Obviously each
thread has separate PC register.
e) Native method stacks: For every thread, a separate native stack is created. It
stores native method information.
Cont…
Execution Engine

Execution engine executes the .class (bytecode). It reads byte code line by line,
uses and information present in various memory area and execute instructions. It
can be classified into three parts.

1. Interpreter : It interprets the bytecode line by line and then executes.


2. Just-In-Time Compiler : It is used to increase the efficiency of an
interpreter.
3. Garbage collector: It destroys unreferenced objects
Java Native Interface (JNI)

● It is an interface that interacts with the Native Method Libraries and provide
native libraries (C,C++) required for the execution.
● It enables JVM to call C/C++ libraries and to be called by C/C++ libraries
which may be specific to hardware
Native Method Libraries

● It is collection of the native libraries (C,C++)


● Which are required by the execution engine
Overview of Java Language
Java is general-purpose, object oriented programming language. We can develop two types of Java
Programs

1. Stand-alone applications
2. Web applets

Executing stand-alone Java program involves two steps

3. Compiling source code into bytecode using javac compiler


4. Executing the bytecode program using java interpreter

Applets are small Java programs developed for internet applications. We can develop applets for doing
everything from simple animated graphics to comlex games and utilities.

Stand-alone programs can read and write files and perform certain operations that applets cannot do.
Applet can run only within web browser
Two ways of using Java
Simple Java Program Public : the keyword public is an access specifier that
declares the main method as unprotected an therefore
making it accessible to all other classes. This is similar
class SampleOne
to the C++ public modifier
{
Statistic : Next appears the keyword statistic, which
public static void main (String[ ] args ) declares this method as one that belongs the entire
{ class and not a part of any object of the class.

The main must always be declare as static


System.out.println (“Java is
since the interpreter uses this method before any
better than c++”) objects are created.

} Void : The type modifier void states that the main


} method does not return any value
Java Program Structure
Java Tokens
Java tokens are the smallest elements of a program which are identified by the compiler.
Java tokens includes

1. Keywords
2. Identifier
3. Literals
4. Operator
5. Separator
Keywords
A Java keyword is one of 50 reserved terms that have a special function and a set definition
in the Java programming language.
Identifiers
Identifiers are used to naming classes, methods, variables, objects, labels,
packages and interfaces in a program. Java identifier follow the following rules

1. They can have alphabets, digits and the underscore and dollar sign
character
2. They must not begin with digit
3. Uppercase letter and Lowercase letter are distinct
4. They can be of any length

Identifier must be meaningful and short enough


Java Developer uses following naming convention

● Name of all public methods and instance variables start with leading
lowercase letter example

Example : average, sum

When more than one words used

Example : dayTempreture
● All private and local variables use only lowercase letters combined with
underscores

Example : length, batch_strength


● All classes and interfaces start with leading uppercase letter

Example : Student

HelloJava
Literals

A literal is a notation for representing a fixed value in source code. Java language
specifies five major types of literals. They are

1. Integer literals : 1
2. Floating point literals : 10.1
3. Character literals : a
4. String literals : “java”
5. Boolean literals : True, False
Operators
An operator is a symbol that takes one or more arguments and operates on them
to produce a result
Separators
Separators are the symbol used to indicate where group of code divided and
arranged. They basically define the shape and functions of our code
● Parenthesis → ( )
● Braces → { }
● Brackets → [ ]
● Semicolon → :
● Comma → ,
● Period → .
Java Statements
Java statements are like sentences in natural languages. A statement is an
executable combination of tokens ending with semicolon (;) mark.
Installing and configuring Java
Constants in Java
Constant in Java refer to fixed values that do not change during the execution of
program.
Integer constants
There are three types of integer constants

1. Decimal integer consists of a set of digits, 0 through 9

Example : 123 -321 0 654321

2. Octal integer constant consists of any combination of digit from 0 to 7, with a


leading 0.

Example : 037 0437 0551

3. A sequence of digits preceded by 0x or 0X is consider as hexadecimal


integer constants

Example : 0x2 0x9F


Real constants

● Real constants consist of a sequence of digits with fractional parts or


decimal points. These constants are also called floating-point
constants. The valid examples of real constants are 2.3, 0.0034, -0.75,
56.7, etc.
● A real constants number can also be expressed in exponential or
scientific notation. For example, the value 235.569 can also be written as
2.35569e2 in exponential notation. Here, e2 means multiply by 10^2.

It has the following general form:

mantissa e exponent
Single Character Constant
A single character constant contains a single character enclosed within a pair of
single quote marks. Example of character constants are

‘5’ ‘X’ ‘;’ ‘ ’

The character constant ‘5’ is not same as the number 5.

String Constant
A string is a sequence of characters enclosed between double quote.

“HelloJava” “1997” “WELCOME”


“5+3”
Backslash Character Constants
Variables

● A Variable is an identifier that denotes a storage location used to store a data


value.
● Unlinke constants that remain unchanged during the execution of a program,
a variable may take different values at different times during the execution of
the program
● Variables name may consists of alphabets, digits, the underscore (_) and
dollar character
Data Types
Size and Range of Data Types
How to use Data types in Java Programming

public class DataTypes { System.out.println(byteDataType);

public static void main(String[] args) { System.out.println(shortDataType);

byte byteDataType = 127; System.out.println(intDataType);


System.out.println(longDataType);
short shortDataType = 128;
System.out.println(floatDataType);
int intDataType = 32768;
System.out.println(doubleDataType);
long longDataType = 2147483648L;
System.out.println(charDataType);
float floatDataType = 20.99F;
System.out.println(booleanDataType);
double doubleDataType = 49999999.9d;
}
char charDataType = 'M';
}
boolean booleanDataType = true;
Declaration of variables
In java variables are the names of storage location. After designing suitable names declare them to the
compiler. Declaration does three things

1. It tells the compiler what the variable name is


2. It specifies which type of data the variable will hold
3. The place of declaration decides the scope of the variable

The general form of declaration of a variable is

Type variable1, variable2, ……………………variableN

Example

int count;

float x,y;

double pi;

byte b;
Giving values to variable

This is achieved by using two ways

1. By using assignment statement

Data type variableName = value;

For example : initialValue = 0;

2. By using read statement

We may also give values to variable interactively through the keyboard using
readLine() method
Scope of variable {

int x=0;

Java variables are actually classified into ………………..


………………
three kinds ………………. Block 1
int n=5;
● Instance variables ……………….
● Class variables ……………….
● Local variables
………………..
Instance and class variables are
………………
declared inside a class. ………………. Block 2
int m=10;
Variables declared and used inside ……………….
methods are called local variable. ……………….

}
Type Casting
The process of converting one data type to another data type is called type casting.
The syntax is

type variable1= (type) variable2

Example :

byte m = 50;

int n = (int) m;

long count = (long) n;


Getting values of variables

A Computer program is written to manipulate a given set of data and to display or


print the results. Java support two output methods that can be used to send the
result to the screen
System.out.print(“Hello”)
System.out.print(“Java!”)

System.out.println(“Hello”)
System.out.println(“Java”)
Operator and Expressions

Java operators can be classified into a number of related categories as below

1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Increment and Decrement operator (Unary Operator)
6. Conditional operator
7. Bitwise operator
8. Special operator
Arithmetic operator
Relational Operator
Assignment Operator
Logical Operator
Unary Operator
Bitwise Operator
Conditional Operator (Ternary Operator)
● The ternary operator is a conditional operator that decreases the length of code while
performing comparisons and conditionals.
● This method is an alternative for using if-else and nested if-else statements. The
order of execution for this operator is from left to right.
Syntax:

(Condition) ? (Statement1) : (Statement2);

Condition: It is the expression to be evaluated which returns a boolean value.

Statement 1:It is the statement to be executed if the condition results in a true state.

Statement 2:It is the statement to be executed if the condition results in a false state.
Arithmetic Expression
● An arithmetic expression is a combination of variables, constants, and operators
arranged as per the syntax of the language.
● An arithmetic expression without any parenthesis will be evaluated from left to right
using the rules of precedence of operators. There are two distinct priority levels of
arithmetic operator in java.

High priority * / %

Low priority + -

Evaluate the expression below using a=9, b=12, and C=3

x =a-b/3+c*2-1
Decision making and Branching
● Java compiler executes the code from top to bottom. The statements in the code
are executed according to the order in which they appear. However,
● Java provides statements that can be used to control the flow of Java code.
Such statements are called control flow statements.
● It is one of the fundamental features of Java, which provides a smooth flow of
program.
● When a program break the sequential flow and jumps to another part of the
code it is called branching
Java provides three types of control flow statements.

1. Decision Making statements


○ if statements
○ switch statement
2. Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
3. Jump statements
○ break statement
If statement
Nested if statement
Else if Ladder
Switch Statement
While Loop
Do while loop
For Loop
Nested For Loop
Cont...
Continue Statement in Java
Break Statement in Java

You might also like