Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

CH-1 Java Introduction To Java Programming

The document provides an introduction to Java programming, covering procedural and object-oriented programming concepts, including key principles like encapsulation, inheritance, and polymorphism. It details Java's features, such as being platform-independent, robust, and secure, along with its architecture including the Java Virtual Machine (JVM). Additionally, it explains Java's data types, variable declaration, type casting, and array creation, highlighting the language's simplicity and efficiency.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CH-1 Java Introduction To Java Programming

The document provides an introduction to Java programming, covering procedural and object-oriented programming concepts, including key principles like encapsulation, inheritance, and polymorphism. It details Java's features, such as being platform-independent, robust, and secure, along with its architecture including the Java Virtual Machine (JVM). Additionally, it explains Java's data types, variable declaration, type casting, and array creation, highlighting the language's simplicity and efficiency.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Introduction To Java

Programming
Procedural Programming
It is a programming language that follows a step-by-step approach to break down a
task into a collection of variables and routines through a sequence of instructions.

It follows the concept of the calling procedure.

The procedures are also called functions,routines or subroutine.consists of a series of


computational steps that they need to carry out.

During the execution of a program,one can call any given procedure at any point either
by other procedures or by itself.
Object-Oriented Programming
Object-Oriented Programming as programming model that follows the concept of
objects.

OOP treats data as a critical element in the program development and does not allow
it to flow freely around the system.

It ties data more closely to the functions that operate on it and protects it from
unintentional modification by other functions.
Basic Concepts of Object-Oriented Programming
1.Objects and Classes.

2.Data Abstraction and Encapsulation.

3.Inheritance.

4.Polymorphism.
Objects and Classes
Objects are the basic runtime entities in an object-oriented system.They may
represent a person,a place,a bank account that the program may handle.

Example:
Data Abstraction and Encapsulation
The wrapping up of data and methods into a single unit is known as encapsulation.

The data is not accessible to the outside world and only those methods,which are
wrapped in the class,can access it.This insulation of the data from direct access by
the program is called data hiding.

Abstraction refers to the act of representing essential features without including the
background details or explanations.
Inheritance
Inheritance is the process by which objects of one classacquire the properties of
objects of another class.Inheritance supports the concept of hierarchical
classification.

In OOP,the concept of inheritance provides the idea of reusability.This means that


we can add additional features to an existing class without modifying it.This is
possible by deriving a new class from the existing one.The new class will have the
combined features of both the classes.
Polymorphism
Polymorphism means the ability to take more than one form.The behavior depends
upon the types of data used in the operation.
Difference between Procedure Oriented and Object
Oriented Programming
Procedure Oriented Programming Object Oriented Programming

Access modifiers are not supported. Access modifiers are supported.

It focuses on the process and functions. It focuses on the data and classes.

Procedural programming is less secure than Object-Oriented Programming is secure because


Object-Oriented Programming. data hiding is possible in OOPs due to abstraction.

In Procedural programming, the program is In Object-Oriented Programming, a program is


divided into small functions. divided into small objects.

POP follows a top-down approach. OOP follows a bottom-up. approach.


History of Java

● Java is a general-purpose,object-oriented programming language developed by


Sun Microsystems of USA in 1991.
● Originally called Oak by James Gosling,one of the inventors of the
language,Java was designed for the development of software for consumer
electronic devices like TVs,VCRs,toasters and such other electronic machines.
● The goal had a strong impact on the development team to make the language
simple,portable and highly reliable.
Java Features
1.Compiled and Interpreted.

2.Platform-Independent and Portable.

3.Object-Oriented

4.Robust and Secure

5.Distributed.

6.Simple,Small and Familiar.

7.Multithreaded and Interactive.


8.High Performance

9.Dynamic and Extensible

10.Ease of Development

11.Scalability and Performance

12.Monitoring and Manageability.


Compiled and Interpreted
1.Java is a two-stage system.

2.First,Java compiler translates source code into what is known as bytecode


instructions.

3.Bytecodes are not machine instructions and therefore the second stage,Java
interpreter generates machine code that can be directly executed by the machine that
is running the java program.

4.Thus Java is both a compiled and an interpreted language.


Platform-Independent and Portable.

Portability:Java programs can be easily moved from one computer system to


another,anytime anywhere.

Changes and upgrades in operating system,processors and system resources will not
force any changes in the Java programs.

