Unit I Introducation and Overview Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Tutorial 1
Introduction to Java

Java History
• Java is a general purpose, object oriented programming language developed by Sun Micro-
system of USA in 1991.

• Originally called as “Oak” by James Gosling.

• Java was designed for the development of software for consumer electronic devices like TVs,
VCRs, such other electronic device.

Java Milestones

• 1990: Sun Microsystems decided to develop special software that could be used to manipulate
consumer electronic devices. A team of Sun Microsystems programmers headed by James
Gosling was formed to undertake this task.

• 1991 : After exploring the possibility of using the most popular object-oriented language C++,
the team announced a new language named “Oak”

• 1992: The team, known as Green project team by Sun Micro-system, demonstrated the
application of their new language age to control a list of home appliances using a hand-held
device with a tiny touch- sensitive screen.

• 1993: The WWW appeared on the internet and transformed the text-based internet into a
graphical-rich environment. The Green project team came up with the idea of developing
Web applets using the new language that could run on all types of computers connected to
Internet.

• 1994: The team developed a web browser called “HotJava” to locate and run applet programs
on Internet. HotJava demonstrated the power of the new language, thus making it instantly
popular among the internet users.

• 1995: Oak was renamed “JAVA”, due to some legal problem. Java is just a name and is not an
acronym. Many popular companies including Netscape and Microsoft announced their
support to java.

• Java coffee refers to coffee beans produced in the Indonesian island of Java

• 1996: Java established itself not only as a leader for internet programming but also as a
general-purpose, object-oriented programming language.Sun releases Java Development Kit
1.0

• 1997:Sun RELEASES Java Development Kit 1.1 (JDK1.1)

• 1998:Sun releases the JAVA 2 with version 1.2 of the software Development Kit (SDK 1.2)

Mr. S V Deshmukh 2022-23 Page 1


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

• 1999:Sun releases JAVA 2 platform, Standard Edition(J2SE) and Enterprise Edition(J2EE)

• 2000:J2SE With SDK 1.3 was released.

• 2002:J2SE with SDK 1.4 Was released.

• 2004:J2SE with JDK 5.0 (instead of JDK 1.5) was released, This is known as J2SE5.0

JAVA FEATURES

• The inventors of java wanted to design a language which could offer solutions to some of the
problems encountered in modern programming.

• They wanted the language to be not only reliable, portable and distributed but also simple,
compact and interactive.

Features of JAVA Programming

1. Compiler and interpreter

- Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making java a two stage system.
- First, Java compiler translates source code into what is known as byte-code instruction.
Byte-code are not machine instructions and therefore, In second stage, java interpreter
generates machine code that can be directly executed by the machine that is running the
java program. Thus, we can say that java is both a compiled and interpreted language.

2. Platform- Independent and portable

- The most significant contribution of java over other language is its portability.
- Java program can be easily moved from one computer system to another, anywhere and
anything. Changes and upgrades in operating systems, processors and system resources
will not force any changes in java programs.
- This is the reason why java has become a popular language for programming on internet
which interconnects different kind of systems worldwide.
- We can download a java applet from a remote computer onto our local system via internet
and execute it locally.

Java ensures portability in two ways:

- First, java compiler generates byte-code instructions that can implemented on any
machine.
- Secondly, the size of the primitive data types is machine independent.

3. Object- oriented

Mr. S V Deshmukh 2022-23 Page 2


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

- 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. Such packages, we can
use in our programs by using inheritance.

4. Robust (Strong) and secure

- Java is a robust (strong/healthy) language. It provides many safeguards to ensure reliable


code.
- It has strict compile time and run time checking for data types.
- It is designed as a garbage – collected language relieving the programmer virtually all
memory management problems.
- Java also incorporates the concept of exception handling which captures series errors and
eliminates any risk of crashing the system.
- Security becomes an important issues for a language that is used for programming on
internet. Threat of viruses and abuse of resources are everywhere. Java systems not only
verify all memory access but also ensure that no viruses are communicated with an applet.
- The absence of pointers in java ensures the programs cannot gain access to memory
locations without proper authorization.

5. Distributed

- Java is designed as a distributed language for creating applications on network. 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.

6. Familiar, simple and small

- Java is small and simple language. Many features of C and C++ that are either redundant
or sources of unreliable code are not part of java.
e.g. Java does not use pointer, preprocessor header files, goto statement and many more.
- It also eliminates operator overloading and multiple inheritance.

7. Multithreaded and Interactive

- Multithreaded means handling multiple tasks simultaneously. Java support


multithreaded programs. This means that we need not wait for the application to finish
one task before beginning another.
- This feature greatly improves the interactive performance of graphical applications.
- The java runtime comes with tools that support multi-process synchronization and
construct smoothly running interactive system.

8. High performance

Mr. S V Deshmukh 2022-23 Page 3


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

- Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte-code. According to sun, java speed is comparable to the native C/C++.
- Java architecture is also designed to reduce overheads during runtime.
- Further, the incorporation of multi treading enhances the overall execution speed of java
programs.

