0% found this document useful (0 votes)
6 views23 pages

Unit I-Java Notes (New Syllabus)

The document provides an overview of programming with Java, focusing on Object-Oriented Programming (OOP) concepts, Java's evolution, features, and its relationship with the Internet and World Wide Web. It discusses the differences between procedural and object-oriented programming, Java's history, and its advantages such as portability, security, and ease of development. Additionally, it highlights the applications of OOP in various fields and the significance of Java in creating interactive web applications.

Uploaded by

jananippriya18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

Unit I-Java Notes (New Syllabus)

The document provides an overview of programming with Java, focusing on Object-Oriented Programming (OOP) concepts, Java's evolution, features, and its relationship with the Internet and World Wide Web. It discusses the differences between procedural and object-oriented programming, Java's history, and its advantages such as portability, security, and ease of development. Additionally, it highlights the applications of OOP in various fields and the significance of Java in creating interactive web applications.

Uploaded by

jananippriya18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

PROGRAMMING WITH JAVA

UNIT I NOTES

1. INTRODUCTION TO OOPS
1.1) Paradigms of Programming Languages
1.2) Basic concepts of Object Oriented Programming
1.3) Differences between POP(C) and OOP(Java)
1.4) Difference between c++ and Java
1.5) Benefits of OOPs
1.6) Application of OOPs.
2. JAVA EVOLUTION
2.1) Java History
2.2) Java Features
2.3) Java and Internet
2.4) Java and World Wide Web
2.5) Web Browsers
2.6) Java Environment
3. INTRODUCTION TO JAVA
3.1) Types of java program
3.2) Java Program Structure
3.3) Naming Conventions
3.4) Creating and Executing a Java program
3.5) Java Tokens
3.6) Java Character set
3.7) Java Statements
3.8) Java Virtual Machine (JVM)
3.9) Command Line Arguments
3.10) Comments in Java program.
1
JAVA NOTES UNIT - I

1. INTRODUCTION TO OBJECT ORIENTED PROGRAMMING


1.1) Paradigms of Programming Languages:

Programmers write instructions in various programming languages to perform their


computation tasks such as:
 Machine level Language
 Assembly level Language
 High level Language

Machine level Language :


Machine code or machine language is a set of instructions executed directly by a computer's central
processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an
ALU operation on a unit of data in a CPU register or memory.

Assembly level Language :


An assembly language (or assembler language) is a low-level programming language which is
converted into executable machine code by a utility program referred to as an assembler.

High level Language :


High-level language focuses more on the programming logic rather than the underlying hardware
components such as memory addressing and register utilization. Eg. C, C++, JAVA. The high-level
programming languages are broadly categorized in to two categories:
1) Procedure oriented programming(POP) language.
2) Object oriented programming(OOP) language.

1.2) Differences Between Procedure oriented (C) and Object oriented


programming:

a)Procedure-Oriented Programming:
In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing. The primary focus is on functions.

Characteristics of procedure-oriented programming are:


 Emphasis is on doing things (algorithms).
 Large programs are divided into smaller programs known as functions.
2
JAVA NOTES UNIT - I

 Most of the functions share global data.


 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

b) Object oriented programming:


The major motivating factor in the invention of object-oriented approach is to remove some
of the flaws encountered in the procedural approach. 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 function that operate on it, and protects it from accidental modification from outside
function.
Object oriented programming allows decomposition of a problem into a number of entities
called objects. Data and functions are built around these objects. The data of an object can be
accessed only by the functions associated with that objects. Functions of one object can access the
functions of other objects.

Characteristics of object oriented programming are:


 Emphasis is on data rather than Procedure
 Programs are divided into objects
 Data Structures are designed to characterize the objects
 Functions that operate on the data of an object are tied together in the data structure
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other through functions
 New data and functions can be added easily whenever necessary
 Follows bottom up approach in program design

1.3) Differences between C++ and JAVA:

 C++ was mainly designed for systems programming and Java was created initially to support
network computing.
 C++ supports pointers whereas Java does not pointers.
 At compilation time Java Source code converts into byte code. The interpreter execute this
byte code at run time and gives output. While C++ run and compile using compiler which
converts source code into machine level languages. so, C++ is platform dependent.
 Java is platform independent language but C++ depends upon operating system machine etc.
 Java uses both compiler and interpreter and C++ uses only compiler
3
JAVA NOTES UNIT - I

 C++ supports operator overloading and multiple inheritance but java does not support