Java ensures portability in to ways:First,Java compiler generates bytecode


instructions that can be implementation on any machine.Secondly,the size of the
primitive data types are machine independent.
Object-Oriented

Java is a true object oriented language.

Almost everything in Java is an object.

All program code and data reside within objects and classes.

Java comes with an extensive set of classes,arranged in packages.


Robust and Secure

Java is a robust language as it provides many safeguards to ensure reliable code.


It has strict runtime and compile time checking for data types.
It is designed as a garbage collected language relieving the programmers virtually
all memory management problems.
Java also incorporates the concept of exception handling which captures serious
errors and eliminates any risk of crashing the system.
The absence of pointers in Java ensures that programs cannot gain access to
memory locations without proper authentication.
Distributed

Java is designed as a distributed language for creating applications on networks.

It has the ability to share both data and programs.

Java applications can open and access remote objects on Internet as easily as they
can do in a local system.

This enables multiple programmers at multiple remote locations to collaborate and


work together on a single project.
Simple,Small and Familiar.
Java is a small and simple language.

Java does not use pointers ,preprocessor header files,goto statement and many
others.

To make the language look familiar to the existing programmers,it was modeled on
C and C++ code.
Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously.

Java supports multithreaded programs.This means that we need not wait for the
application to finish one task before beginning another.
High Performance
Java performance is impressive for an interpreted language,mainly due to the use of
intermediate bytecode.

Java architecture is also designed to reduce overheads during runtime.

Further,the incorporation of multithreading enhances the overall execution speed of


Java programs,
Dynamic and Extensible
Java is a dynamic language .

Java is capable of dynamically linking in new class libraries,methods and objects.


Ease of development
Java 2 Standard Edition supports features such as Generics,Enhanced for
loop,Autoboxing or unboxing reduce the work of the programmer by shifting the
responsibility of creating the reusable code to compiler.
Scalability and Performance
Java 2 Standard Edition assures a significant increase in scalability and performance
by improving the startup time and reducing the amount of memory used in Java 2
runtime environment.

Memory utilization is reduced by sharing data in the shared archive among multiple
JVM processes.
Monitoring and Manageability
Java supports number of APIs such as JVM Monitoring and Management
API,Logging,Monitoring and Management Interface.
JVM Architecture
JVM is the core of the Java ecosystem, and makes it possible for Java-based software
programs to follow the "write once, run anywhere" approach. You can write Java code on
one machine, and run it on any other machine using the JVM.
Java uses a combination of both techniques i.e Compilation and Interpretation. Java code
is first compiled into byte code to generate a class file. This class file is then interpreted by
the Java Virtual Machine for the underlying platform. The same class file can be executed
on any version of JVM running on any platform and operating system.
The JVM consists of three distinct components:

1. Class Loader
2. Runtime Memory/Data Area
3. Execution Engine
Class Loader

● When you compile a .java source file, it is converted into byte code as a .class file.
When you try to use this class in your program, the class loader loads it into the main
memory.
● The first class to be loaded into memory is usually the class that contains the main()

method.
● There are three phases in the class loading process: loading, linking, and
initialization.
Runtime Memory/Data Area
Execution Engine
● Once the bytecode has been loaded into the main memory, and details are available
in the runtime data area, the next step is to run the program. The Execution Engine
handles this by executing the code present in each class.
● However, before executing the program, the bytecode needs to be converted into
machine language instructions. The JVM can use an interpreter or a JIT compiler for
the execution engine.
Understanding Working of Java
Java is a general-purpose,object oriented programming language.

We have two types of Java Programs:

1.Standalone applications.

2.Web applets.

Standalone applications are programs written in Java to carry out certain tasks on a
standard local computer.
Executing a standalone Java program involves two steps:

1.Compiling source code into bytecode using javac compiler.

2.Executing the bytecode program using java interpreter.