9. Dynamic and Extensible

- Java is a dynamic language.


- Java is capable of dynamically linking in new class libraries, methods, and objects.
- Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.
- Java program support functions written in other languages such as C and C++. These
functions are known as native methods. This facility enables the programmers to use the
efficient functions available in these languages
- Native methods are linked dynamically at runtime.

10. Easy of Development

- Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, Enhanced for loop,
autoboxing or unboxing, type safe enums, static import and annotation(footnote). These
features reduce the work of the programmer by shifting the responsibility of creating the
reusable code to the compiler.
- The resulting source code is free from bugs because the errors made by the compiler are less
when compared to those made by programmers.

11. Scalability and Performance

- J2SE 5.0 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.
For example,
The introduction of the class, data sharing in the Hotspot JAVA VIRTUAL MACHINE (JVM)
improves the startup time by loading the core classes from the jar files into a shared
archive.
- Memory utilization is reduced by sharing data in the shared archive among JVM
processes.

12. Monitoring and Manageability

- Java supports a number of APIs, such as JVM monitoring and Management API, Sun
management platform Extension, Logging, Monitoring and management interface and
Java Management Extension(JMX) to monitor and manage java applications.
- Java provides tools, such as jconsole, jps, jstat, and jstated use of monitoring and
management facilities.
- For example: GUI based tool called jconsole is used to monitor the JVM.

Mr. S V Deshmukh 2022-23 Page 4


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

13. Desktop client

- J2SE 5.0 provides enhanced features to meet the requirements and challenges of java
desktop user. It provides an improved swing look and feel called ocean.
- This feature is mainly used for developing graphics applications that require OpenGL
hardware acceleration.

14. JDBCRowset

- Java support JDBC Rowset to sent data in a tabular format between the remote
components of a distributed enterprise applications.

How Java Differs from C++

JAVA C++
Object Oriented issues
1 Pure object oriented language Hybrid between procedural and object-
oriented.
2 All methods are part of a class Can have stand alone methods
3 Does not support multiple inheritance. Support multiple inheritance.
4 Does not support operator overloading Support Operator overloading.
5 No parameterized type Templates as parameterized type.
6 No default arguments Function parameters can take default
values.
7 All methods are dynamically bound. Only virtual functions are dynamically
bound.
8 Objects are passed to methods only by Objects can be passed to functions by
reference. value or reference
Pointers, Arrays and Strings
9 No explicit pointer manipulation and Support pointers, with dereferencing ( *
no pointer arithmetic. or ->) and address ( & ) operators.
10 Array references are not translated to Array references translate to pointer
pointer arithmetic. arithmetic.
Array lengths in multidimensional Array lengths have same sizes in
arrays can vary from one element to the multidimensional arrays.
next within one dimension.
Bound checking is done on arrays No bound checking on arrays
Strings are objects Strings are null terminated character
arrays.
Built in string concatenation operator All string operations are performed
(+). using functions
Special features
Automatic garbage collection No automatic garbage collection
Compiled and interpreted. Compiled
Architecture neutral. Architecture specific.

Mr. S V Deshmukh 2022-23 Page 5


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Supports interfaces. Does not have interfaces.


Supports multithreading. Does not have support for
multithreading.
Supports web based applications ( Does not provide built in support for
Applet, servlet and JSP ) distributed most of these features.
applications (socket, RMI, etc) and
network protocols (HTTP, TCP/IP, etc)
with the help of extensive standardized
APIs.
General issues
No preprocessor. Heavy reliance on preprocessor.
Command line arguments don’t Command line arguments include the
include the program name. program name.
Main method cannot return a value. Main function can return a value.
No forward referencing required. Explicit forward referencing required.
No typedef. Support typedef.
No structure and unions Support structures and unions.
Java provides documentation Only two styles of comments are
comments in addition to C/C++ style supported.
comments.

JAVA VIRTUAL MACHINE


• Java compiler translates source code into intermediate code known as bytecode for a
machine that does not exist. This machine called as Java virtual machine.
• It is a simulated computer within the computer and does all major functions of a real
computer.
• The process compiling a java program into bytecode which is also referred to as virtual
machine code.

Java Java Virtual


Program compiler machine
Source code Bytecode
Process of compilation
• The bytecode is not machine code

• Java interpreter act as an intermediary between the virtual machine and the real
machine.

Remember that the interpreter is different for different machines.

Mr. S V Deshmukh 2022-23 Page 6


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Bytecod Java Machine


e Interpret code
Virtual machine Real Machine
Process of converting bytecode into
machine code
The java object framework (Java API) acts as the intermediary between the user
programs and the virtual machine which in turn acts as the intermediary between the
operating system and the java object framework.

Java Virtual machine


RealFramework
Java object machine (API)
Compiler Interpreter
User Application programs

User
Layers of interactions for java programs
JAVA PROGRAM STRUCTURE
A java program may contain many classes of which only one class defines a main method.
Classes contain data members and methods that operate on the data members of the class.
Methods may contain data type declarations and executable statements.