operator overloading and multiple inheritance concepts.
 Java does not support all the complicated aspects of C++ (ex: Pointers, templates, unions,
structures etc.)
 Thread support is built-in in Java but not in C++.
 Internet support is built-in in Java but not in C++.
 Java does not support header files, #include library files just like C++. Java uses import
statements to include different Classes and methods.
 Java does not support default arguments like C++.
 Exception and Auto Garbage Collector handling in Java is different because there are no
destructors into Java.
 Java has method overloading, but no operator overloading just like C++.

1.4) Basic Concepts of Object Oriented Programming:

i) Objects:
Definition: Objects are the basic run time entities in an object oriented system. Object takes up
space in the memory and has an associated address. When a program is executed the objects
interact by sending messages to one another
Example:

ii) Class:
Definition: A class is a collection of objects of similar data types. They are user defined data
types. Once a class has been defined, we can create any number of objects belonging to that
class. Objects are variables of type class.
Example:
class fruit
{
-----
------
-----
} mango, grapes;

mango and grapes are the objects for the class fruit.

iii) Encapsulation:
Definition: The wrapping up of data and methods into a single unit called class 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.
Example:
class student
4
JAVA NOTES UNIT - I
{
int a,b;
public:
void sum();
}

iv) Data Hiding:


Definition: The insulation of the data from Direct Access by the program is called Data Hiding.
Example: private int a,b;

v) Data Abstraction:
Definition: Abstraction refers to the act of representing essential features without including the
background details or explanations.
Example: size, weight, cost etc.
size, weight, cost are called attributes or data members. Functions that operate on these data are
called methods or member functions.

vi) Inheritance:
Definition: Inheritance is a process by which objects of one class acquire the properties of objects
of another class. The concept of inheritance provides the idea of Reusability. we can add additional
features to an existing class without modifying it.
Example:

vii) Polymorphism:
Definition: Polymorphism means the ability to take more than one form. An operation may exhibit
different behaviours in different instances. The behaviour depends upon the types of data used in the
operation
Example:
 Addition of two numbers generates a sum (eg. 1+2=3)
 Addition of two strings generates a concatenation (eg. Sun + flower = sunflower)

viii) Dynamic Binding or Late Binding:


Definition: Binding refers to the linking of a procedure call to the code to be executed in response
to the call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.

ix) Message Passing:


Definition: An object-oriented program consists of a set of objects that communicate with each
other. It involves the following basic steps:
1. Creating classes that define object and their behaviour.
5
JAVA NOTES UNIT - I
2. Creating objects from class definitions,
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information.
Example:

1.5) Benefits of OOP:

OOP offers several benefits to both the program designer and the user. ObjectOrientation
contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises greater
programmer productivity, better quality of software and lesser maintenance cost. The
principal advantages are:
 Through inheritance, we can eliminate redundant code extend the use of existing Classes.
 We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
 The principle of data hiding helps the programmer to build secure program that cannot be
invaded by code in other parts of a programs.
 It is possible to have multiple instances of an object to co-exist without any interference.
 It is possible to map object in the problem domain to those in the program.
 It is easy to partition the work in a project based on objects.
 The data-cantered design approach enables us to capture more detail of a model in an
implemental form.
 Object-oriented system can be easily upgraded from small to large system.
 Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
 Software complexity can be easily managed.

1.6) Applications of OOP:

The most popular application of object-oriented programming, up to now, has been in the
area of user interface design such as window. Hundreds of windowing systems have been developed,
using the OOP techniques.
Real-business system are often much more complex and contain many more objects
with complicated attributes and method. OOP is useful in these types of application
because it can simplify a complex problem. The promising areas of application of OOP
include:
 Real-time system
 Simulation and modeling
 Object-oriented data bases
 Hypertext, Hypermedia, and expertext
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAM/CAD systems
6
JAVA NOTES UNIT - I

2. JAVA EVOLUTION
2.1) Java History:

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


Microsystems of USA in 1991. Originally called Oak by James Gosling. Java was designed for the
development of software for consumer electronic devices like TVs, VCRs, toasters and such other
electronic machines. Below lists some important milestones in the development of Java.