Sample Java Program
class SampleOne{

public static void main(){

System.out. println(“Welcome to Java Programing”);

}
Class Declaration
The first line SampleOne declares a class,which is an object-oriented construct.

Java is a true object-oriented language and therefore everything must be placed


inside a class.class is a keyword and declares that a new class definition follows.

SampleOne is a Java identifier that specifies the name of the class to be defined.
The Main Line
The third line
public static void main(String args[])
Defines a method named main.Every Java application program must include the main() method.This
is the starting point for the interpreter to begin the execution of the program.A Java application can
have any number of classes but only one of them must include a main method to initiate the
execution.
This line contains a number of keywords:public,static and void.
public:the keyword public is an access specifier that declares the main method as unprotected and
therefore making accessible to all other classes.
static:which declares this method as one that belongs to the entire class and not a part of any objects
of the class.The main method must always be declared as static since interpreter uses this method
before any objects are created.
void:The type modifier void states that the main method does not return any value.
The Output Line
The only executable statement in the program is
System.out. println(“Welcome to Java Programing”);
This is similar to the printf() statement in C.Since Java is a true object oriented
language,every method must be part of an object.The println method is a member of
the out object,which is a static data member of System class.
The method println always appends a newline character to the end of the string.This
means that any subsequent output will start on a new line.Every Java statement
must end with a semicolon.
Java Program Structure
Documentation Section
The documentation section comprises a set of comment lines giving the name of the
program,the author and other details,which the programmer would like to refer to at
a later stage.Comments must explain why and what of classes and how of
algorithms.

There are three types of comments:

1.single line comment (//).

2.multiline comments(/*....*/)

3.documentation comment(/**.......*)
Package Statement
The first statement allowed in a Java file is a package statement.This statement
declares a package name and informs the compiler that the classes defined here
belong to this package.

Example:package student;

The package statement is optional.Our classes do not have to be part of package.


Import Statements

Import statements are similar to the #include statement in C.Example:

import java.io.*;

This statement instructs the interpreter to load the all classes contained in io package.

Using import statements,we can have access to classes that are part of other named packages.

Interface Statements

An interface is like a class but includes a group of method declarations.

Class Definitions

A Java program may contain multiple class definitions.Classes are the primary and essential elements of a Java
program.The number of classes used depends on the complexity of the program.

Main Method Class

Java standalone program requires a main method as it starting point.The main method creates objects of various classes
and establishes communication between them.On reaching the end of main,the program terminates and the control
passes back to the operating system.
Data Types
Every variable in Java has a data type.Data type specify size and types of values
that can be stored. Data types in Java

Primitive or Intrinsic Non-Primitive(Derived)

Numeric Non-numeric Classes Arrays

Floating-
Integer point Interface

Character Boolean
Integer Types:Integer types can hold whole numbers such as 123,-96 and 5639.

The size of the values that can be stored depends on the integer data type.Java
supports four types of integers.

Integer

Byte Long

Short INT
Floating PointTypes
Floating Point types to hold numbers containing fractional part such as 27.59.There
are two kinds of floating point storage in Java:
Floating Point

Float(Single-precision Double(double
Numbers) precision numbers)
Character Type

In order to store character constants in memory,Java provides a character data type


called char.The char type assumes a size of 2 bytes.

Boolean Type

Boolean type is used when we want to test a particular condition during the
execution of the program.There are only two values that a boolean type can
take:true or false.Boolean type is denoted by the keyword boolean and uses only one
bit of storage.
Declaration of Variables
In java,variables are the names of storage locations.After designing suitable variable
names,we must declare them to the compiler.Declaration does three things:
1.It tells the compiler what the variable name is.
2.It specifies what type of data the variable will hold.
3.The place of declaration decides the scope of the variable.
A variable must be declared before it is used in the program.Variable can be used to store
a value of any data type.
General Syntax:
type variable1,variable2…………………..variableN;
Examples:int count;
Float x,y;
Type Casting
Type casting is helpful in situations where there is a need to store a value of one
type into a variable of another type.If the two types are compatible,then Java will
perform the conversion automatically.

Example:It is always possible to assign an int value to a long variable.

However,not all types are compatible,and thus not all type conversions are implicitly
allowed.For instance,there is no automatic conversion defined from double to byte.

Fortunately,it is still possible to obtain a conversion between incompatible types.


Java’s Automatic Conversions
When one type of data is assigned to another type of variable,an automatic type
conversion will take place if the following two conditions are met:

1.The two types are compatible.

2.The destination type is larger than the source type.


Casting Incompatible types:
For example,if you want to assign an int value to a byte variable,the conversion will not be performed
automatically,because a byte is smaller than an int.This kind of conversion is sometimes called a
narrowing conversion,since you are explicitly making the value narrower so that it will fit into the
target type.

To create a conversion between two incompatible types,you must use a cast.A cast is simply an
explicit type conversion.

Syntax is :

type variable1=(type)variable2;

This process of converting one data type to another is called casting.

Example:

int a;

byte b;

b=(byte)a;
Arrays
An array is a group of contiguous or related data items that share a common name.
For example,we can define an array name salary to represent a set of salaries of a group of employees.A
particular value is indicated by writing a number called index number or subscript in brackets after the array
name.
For example:salary[10];
Represents the salary of the 10th employee.The complete set of values is referred to as an array,the
individual values are called elements.
The ability to use a single name to represent a collection of items and to refer to an item by specifying the
item number enables us to develop concise and efficient programs.
Creating an Array
Arrays must be declared and created in the computer memory before they are used.

Three steps are involved in creating an array:

1.Declaring an array

2.Creating memory locations.

3.Putting values into the memory locations.


Declaration of Arrays
Arrays in Java may be declared in two forms:

1.type arrayname[];

2.type [] arrayname;

Example:

int number[ ];

int [ ] marks;
Creation of Arrays
After declaring an array,we need to create it in the memory.Java allows us to create
arrays using new operator.

Syntax:

arrayname=new type[size];

Example:

number=new int[5];
Initialization of Arrays
The final step is to put values into the array created.This process is known as
Initialization.

Syntax:

arrayname[subscript]=value;

Example:

number[0]=35;

number[1]=40;

Java creates arrays starting with the subscript of 0 and ends with a value one less than
the size specified.
We can also initialize arrays automatically in the same way as the ordinary variables
when they are declared as shown below:

type arrayname[ ]={list of values};

Example:

int number[ ]={35,40,20,57,19};

The array initializer is a list of values separated by commas and surrounded by curly
braces.No arraysize is specified.The compiler allocates enough space for all the
elements specified in the list.
Two-dimensional Arrays
There are some situations where table of values will have to be stored.

We can think of this table as a matrix consisting of rows and columns.

In mathematics we can represent a particular value in a matrix by using two


subscripts such as vij.Here v denotes the entire matrix and vij refers to the value in
the ith row and jth column.

Two dimensional arrays are stored in memory as below:


Creating Two-dimensional arrays:
For creating two dimensional arrays,
Syntax:
type arrayname[ ][ ];
arrayname=new type[size][size];
Example:
int myArray[ ][ ];
myArray=new int[3][4];
Or
int myArray[ ][ ]=new int[3][4];
Two dimensional arrays may be initialized by following their declaration with a list
of initial values enclosed in braces:

Example:

int table[2][3]={0,0,0,1,1,1};

Initializes the elements of the first row to zero and the second row to one.The
initialization is done row to row.
Multidimensional Arrays
Java treats multidimensional array as “arrays of arrays”.

Example:

int x[ ][ ]=new int[3][];

x[0]=new int[2];

x[1]=new int[4];

x[2]=new int[3];
Operators:
Java supports a rich set of operators.
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Java Operators are classified into a number of related categories:
1.Assignment Operators.
2.Comparison Operators.
3.Bitwise Operators.
4.Arithmetic Operators.
5.Shifting Operators.
Arithmetic Operators:
Arithmetic operators are used to construct mathematical expressions.

Arithmetic operators are used as shown below:

a-b a+b

a*b a/b

a%b -a*b

Here a and b may be variables or constants and are known as operands.


Integer Arithmetic

When both the operands in a single arithmetic expression such as a+b are integers,the expression is called an
Integer expression and the operation is called integer arithmetic.Integer arithmetic always yields an integer
value.

Real Arithmetic

An arithmetic operation involving only real operands is called real arithmetic.

A real operand may assume values either in decimal or exponential notation.

Mixed-Mode Arithmetic:

When one of the operands is real and the other is integer,the expression is called a mixed-mode arithmetic
expression.

Example:

15/10.0 produces result 1.5

15/10 produces the result 1


Assignment Operators:
Assignment Operators are used to assign the value of an expression to a variable.

Java has a set of ‘shorthand’ assignment operators which are used in the form

v op=exp;

Example: x+=y;
Comparison Operators(Relational Operators)
We can compare two quantities and depending on their relation,take certain
decisions.

For example,we may compare the age of two persons or the price of two items.These
comparison are done with the help of relational operators.

Java Supports 6 relational operators in all.


Operator Meaning

< Is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal to

== Is equal to

!= Is not equal to
Bitwise Operator
Bitwise operators are used for manipulating of data at values of bit level.

These operators are used for testing the bits, or shifting them to the right or left.
Operator Meaning

& Bitwise AND

! Bitwise OR

^ Bitwise exclusive OR

~ One’s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill


Shifting Operators
The Java programming language also provides operators that perform bitwise and bit shift operations on integral
types.
Control Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear.
Control flow statements, however, break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks of code.

The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true.
void applyBrakes() {

// the "if" clause: bicycle must be moving

if (isMoving){

// the "then" clause: decrease current speed

currentSpeed--;

}
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You
could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when
the bicycle is not in motion.
void applyBrakes() {

if (isMoving) {

currentSpeed--;

} else {

System.err.println("The bicycle has already stopped!");

}
Switch Statement
The switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primit ive data
types.

A built- in multiway decision statement known as switch,which tests the value of a given variable.

switch(expression)

case value-1:

block-1

break;

case value-2:

block-2

break;

---------------

----------------

default:

Default-block

break;

}
Decision Making and Looping
A computer is well suited to perform repetitive operations.It can do it tirelessly for
10,100 and even 10000 times.Every computer language must have features that
instruct a computer to perform such repetitive tasks.The process of repeatedly
executing a block of statements is known as looping.The statements in the block may
be executed any number of times from zero to infinite number.
In looping,a sequence of statements are executed until some conditions for the
termination of the loop are satisfied.A program loop therefore consists of two
segments,one known as the body of the loop and the other known as the control
statement.The control statements tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop,a control structure may be
classified either as the entry-controlled loop or as exit-controlled loop.
In the entry-controlled loop,the control conditions are tested before the start of the loop
execution.If the conditions are not satisfied,then the body of the loop will not be executed.
In the case of an exit-controlled loop,the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
A looping process,would include the following four steps:
1.Setting and initialization of a counter.
2.Execution of the statements in the loop.
3.Test for a specified condition for execution of the loop.
4.Incrementing the counter.
The Java language provides for three constructs for performing loop operations.

They are:

1.While construct.

2.do construct.

3.for construct.
While statement
The simplest of all the looping structures in Java is the while statement.The basic format of the while statement is

Initialization:
while(test condition){
Body of the loop

}
The while os an entry-controlled loop statement.The test condition is evaluated and if the condition is true,then the
body of the loop is executed.After execution of the body,the test condition is once again evaluated and if it is
true,the body is executed once again.This process of repeated execution of the body continues until the test
condition finally becomes false and the control is transferred out of the loop.On exit,the program continues with
the statement immediately after the body of the loop.
The body of the loop may have one or more statements.The braces are needed only if
the body contains two or more statements.However,it is a good practice to use braces
even if the body has only one statement.

2.do statement.

The while loop construct makes a test condition before the loop is
executed.Therefore,the body of the loop may not be executed at all if the condition is
not satisfied at the very first attempt.

One some occasions,it might be necessary to execute the body of the loop before the
test is performed.Such situations can be handled with the help of the do statement.
General Syntax:
Initialization;
do
{
Body of the loop
}while(test condition);
On reaching the do statement,the program proceeds to evaluate the body of the loop
first.At the end of the loop,the test condition in the while statement is evaluated.If the
condition is true,the program continues to evaluate the body of the loop once
again.This process continues as long as the condition is true.When the condition
becomes false,the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
Since the test condition is evaluated at the bottom of the loop,the do….while
construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.
3.For statement.
The for loop is another entry-controlled loop that provides a more concise loop
control structure.The general form of the for loop is
for(initialization;test condition;incr/decr)
{
Body of the loop
}
The execution of the for statement is as follows:
1.Initialization of the control variables is done first,using assignment statements such as
i=1 or count =0.The variables i and count are known as loop-control variables.
2.The value of the control variable is tested using the test condition.The test condition is
a relational expression,such as i<10 that determines when the loop will exit.If the
condition is true,the body of the loop is executed,otherwise the loop is terminated and the
execution continues with the statement that immediately follows the loop.
3.When the body of the loop is executed,the control is transferred back to the for
statement after evaluating the last statement in the loop.Now,the control variable is
incremented using an assignment using an assignment statement such as i=i+1 and the
new value of the control variable is again tested to see whether it satisfies the loop
condition.If the condition is satisfied,the body of the loop is again executed.This process
continues till the value of the control variable fails to satisfy the test condition.

You might also like