Documentation Section
Suggested
Package Statement
Optional
Import Statement
Optional
Interface Statement
Optional
Class definition
Optional
Main method class {
Essential
Main method definition

}
Mr. S V Deshmukh 2022-23
Fig. General structure of a Java Program Page 7
Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

1. 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. Comment must explain why, and what of classes
and how of algorithms. Java uses three type of comments from these two
comments are already observed in C and C++. i.e single line ( // ) and Multiline
comment (/* */). Java also uses a third style of comment /** …..*/ known as
documentation comment.

2. 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. Package statement is optional.

3. Import statement
An import statements are similar to the #include statement in C. This
statement instructs the interpreter to load the given class. Using import
statements, we can have access to classes that are part of other named
packages.

4. Interface statements
An interface is like a class but includes a group of method declarations. This is
also an optional section and is used only when we wish to implement the
multiple inheritance feature in the program.

5. Class definitions
A java program may contain multiple class definition. Classes are the primary
and essential of a java program. These classes are used to may the objects of
real- world problems. This is also optional.
6. Main method class
Every Java stand – alone program requires a main method as its starting point,
this class is the essential part of a java program.

JAVA ENVIRONMENT
• Java environment include a large number of development tools and hundreds of
classes and methods.

Mr. S V Deshmukh 2022-23 Page 8


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

• The development tools are part of the system known as JAVA DEVELOPMENT KIT(JDK)
and the classes and methods are part of the JAVA STANDARD LIBRARY(JSL), also known
as the Application programming interface (API)

The is not just a programming language. It is a complete technology. The Java


technology contains:

7. A programming language
8. A development Environment
9. An application Environment
10.A deployment Environment
11.Integration libraries
1. A programming Language
It is an object oriented programming language which requires both, a
compiler and an interpreter. The compiler first translates a program into
an intermediate code called Java bytecode. Java bytecodes are the
platform independent codes for the JVM. They are interpreted by the
interpreter on the Java platform.
Compilation occurs just once; interpretation occurs each time.

2. A development Environment
The java development tools provide the programmer everything that is
needed for compiling, running, monitoring, debugging, and documenting
application.

3. An application Environment
The API(Application programming interface) provides the core
functionality of the Java programming language. It offers a huge collection
of useful classes which can be directly used in application.

4. A deployment Environment
The java technology provides standard mechanisms such as Java Web
start and Java Plug-in for deploying applications to end users.

5. Integration Libraries
Integration libraries such as Java DataBase Connectivity (JDBC) API, Java
Naming and Directory Interface (JNDI) API, Java Remote Method
Mr. S V Deshmukh 2022-23 Page 9
Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Invocation (RMI), Java Messaging Service ( JMS) enable communication


between database, heterogeneous, remote or distributed objects.

The JAVA Platform

A platform is the hardware or software environment in which a program runs.


Most platforms can be described as a combination of the operating system and
hardware.

The java platform has two components:

1. The Java Virtual Machine (JVM)


2. The Java Application programming Interface( Java API)

The JAVA Virtual Machine is the base for the java platform and is ported onto
various hardware-based platforms. The Phrase “Write once, run anywhere” is
used with java program. The platform independence of java is possible due to
the JVM. The java compiler is used to compiles the source code and generate
bytecode, which can be interpreted by a suitable JVM on any platform.

The JAVA API is a large collection of ready made software components that
provide many useful capabilities, such as Graphical User Interface(GUI), event
handling, I/ O, file handling, networking etc.

Java comes in three editions:

1. Java Standard Edition


2. Java Enterprise Edition
3. Java Micro Edition
The standard edition is used to develop stand-alone, client-side application or
applets. The Enterprise Edition is used to develop server-side programs, servlets
and distributed applications. For developing mobile applications(midlets) and
wireless application, the Micro Edition is used.
JAVA DEVELOPMENT KIT
The java development kit comes with a collection of tools that are used for developing
and running JAVA Programs. They include:

 Appletviewer ( for viewing java applets)


Enables use to run java applets (without actually using a java compatible browser)
 Java
Mr. S V Deshmukh 2022-23 Page 10
Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Java interpreter, which runs applets and applications by reading and interpreting
bytecode files.
• Javac
The java compiler, which translate java source code to byte-code files that the
interpreter can understand.
• Javadoc
Creates HTML format documentation from java source code files.
• Javah
Produces header files for use with native methods.
• Javap
Java disassembler, which enables us to convert bytecode files into a program
description.
• Jdb : Java debugger, which helps us to find errors in our programs.
Text Editor

Java Source code Javadoc HTML files

Javac

Java class file Javah Header Files

Java Jdb

Java Program Process of building and running


output java application program

• The way these tools are applied to build and run application programs. 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 jdb is used to find errors, if any in the source code.

• A compiled java program can converted into a source code with the help of java
disassembler javap.

We can develop two types of java programs:


1. Stand-alone applications
2. Web applets

Mr. S V Deshmukh 2022-23 Page 11


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Jav
a
Java compiler

Apple Applicati
t Type on Type
Java Java
enable Interp
Output Output
Two ways of using java

Installing Java
To install java, we need to perform the following steps:
1. Double click the .exe file to initiate the installation procedure. The welcome screen
appears.
2. The welcome screen shows the licensing terms and conditions. Click the Accept
button to begin java installation. The progress screen appears.
3. The progress screen depicts the percentage of installation that has been completed.
Once the installation is complete, the complete screen appears.
4. The complete screen show the successful installation. Click the Finish button.

Configuring Java
Once java is installed, we need to configure it by adding the Java Path to the environment
variable, PATH.
To set the PATH variable to the java directory, we need to perform the following steps:
1. Right click on the My Computer icon and select the Properties option from the
dropdown menu.
2. Select the advanced tab to display the advance tab page.
3. Click the Environment variables button to display the Environment variables dialog
box,
4. The Environment variables dialog box is divided into two section-User Variable and
System variable. Under the System variables section, select the Path option below

Mr. S V Deshmukh 2022-23 Page 12


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

the variable column and Click the Edit button. The Edit system Variable dialog box
appears.
5. By default, the PATH variable is already set to multiple locations. To set the Java
directory path to the Path variable, append the directory path in the Variable value
text box, separated by a semi-colon.
6. Click OK to close the Edit system Variable dialog box.
7. Click Ok to close the Environment Variable Dialog box.
8. Click OK to close System Properties dialog box and complete the process of
configuring Java.

Types of Comments

There are three types of comments defined in java.

1. Single Line
- The Single line comment begins with a //. It is used in application program.

2. Multiline
- The Multiline comment begins with a /* and end with a */. It is used in application program.

3. Documentation comment
- This type of comment is used to produce an HTML file that documents your program.
- The documentation comment begins with a /** and ends with a */.
- Documentation comments allow you to embed information about your program into the
program itself.
- You can then use the javadoc utility program to extract the information and put it into an HTML
file.
- Documentation generated with javadoc, because that is the way the Java API library was
documented by Sun.
General form of a documentation comment
After the beginning /**, the first line or lines become the main description of your class,
variable, or method. After that, you can include one or more of the various @tags. Each @tag
must start at the beginning of a new line or follow an asterisk( * ) that is at the start of a line.
Multiple tags of the same type should be grouped together.
For example:
If you have three @see tags, put them one after the other.
/**

* This class draws a bar chart.

*@author Herbert Schildt

* @version 3.2
*/

Tokens

Mr. S V Deshmukh 2022-23 Page 13


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

- A Java program is basically a collection of classes.


- A class is defined by a set of declaration statements and methods containing executable
statements.
- Most statements contain expressions, which describe the actions carried out on data.
- Smallest individual units in a program are known as tokens.
- The compiler recognizes them for building up expressions and statements.
- A Java program is a collection of tokens, comments and white spaces. Java language
includes five types of tokens.

They are:

1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Variable
7. Datatypes

Keywords ( Reserved Words):

- Keywords are essential part of a language definition. They implements specific features of
language. Java language has reserved words, these keywords combined with operators and
separates according to syntax, from definition of the java language.
- Java language has reserved 50 words as keywords.
- Since keywords have specific meaning in java, we cannot use them as names for variables,
classes, methods and so on. All keywords are to be written in lower case letters.

abstract continue for new switch


assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

Note: we should also not attempt to use the Boolean values true and false or null as names in our
program.

Identifiers:
- Identifiers are programmer-designed tokens.
- They are used for naming classes, methods, variables, objects, labels, packages and
interfaces in a program.

Mr. S V Deshmukh 2022-23 Page 14


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Example: average, sum, length etc.


Java identifiers follow the following rules:
1. They can have alphabets, digits and the underscore and dollar sign characters.
2. Type must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.

Literals:

- Literals in java are a sequence of characters (digits, letters and other characters) that
represent constant values to be stored in variables.
Java language specifies five major types of literals. They are:

 Integer literals
 Floating point literals
 Character literals
 String literals
 Boolean literals

Data Types
Every variable in Java has data type. Data types specify the size and type of value that can be stored.
Java define eight simple types of data: byte, short, int, long, char, float, double and boolean.
These can be put in four groups:

Integers: This group includes byte, short, int and long, which are for whole valued signed
numbers.

Floating-point numbers: This group include float, double, which represent numbers with
fractional precision.

Characters: This group includes char, which represents symbols in a character set, like letters and
numbers.

Boolean: This group included boolean, which is a special type for representing true/false values.

Mr. S V Deshmukh 2022-23 Page 15


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

 Integers
Java defines four integer types: byte, short, int and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. The width and ranges of
these integer types is shown below:

DataType Size Default


(Bytes) Values
Byte 8 0 -128 to 127
Short 16 0 -32768 to 32767
Integers Int 32 0 -2147483648 to 2147483647
Long 64 0L -9223372036854775808 to
9223372036854775808
Floating-point Float 32 0.0f 1.4e-045 to 3.4e+038
numbers
double 64 0.0d 4.9e-324 to 1.8e+308

Characters char 2 Null 0 to 65,536


Character
Booleans boolean 2 False
Reference reference null

Name Width Range

Long: 64 -9, 223, 372, 036,854,775,808 to 9,223,372,036,854,775,807


Int: 32 -2, 147, 483, 648 to 2,147,483,647
Short: 16 -32,768 to 32,767
Byte: 8 -128 to 127
For example the following statement declare variables of byte, short, int and long data type.

byte b,c;

short s;

int a;

long seconds;

 Floating-point numbers
Floating-point numbers also known as real numbers, are used when evaluating expressions that
require fractional precision. There are two kinds of floating-point types, float and double, which
represent single and double-precision numbers, respectively. The width and ranges are shown here:

Name Width Range


double 64 4.9e-324 to 1.8e+308

float 32 1.4e-045 to 3.4e+038

Example: float hightemp,lowtemp;

Mr. S V Deshmukh 2022-23 Page 16


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

double pi=3.1416;
 Characters
In Java, the data type used to store characters is char. In C/C++, char is an integer type that is 8
bits wide. This is not the case in Java. Instead, Java uses Unicode to represent character. Unicode
defines a fully international character set that can represent all of the characters found in all human
languages. Some human languages have more than 256 characters such as Chinese and Japanese.
To represent this character it requires 16 bits. Thus in Java chars a 16-bit type. The range of char
is 0 to 65,536. there are no negative chars.

Example: char ch,ch2;

ch = ’X’;

 Booleans
Java has simple type, called boolean, for logical values. It can have only one of two possible values,
true or false. This is the type returned by all relational operators, such as a<b.
Example:
boolean b;
b = true;
System.out.println(“ b is “ + b);
Standard Default Values
In Java, every variable has default value. If we don’t initialize a variable when it is first created,
Java provides default value to that variable type automatically as shown in table below:
Type of Variable Default value
byte zero : (byte) 0
short zero : (short) 0
int zero : 0
long zero : 0L
float 0.0f
double 0.0d
int zero : 0
char null character
boolean false
reference null

Separators:

Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code.

For example:

parentheses (), braces { }, brackets [], etc are separators

Variables and Dynamic Initialization


A variable is an identifier that denotes a storage location used to store a data value. In Java all
variables must be declared before they can be used. The basic form of a variable declaration is
shown here:

Mr. S V Deshmukh 2022-23 Page 17


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

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

The type is one of Java’s data type, or the name of a class or interface. The identifier is the name
of the variable. You can initialize the variable by specifying an equal sign and a value. To declare
more than one variable of the specified type, use comma-separated list.

Example:

int a, b, c; // declare three integers a, b, and c.

int d = 4, e, f = 8; // declare three int and initialize d and e.

byte z = 22; // initialize z

char ch = ‘X’;

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

For example,

double c = Math.sqrt( a * a + b ); // c is initialized dynamically

The Scope and Lifetime of Variables

- Java allows variables declared within any block. A block begins with an opening curly
brace and ended by a closing curly brace.
- A block defines a scope.
- Thus each time you start a new block, you are creating a new scope.
- A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
- Variable declared inside a scope is not visible (accessible) to code that is defined outside
that scope. Thus, when you declared a variable within a scope, you are localizing that
variable and protecting it from unauthorized access and/or modification.
- Scope can be nested.

For example,

Each time you create a block of code, you are creating a new, nested scope. When this occurs,
the outer scope encloses the inner scope. This means that objects declared in the outer scope
will be visible to code within the inner scope. However, the reverse is not true. Objects declared
within the inner scope will not be visible outside it. To illustrate the effect of nested scope,
consider the following program:

// Demonstrate block scope


class Scope {
public static void main(String args[ ])

Mr. S V Deshmukh 2022-23 Page 18


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

{
int x; //known to all code within main
x = 10;
if (x == 10 )
{ //start a new scope
int y=20; //known only to this block
// x and y both known here (continued)
System.out.println(“x and y : ” + x + “ ” + y);
}
// y = 100; // Error ! y not known here
// x is still known here
System.out.println(“x is : ” + x);
}
}

As the comments indicate, the variable x is declared at the start of main()’s scope and is accessible
to all subsequent code within main(). Within the if block, y is declared. Since a block defines a
scope, y is only visible to other code within its block. Within the if block, x can be used because
code within a block (that is, a nested scope) has access to variables declared by an enclosing scope.
Variables are created when their scope is entered, and destroyed when their scope is left. This
means that a variable will not hold its value once it has gone out of scope. Therefore variables
declared within a method will not hold their values between calls to that method. Also, a variable
declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is
confined to its scope. If a variable declaration includes an initialized, that variable will be
reinitialized each time the block in which it is entered. For example, consider the program given
below.

// Demonstrate life time of variable

class LifeTime

public static void main(String args[ ])

int x;

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

int y = -1; // y is initialized each time block is entered.

System.out.println(“y is : ” + y); // this always print -1

Mr. S V Deshmukh 2022-23 Page 19


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Y = 100;

System.out.println(“y is now : ” + y);

The output of this program is shown here:

y is : -1

y is now : 100

y is : -1

y is now : 100

y is : -1

y is now : 100

As you can see, y is always reinitialized to –1 each time the inner for loop is entered. Even though
it is subsequently assigned the value 100, this value is lost.

Operators and Expression


- Java supports a rich set of operators.
- An operator is a symbol that tells the computer to perform certain mathematical and
logical manipulation.
- An operator is a symbol that takes one or more arguments are operates on them to
produce a result.
- Operators are used in program to manipulate data and variables.

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


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Mr. S V Deshmukh 2022-23 Page 20


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Arrays
An array is a group of similar variables that are referred to by a common name. Arrays of any type
can be created and may have one or more dimensions. A specific element in an array is accessed
by its index. Arrays offer a convenient means of grouping related information.

1. One-Dimensional Arrays

A one-dimensional array is a list of similar variables. To create an array, you first must create an
arrayvariable of the desired type. The general form of one-dimensional array declaration is

type var-name[ ];

Here,

type declares the base type of the array. The base type determines the data type of each element
that comprises the array. Thus, the base type for array determines what type of data the array will
hold. For example, the following declared an array named month_days with the type “array of
int”:
int month_days[];
Although, this declaration establishes the fact that month_days is an array variables, no array
actually exist. In fact, the value of month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days. new is special operator that allocates memory.
The general
for of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
Ex : month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Furthermore all
elements in the array will be initialized to zero. It is possible to combine the declaration of the array
variable with the allocation of the arrays itself, as shown here:
int month_days[] = new int[12];
Once you have allocated an array, you can access a specific element in the array by specifying its
index within square brackets. All array indexes start at zero.
For example, this statement assigns the value 28 to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Arrays can be initialized when they are declared. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the values of the array elements.
The array will automatically be created large enough to hold the number of elements you specify
in the array initializer. There is no need to use new. For example to store the number of days in
each month,
the following code creates an initialized array of integers:

Mr. S V Deshmukh 2022-23 Page 21


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

class AutoArray {

public static void main(String args[ ]) {

int month_days[12] = {31, 28, 30, 31, 30, 31, 30, 31,

30, 31, 30, 31 };

System.out.println(“April has “ + month_days[3] + “days”);

}}

2. Arrays of Arrays

In Java multi-dimensional arrays are actually arrays of arrays. To declare multi-dimensional array
variable, specify each additional index using another set of square brackets. For example, the
following declares a two-dimensional array variable called twoD.

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

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix implemented as an array
of arrays of int. conceptually, this array will look like the one shown in figure below:

Right index determines column.

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

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

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

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

Left index Given int twoD[ ][ ] = new int [4][5]; //determines row

The following program numbers each element in the array from left to right, top to bottom, and
then display these values:

class twoDArray {

public static void main(String args[ ]) {

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

int i, j, k=0;

Mr. S V Deshmukh 2022-23 Page 22


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

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

for(j=0; j<5; j++) {

twoD[i][j] = k;

k++;

}}

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

for(j=0; j<5; j++){

System.out.println(twoD[i][j] + “ ” );

System.out.println( );

}}

This program generates the following output:

01234

56789

10 11 12 13 14

15 16 17 18 19

When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension. For example, the following code allocated memory for the first
dimension of twoD

when it is declared.

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

Alternative Array Declaration Syntax

There is second form that may be used to declare an array:

type[ ] var-name;

Mr. S V Deshmukh 2022-23 Page 23


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Here, the square brackets follow the type specifier, and not the name of the array variable.

For example,

The following two declarations are equivalent:

int month_days[ ] = new int[12];

int[ ] month_days = new int[12];

The following declarations are also equivalent:

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

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

Control Statements

Java’s Selection Statement


When a program breaks the sequential flow and jumps to another part of the code, it is called
branching. When the branching is based of a particular condition, it is known as conditional
branching. If branching takes place without any decision, it is known as unconditional branching.
Java language possesses such decision-making capabilities and supports the following statements
known as control or decision making statements.

1. if statements
2. switch statement
3. Conditional operator statement ( ? : Operator as discuss above )

if statements
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. Here is the general form of the if statement

if (test-expression) statement1;

It allows the computer to evaluate the expression first and then, depending on whether the value of
the expression (relation of condition) is ‘true’ or ‘false’, it transfers the control to a particular
statement. The if statement may be implemented in different forms depending on the complexity
of condition to be tested.

a) Simple if statement
b) If….else statement