Year Development
1990 Sun Microsystems decided to develop special software that could be used
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, demonstrated the application of
their new language to control a list of home appliances using a hand-held device
with a tiny touch sensitive screen.
1993 The World Wide Web (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 (tiny programs) using the new language
that could run on all types of computers connected to Internet
1994 The team developed a Web browser called “Hot Java” to locate and run applet
programs on Internet. Hot Java 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 snags. Java is just a name and is not
an acronym. Many popular companies including Netscape and Microsoft
announced their support to 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 (JDK 1.1)
1998 Sun releases the Java 2 with version 1.2 of the Software Development Kit (SDK
1.2)
1999 Sun releases the 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 SDK 5.0( instead of JDK 1.5) was released. This is known as J2SE 5.0
2006 Java SE 6 was released. With this release , sun changed the name from ‘J2SE’ to
Java SE and also removed ‘0’ from the version name.
2011 Java SE 7 was released.

2.2) Features of Java:

1) Compiled & Interpreted:


Java follows a two stage system. In the first stage, Java compiler translates the source code into byte
code instructions. Byte codes are not machine instructions and therefore in the second stage, java
7
JAVA NOTES UNIT - I
interpreter generates the machine code that can be directly executed by the system. Thus java is both
a compiled and an interpreted language.

2) Platform-Independent & Portable:


Java program can be executed anywhere on any system. There is no need to change the java
programs for execution in another operating system. Java ensures portability in two ways.
 Java compiler generates byte code instructions that can be implemented on any machine.
 The size of the data types are machine independent.

3) Object Oriented:
The object model in Java is simple and easy to extend. It is a fully Object Oriented language.
Everything in java is object even the primitive data types can also be converted into object by using
the wrapper class.

4) Robust & Secure:


Java is a strictly typed language. It checks the program code at compile time as well as at run time.
Java manages memory allocation and deallocation automatically. Java provides object oriented
exception handling to avoid system crashes.
Java program verifies all memory access but also ensure that no viruses are communicated with the
applet. There is no pointer concept in java, so nobody can access the memory location without
proper authorization.

5) Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.
Internet programmers can call functions on these protocols and can get access the files from any
remote machine on the internet rather than writing codes on their local system.

6) Simple, Small & Familiar:


Java was designed to be easy for the professional programmer to learn and use effectively. Because
Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers
have little trouble learning Java.

7) Multithreaded & Interactive:


Java was designed to meet the real world requirement of creating interactive networked programs.
Therefore to accomplish this, Java supports multithreading. Multithreaded programming allows you
to write programs that can do many things simultaneously.

8) High Performance:
Java uses native code usage, and lightweight process called threads for faster execution. The
advance version of JVM uses the adaptive and just in time compilation technique that improves the
performance.

9) Dynamic & Extensible:


Java programs have the capability to carry a sufficient amount of run time type information. This
information can be used to verify and resolve accesses to the objects at run time. This makes it
possible to dynamically link code in a safe manner.

10) Ease of development:


Java supports the concept of reusable code for program execution. Thus java program can be
developed in an easier way.
8
JAVA NOTES UNIT - I
2.3) Java and Internet

Java is strongly associated with the internet because of the first application program is
written in Java was hot Java. Web browsers to run applets on the internet. Internet users can use
Java to create applet programs & run then locally using a Java-enabled browser such as hot Java.
Java applets have made the internet a true extension of the storage system of the local computer.

2.4)Java and World wide web

 World wide web is a collection of information stored on internet computers.


 World wide web is an information retrieval system designed to be used in the internet’s
distributed environment.
 World wide web contains web pages that provide both information and controls.
 Web pages contain HTML tags that enable us to find retrieve, manipulate and display
documents world wide.
 Before Java, the world wide web was limited to the display of still images & texts.
 With the help of Java WWW is capable of supporting animation graphics, games and wide rage
special effects.

The figure shows the following communication steps:


 Java communicates with a web page through a special tag called <applet>.
 Java user sends a request for an HTML document to the remote computers net browser.
9
JAVA NOTES UNIT - I

 The web-browser is a program that accepts a request, processes the request and sends the
required documents.
 The HTML document is returned to that user browser.
 The document contains the applet tag which identifies the applet. The corresponding applet is
transferred to the user computer.
 The Java enabled browser on the user's computer interprets the byte code and provide output.

2.5) Web Browsers

A browser is a software application used to locate, retrieve and display content on the
World Wide Web, including Web pages, images, video and other files. As a client/server model,
the browser is the client run on a computer that contacts the Web server and requests
information. The Web server sends the information back to the Web browser which displays
the results.
The browser application retrieves or fetches code, usually written in HTML (HyperText
Markup Language) and/or another language, from a web server, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or another Internet-
enabled device that supports a browser.
Examples of Web Browsers:

 Hot Java
 Netscape Navigator
 Internet Explorer