Mr. S V Deshmukh 2022-23 Page 24


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

c) Nested if…else statement


d) else if ladder

i) Simple if statement
The general form of simple if statement is

if (test-expression)
{
statement-block;
}
statement-X;

The statement-block may be single statement or a group of statements. If the test-expression is true,
the statement-block will be executed; otherwise the statement-block will be skipped and the
execution will jump to the statement-X. For example:

if ( perc >= 35 )
result=”Pass”;
ii) The if..else statement
The general form of simple if statement is

if (test-expression) {
True-block statement(s);
}
else {
False-block statement(s);
}
statement-X;

If the test-expression is true, then the true-block statement(s) immediately following the if
statement, are executed; otherwise the false-block statement(s) are executed. In either case, either
true-block or false-block will be executed, not both. True block or false block may contain single
or multiple statement. For a single statement you don’t need to take curly braces.
int a, b;
// …..
if ( a< b)
a = 0;
else
b = 0;

iii) The nested if..else statement


When a series of decisions are involved, we may have to use more that one if…else statement in
nested form as follows.
if (test-condition1) {
if (test-condition1) {
statement1;
}
else {
statement2;
}
}
else {

Mr. S V Deshmukh 2022-23 Page 25


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

statement-3;
}
statement-X;
If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test. If the condition-2 is true, the statement-1 will be evaluated;
otherwise the statmenet-2 will be evaluated and then the control is transferred to the
statement-X.

class ElseDemo {
public static void main(String args[]) {
int a = 10, b = 30, c = 20;
System.out.println(“Largest Value is : “);
if ( a > b) {
if (a > c)
System.out.println(a);
else
System.out.println(c);
}
else {
if (c > b)
System.out.println(c);
else
System.out.println(b);
}
}
}

iii) The else if ladder


There is another way of putting its together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if. It takes the
following general form.

if (condition-1) {
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
………………….
else if (condition-n)
statement-n;
else
default-statement;
}
statement-X;
This construct is known as the else if ladder. The condition is evaluated from top to bottom (of the
ladder), downwards. As soon as the condition is found, the statement associated with it executed
and the control is transferred to the statement-X (skipping the rest of the ladder).

Mr. S V Deshmukh 2022-23 Page 26


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

When all the n conditions become false, then the final else containing the default-statement will
be executed. For example :

if ( mark > 79)


grade = “Honors”;
else if (marks > 59)
grade = “First Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 49)
grade = “Third Division”;
else
grade = “Fail”;
System.out.println(“Grade : ” + grade);

Switch statements

When one of the many alternative is to be selected, we can design a program using if statements to
control the selection. However, the complexity of such a program increases. The program becomes
difficult to read and follow. Java has built-in multiway decision statement known as a switch. The
switch statement test the value of a given variable (or expression) against a list of case value and
when a match is found, a block of statements associated with that case is executed. The general
form of the switch statement is shown below:

switch (expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
………………..
………………..
default:
default-block;
break;
}
statement-X;
The expression is an integer expression of characters. value-1, value-2, …… are constants or
constant expressions and are known as case labels. Each of these values should be unique within a
switch statement. block-1, block-2,…..are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks but it is important to note that case labels end
with a colon (:).
When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2, ……. If a case is found whose value matched with the value of the
expression, then the block of statements that follow the case are executed. The break statement at

Mr. S V Deshmukh 2022-23 Page 27


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

the end of each block signal the end of a particular case and causes an exit from the switch
statement, transferring the control to the statement-X following the switch.
The default is an optional case. When present, it will be executed it the value of the expression
does not match with any of the case values. If not present, no action takes place when all matched
fail and the control goes to the statement-X.
The break statement is optional. If you omit the break execution will continue on into the next
case. If is sometimes desirable to have multiple cases without break statements between them. For
example, consider the following program. As you can see, execution falls through each case until
a break statement for the end of the switch is reached.

class SwitchDemo {
public static void main(String args[ ] ) {
for(int I=0; I<12; I++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println(“i is less than 5”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println(“i is less than 10”);
break;
default:
System.out.println(“i is 10 or more”);
} break;
}
}

This program generate the following output:


i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more

Mr. S V Deshmukh 2022-23 Page 28


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

Iteration Statements (Looping)


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. The Java language provides for three constructs
for performing loop operations. They are:

1. The while statement


2. The do statement
3. The for statement

while
The general form of while statement is

Initialization
while (test-condition)
{
Body of the loop;
}

The while statement is an entry controlled loop. 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. Consider the following program:

class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
i = 1;
sum = 0;
while(i <= 10) {
sum = sum + i;
i++;
}
System.out.println(" Addition of numbers through 1...10 is : " + sum);
}}
The output of the program would be…..
Addition of numbers through 1...10 is : 55