HotJava
HotJava was a modular, extensible web browser from Sun Microsystems implemented
in Java. It was the first browser to support Java applets, and was Sun's demonstration
platform for the then-new technology. It has since been discontinued and is no longer
supported.

Netscape Navigator
Netscape Navigator is a browser that became popular in 1994 when it was released by
Netscape Communications. This was released as a competition to Internet Explorer, however it
soon lost popularity.

Internet Explorer
Internet Explorer (IE) is a product from software giant Microsoft. This is the most commonly
used browser in the universe. This was introduced in 1995 along with Windows 95 launch .it
uses just-in-time compiler which greatly increases the speed of execution.
10
JAVA NOTES UNIT - I
2.6) Java Environment

Java Environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development kit (JDK)
and the classes and methods are part of the Java Standard Library(JSL), also known as the
Application Programming Interface(API).

1. Java Development Kit

The Java Development Kit comes with a collection of tools that are used for developing
and running Java Programs. They include:
a) appletviewer(for viewing Java Applets) : Enables us to run Java applets(without actually
using a Java-compatible browser).
b) javac( Java Compiler) : The Java comiler, which translates Java sourcecode to bytecode
files that the interpreter can understand.
c) java( Java Interpreter) : Java interpreter, which runs applets and applications by reading
and interpreting bytecode files.
d) javadoc : Creates HTML format documentation from Java source code files.
e) javah : Produces header files for use with native methods.
f) javap : Java disassembler, which enable us to convert byte code files into a program
description.
g) Jdb : Java debugger, which helps us to find errors in our programs.
11
JAVA NOTES UNIT - I
The way these tools are applied to build and run application programs is illustrated in
above figure. 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 be converted into a source code with the help of Java
disassemble javap.

2. Application Programming Interface

The Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:
 Language Support Package: A collection of classes and methods required for implementing
basic features of java.
 Utilities Package: A collection of classes to provide utility functions such as date and time
functions.
 Input/Output Package : A collection of classes required for input/output manipulation.
 Networking Package: A collection of classes for communicating with order computers via
Internet.
 AWT package : The Abstract Window Tool Kit package contains classes that implements
platform-independent graphical user interface.
 Applet Package : This includes a set of classes that allows us to create Java applets.

3. Java Runtime Environment

The java Runtime Environment (JRE) facilitates the execution of programs developed in java.
It primarily comprises the following:
 Java virtual machine (JVM) : it is a program that interprets the intermediate Java byte code
and generates the desired output. It is because of byte code and JVM concepts that programs
written in Java are highly portable.
 Runtime class Libraries: These are a set of core class libraries that are required for the
execution of Java programs.
 User interface tool kits: AWT and Swing are examples of tool kits that support varied input
methods for the users to interact with the application program.
 Deployment technologies: JRE comprises the following key deployment technologies:
a) Java plug-in: Enables the execution of a Java applet on the browser.
b) Java Web Start: Enables remote-deployment of an application. With web start, users can
launch an application directly from the web browser without going through the installation
procedure.

3. INTRODUCTION TO JAVA

3.1) Types Of Java Programs:

Java is a programming language that is used to build programs that can work on the local
machine and on the internet as well. It is a platform independent language which could be used to
create software for embedded systems. So there are various categories of programs that can be
developed in Java.

 STAND-ALONE APPLICATIONS - Console Applications - An application is a program that


runs on the computer under the operating system of your computer. Creating an application in java
12
JAVA NOTES UNIT - I
is similar to doing so in any other computer language. The application can either be GUI based or
console based.

 WEB APPLICATIONS - These are the applications which are web-based in nature and require a
web browser for execution. The Web applications makes use of a Server to store the data, and
every time a user requests to execute that application, the request is passed on to the server for
suitable reply. E.g. Applet and Servlet.
 An applet is an application designed to be transmitted over the Internet and executed by a Java-
compatible Web browser. An applet is actually a tiny Java program, dynamically downloaded
across the network, just like an image, sound file, or video clip.
 In Servlets, the client sends a request to a server. The server processes the request and sends a
response back to the client.

 DISTRIBUTED APPLICATIONS - It requires a server to run these applications. A number of


servers are used simultaneously for backup to prevent any data losses.

 CLIENT SERVER APPLICATIONS - These applications too make use of web technology for
their execution. They follow simple Client-Server model, where a client makes requests directly to
the server.

3.2) Java Program Structure:

When we consider a Java program, it can be defined as a collection of objects that


communicate via invoking each other's methods.

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/blue print that describes the behaviors /states that object
of its type support.

Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is created
by the values assign
Documentation Section Suggested