do
As we know, in while loop a test the condition before the loop is executed. On some occasions it
might be necessary to execute the body of the loop before the test is performed. Such situation can
be handled with the help of the do statement. this takes the form:

Initialization
do

Mr. S V Deshmukh 2022-23 Page 29


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

{
Body of the loop;
}
while (test-condition);

On reaching 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. For example, in the following
program test condition is false in the first attempt, still loop is executed only once.

class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
i = 100;
sum = 0;
do {
sum = sum + i;
i++;
} while(i <= 10);
System.out.println(" Addition of numbers through 1...10 is : " + sum);
}
}
The output of the program would be…..
Addition of numbers through 1...10 is : 100

for

The for loop is another entry controlled loop that provides a simple loop structure. The general
form of the for loop is:

for (initialization; test-condition; increment)


{
Body of the loop;
}

The execution of the for statement is as follows :

1. Initialization of the control variables is done first, using assignment statement such as, i =
0. The variable i is known as loop-control variable.

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

Mr. S V Deshmukh 2022-23 Page 30


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

assignment statement such as i++ and the new value of the condition 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.

class CalcTotal {
public static void main(String args[ ] ) {
int i, sum;
sum = 0;
for(i = 1; i <= 10; i++)
sum = sum + i;
System.out.println(" Addition of numbers from 1to 10 is : " + sum);
}
}
The output of the program would be…
Addition of numbers from 1to 10 is : 55

Jump statement
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
Using break
In Java, the break statement has three uses. First, in a switch statement to terminate a statement
sequence. Second, it can be used to exit a loop. Third, it can be used a “civilized”
form of goto. By using break, you can force immediate termination of a loop, by passing the
conditional expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next statement
following the loop including infinite loops. The break statement can be used with any of Java’s
loop. When used inside a set of nested loops, the break statement will only break out of the
innermost loop. For example:

class BreakDemo {
public static void main(String args[ ]) {
for(int i = 0; i < 100; i++) {
if(i == 10) break; //terminate loop is I is 10
System.out.println(" i : " + i ) ;
}
System.out.println(" Loop Complete " ) ;
}
}
The output of the program would be..
i:0
i:1
.
.
.
i:9

Loop Complete

Mr. S V Deshmukh 2022-23 Page 31


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

The break statement an also be employed by itself to provide a “civilized” form of the goto
statement. Java does not have a goto statement. By using this form of break, you can break out of
one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any
block. The general for of the labeled break statement is shown here:

break label;

Here, label is the name of a label that identifies a block of code. When this form of break executes,
control is transferred out of the names block of code. To name a block, put a label at the start of it.
A label is any valid Java identifier followed by a color. For example, the following program shows
three nested blocks, each with its own label. The break statement causes execution to jump
forward, past the end of the block labeled second, skipping the two prinln() statements.

class BreakDemo {
public static void main(String args[ ]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break" ) ;
if(t) break second; //break out second block
System.out.println("This won’t execute " ) ;
}
System.out.println("This won’t execute " ) ;
}
System.out.println("This is after second block " ) ;
}
}
}

Simple program of Java

Consider the simple Java program

/* This is a simple Java program

call this file “ Example.Java”.

*/

class Example {

// Your program begins with a call to main().

public static void main(String args[ ]) {

Mr. S V Deshmukh 2022-23 Page 32


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

System.out.println(“This is a simple Java program.”);

 Compiling the Program


- The name of the source file should be Example.java . If program contain more than
one classes the name of the source file should name of the class within which you have
defined main() method.
- To compile the Example program, execute the compiler, javac, specifying the name
of the source file on the command line, as shown here:

C:\>javac Example.Java

- After compilation compiler will create .class file for each class. If program contain
more than one class, compiler will create separate .class file for each class. (in this
example compiler will create Example.class file, which contain Bytecode for
interpreter or JVM.

To actually run the program, you must use the Java interpreter, called java. To do so, pass the
class name Example as a command-line argument, as shown here:

C:\>java Example

When program is run, the following output is displayed.

This is a simple Java program.

- When you execute the Java interpreter as just shown you are actually specifying the name of
the class that you want interpreter to execute. It will automatically search for a file by that
name that has .class extension. If it finds the file, it will execute the code contained in the
specified class.

A closer look at the program

The program begins with the following lines:

/* This is a simple Java program call this file “ Example.Java”. */

This is multilane comment , and

// Your program begins with a call to main().

Mr. S V Deshmukh 2022-23 Page 33


Tutorial 1 : Introduction to Java BCA Sy COCSIT, Latur

This is single-line comment. Java also uses a third style of comment /** …. */ known as
documentation comment. This form of comment is used for generating documentation
automatically. The next line of code is shown here:

public static void main(String args[ ])

This line begins the main() method. This is the line at which program begin executing. All Java
application begins by calling main(). The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a class member is preceded by public,
then that member may be accessed by code outside the class in which it is declared. In this main()
must be declared as public, since it must be called by code outside of its class when the program
is started. The keyword static allows main() to be called without having to instantiate a particular
instance of the class. This is necessary since main() is called by the Java interpreter before any
objects are made. The keyword void simply tells the compiler that main() does not return a value.
In main() method there is only one parameter String args[] declares a parameter named args,
which is an array of String store character strings. In this case, args receives any command-line
arguments present when the program is executed. The next line of code is shown here. Notice that
it occurs inside main().

System.out.println(“This is a simple Java program.”);

This line output the string “This is a simple Java program.” followed by a new line on the screen.
In this statement System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console.

Mr. S V Deshmukh 2022-23 Page 34

You might also like