Package statement Optional

Import statement Optional

Interface statement Optional

Class definition Optional

Main Method Class{main method definition.} Essential


13
JAVA NOTES UNIT - I
Let us start Java programming with a small example.

//This program will display the output “My first Java program”
import java.io.*;
class first
{
public static void main(String args[])
{
System.out.println(“My first Java program”);
}
}

 Documentation section - The documentation section consist of a set of comment lines such
as the name of the program, program details etc. The three types of comments are
// Single line comment
/* ………..*/ Multiline comment
/**………..*/ For generating documentation automatically

 Package Statements: The first statement allowed in a java file is a package statement. This
statement declares a package name and informs the compiler that classes defined here belong
to this package.
E.g: package student;

 Import statements - It instructs the interpreter to load the corresponding class contained in
the package statement. There can be any number of import statements in a java program.
Eg: import student.test;
This statement instructs the interpreter to load the test class contained in the package student.

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

 Class Declaration – This line declares a class. class is an object-oriented construct and a
keyword which states that the class declaration follows. “first” is the name of the class.

 Opening and Closing Brace - The entire class definition, including all of its members, will
be between the opening curly brace ({) and the closing curly brace (}).

 Public - The keyword public is an access specifier that declares the main method accessible
to all other classes.

 Static - The keyword static states that this method belongs to the entire class. The keyword
static allows main() to be called without having to instantiate a particular instance of the class.

 Void - The type modifier void states that the main() method does not return any value.

 Main() – The main() function is similar to the the main() in C/C++. Every Java application
program must include the main() method. It is the method called when a Java application
begins.
14
JAVA NOTES UNIT - I

 String args[ ] - The parameter args[] denotes an array of instances of the class String.

 Output Line –The println() method is a member of the out object, which is a static data
member of System class. System is a predefined class that provides access to the system, and
out is the output stream that is connected to the console.

3.3) Naming conventions:

a) Names of all public methods and instances start with a leading lower case letters.
Eg. average
sum
b) When more than one words are used in a name, the second words are marked with a leading
upper case letters.
Eg. day Temperature
total Marks
c) All private and local variables use only lower case letters combined with under score.
Eg. area_triangle
d) All classes and interfaces start with the leading upper case letters.
Eg. Area
e) Variables that represent constant values use all upper case letters and under score.
Eg. TOTAL
MAX_COUNT

3.4) Java Tokens:

The tokens are the small building blocks of a Java program that are meaningful to the Java
compiler.

Types of Tokens:
1) Keywords
2) Identifiers
3) Literals
4) Operators
5) Separators

1) Keywords:
These are the pre-defined reserved words of any programming language. Each keyword has a
special meaning. It is always written in lower case. Java provides the following keywords:

01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements

2) Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined by the
user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a
special kind of identifier that is used in the goto statement.
15
JAVA NOTES UNIT - I
Rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign.
o It cannot start with digits but may contain digits.
o The white space cannot be included in the identifier.
o Identifiers are case sensitive.

Some valid identifiers are:


PRICE
radius
a1
$circumference

3) Literals:
Literal is a notation that represents a fixed value (constant) in the source code. It is defined by the
programmer. Once it has been defined it cannot be changed. Java provides five types of literals:
o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"java" String

null any reference type

4) Operators:
Operators are the special symbol that tells the compiler to perform a special operation. Java
provides different types of operators that can be classified according to the functionality they
provide.

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !
16
JAVA NOTES UNIT - I

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

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

Bitwise &,|,^,~

Shift << , >> , >>>


5) Separators:

The separators in Java is also known as punctuators. There are nine separators in Java:

o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the
two statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.

3.5) Java Character Set

The smallest units of java language are the characters used to write java tokens. These
characters are defined by the Unicode character set which tries to create characters for a large
number of scripts world wide.
The Unicode is a l6-bit character coding system and currently supports more than 34,000
defined Characters derived from 24 languages from America, Europe, Middle East, Africa and Asia
(including India)

3.6) Java Statements

A statement is an executable combination of tokens ending with a semicolon(;). Statements


are usually executed in sequence in the order in which they appear. Java implements several types
of statements and these are:
17
JAVA NOTES UNIT - I

 Labelled Statement:
Any statement which begins with a Label. These are not keywords and they are the
arguments of jump statements.
 Expression Statement:
Java has seven types of Expression Statements like
1) Assignment
2) Pre-decrement
3) Post-decrement
4) Pre-increment
5) Post -increment
6) Method call
7) Allocation Expression.
 Control statements:
Selection Statement: This statement is used for selecting one of several control flows.
Iteration Statement: These statement specify how and when looping will take place.
Jump Statement: This statement pass control to the beginning or end of the current block,
or a labeled Statement.
18
JAVA NOTES UNIT - I
 Synchronization Statement:
These are used for multithreading in Java.
 Guarding Statement:
This statements are used for safe handling of code and uses try , catch and finally block.

3.7) Creating and Executing a Java Program

Implementation of a Java application program involved a series of steps they include :


 Creating the program
 Compiling the program
 Running the Program

Remember that, before we begin creating the program, the java development kit(jdk) must be
properly installed in your system.

1.Creating the program:


We can create a program using any text editor assume that we have entered the following
program:

Class Test
{
public static void main(String args[])
{
System.out.println(“Hello!”);
System.out.println(“Welcome to the world of java”);
System.out.println(“Let us learn java”);
}
}

We must save this program in a file called Test.java ensuring that the file name has the class
name properly. This file is called the source file. Note that all java source file will have the
extension java. Note also that if a program contain multiple classes, the file name must be the
class name of the class containing the main method.

2.Compiling the Program


To compile the program, we must run the java compiler javac, with the name of the source
file on the command line as shown below:
javac Test.java
If everything is ok, the javac compiler creates a file called Test.class containing the bytecode of
the program. Note that the compiler will automatically names the bytecode as <class name> .class
19
JAVA NOTES UNIT - I

3.Running Program
We need to use the java interpreter to run a stand-alone program. At the command prompt,
type java Test
now, the interpreter looks for the main method in the program and begins execution from there.
When executed, the program displays the following:
Hello!
Welcome to the world of java
Let us learn java
Note that we simply type “Test” at the command line and not “Test.class” or “Test.java”.

4.Machine Neutral
The compiler converts the source code files into bytecode files. These codes are machine
independent and therefore can be run on any machine. This is a program complied on an IBM
machine will run on a Macintosh machine.
Java interpreter reads the bytecode files and translates them into machine code for the
specific machine on which the java program is running. The interpreter is therefore specially
written for each type of machine.

3.8) Java Virtual Machine

All language compilers translates source code into machine code for a specific computer.
Java compiler also does the same thing. Then, how does java achieved architecture neutrality? The
answer is that the java compiler produces an intermedia code known as bytecode for a machine
that does not exist. The machine is called the Java Virtual Machine and it exist only inside the
computer memory. It is a simulated computer within the computer and does all major functions
of a real computer. Below figure illustrate the process of compiling a java program into bytecode
which is also referred to as virtual machine code.
20
JAVA NOTES UNIT - I
The virtual machine code is not machine specific. The machine specific code(known as a
machine code) is generated by the java interpreter by acting as an intermediary between the
virtual machine and the real machine as shown in below figure. Remember that the interpreter is
different for different machine

Below figure illustrate how java works on a typical computer. The Java object framework
(Java API) acts as the intermediary between the user program and the virtual machine which in turn
acts as the intermediary between the operating system and the java object framework.

3.9) Command line arguments:

Sometimes you will want to pass some information on a program when you run it. This is
accomplished by passing command-line arguments to main( ).
A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ). We can pass any
number of arguments because argument type is an array.
Any argument provided in the command line at the time of program execution, are accepted
to the array args as its elements. Using index or subscripted entry can access the individual elements
of an array. The number of element in the array args can be getting with the length parameter.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Step 1) Copy the following code into an editor.


21
JAVA NOTES UNIT - I

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

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

Step 2) Save & Compile the code


compile by > javac commandline.java

Step 3) Run the code as


run by > java commandline apple orange banana

Step 4) You must get an output as below.


Output:
apple
orange
banana

3.10) Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.

Types of Java Comments


There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1.Java Single Line Comment
The single line comment is used to comment only one line.

Syntax:
//This is single line comment

Example:
public class CommentExample1
{
public static void main(String[] args)
{
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:
22
JAVA NOTES UNIT - I
10

2.Java Multi Line Comment


The multi line comment is used to comment multiple lines of code.

Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}}
Output:
10

3.Java Documentation Comment


The documentation comment is used to create documentation API. To create documentation
API, you need to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{return a-b;}
}

Compile it by javac tool: Eg.javac calculator.java


Create Documentation API by javadoc tool: Eg.javadoc calculator.java
Now, there will be HTML files created for your Calculator class in the current directory. Open the
HTML files and see the explanation of Calculator class provided through documentation comment.

You might also like