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

Unit1- Introduction to Java

The document provides an overview of Java, including its history, features, and differences from C and C++. It discusses Java's development milestones, object-oriented programming concepts, and its role in Internet applications through applets and web browsers. Additionally, it outlines the Java environment, including the Java Development Kit and Runtime Environment, as well as a simple Java program example.

Uploaded by

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

Unit1- Introduction to Java

The document provides an overview of Java, including its history, features, and differences from C and C++. It discusses Java's development milestones, object-oriented programming concepts, and its role in Internet applications through applets and web browsers. Additionally, it outlines the Java environment, including the Java Development Kit and Runtime Environment, as well as a simple Java program example.

Uploaded by

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

Introduction to JAVA

Internet Origin and Development


The Internet has revolutionized the computer and communications world like nothing before.
The invention of the telegraph, telephone, radio, and computer set the stage for this
unprecedented integration of capabilities.

The Internet is at once a world-wide broadcasting capability, a mechanism for information


dissemination, and a medium for collaboration and interaction between individuals and their
computers without regard for geographic location.

The Internet's architecture is based in the specification of the standard TCP/IP protocol,
designed to connect any two networks which may be different in internal hardware, software,
and technical design. Once two networks are interconnected, communication with TCP/IP is
enabled end-to-end, so that any node on the Internet has the near magical ability to
communicate with any other no matter where they are. This openness of design has enabled
the Internet architecture to grow to a global scale.

Introduction to JAVA
Java is a general-purpose, object oriented programming language developed by Sun
Microsystems of USA in 1991. Originally it was called Oak by James Gosling, one of the
inventors of the Java language. Java was developed for the development of software for
consumer electronic devices like TVs, VCRs, toasters and such other electronic machines. Java
is simple, reliable, portable, and powerful language.

Java Milestones
Year Development
1990 Sun Microsystems decided to develop a special software which could be used tomanipulate
consumer electronic devices. James Gosling formed a team of programmers and headed to
undertake this task.
1991 After exploring object-oriented language C++, the team announced a newlanguage named
“Oak”.
1992 The team, demonstrated the application of their new language to control a list of home
appliances.
1993 The team came up with the idea of developing web applets (tiny programs) usingthe new
language that could run on all types of computers connected to Internet.
1994 The team developed a Web Brower called “HotJava” to locate and run appletprograms on
Internet.
1995 Oak was renamed as “Java” and many companies such as Microsoft and Netscape
announced their support to Java.
1996 Java established itself not only as a leader for Internet programming, but also as ageneral-
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 Java 2 with version 1.2 of the Software Development Kit (SDK 1.2).
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 SDK 1.5) was released and was known as J2SE 5.0
2006 J2SE with JDK 6.0
2011 J2SE with JDK 7.0
2014 J2SE with JDK 8.0

Features of Java

Simple
According to Sun, Java language is simple because:
Syntax is based on C++ (so easier for programmers to learn it after C++)

Removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.

Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior. Object-oriented programming(OOPs) is a
methodology that simplifies software development andmaintenance by providing some
rules.

Basic concepts of OOPs are:


Object
Class Inheritance

Polymorphism

Abstraction
Encapsulation

Platform Independent and Portable


A platform is the hardware or software environment in which a program runs. The Java
platform differs from most other platforms in the sense that it's a software- based platform
that runs on top of other hardware-based platforms.

Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
Java code is compiled by the compiler and converted into byte code. This byte code is a
platform independent code because it can be run on multiple platforms i.e. Write Once and
Run Anywhere (WORA).

We may carry the java byte code to any platform, making Java to be portable.

Robust and Secured


Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java.

Java is secured because:

No explicit pointer

Programs run inside virtual machine sandbox.

Distributed
Java is designed as a distributed language for creating application on networks. It can share
data and programs. Java applications can access the remote objects on Internet as easily as
they can do in a local system.

Multi-threaded
A thread is like a separate program, executing concurrently. That means handling multiple
tasks simultaneously. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it shares the same
memory. Threads are important for multi-media, Web applications etc.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++).
OOPs Concepts

Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. One way to think about encapsulation
is as a protective wrapper that prevents the code anddata from being arbitrarily accessed by
other code defined outside the wrapper.
Access to the code and data inside the wrapper is tightly controlled through a well- defined
interface.

Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification.

Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation.

How Java differs from C and C++

Java and C
Main difference is Object-oriented programming language and procedural language.
Java does not include the C unique keywords sizeof and typedef Java
does not have the data types struct and union

Java does not define the type modifier keywords auto, extern, register, signed, and unsigned
Java does not support Pointers

Java does not have a preprocessor, hence we cannot use #include and #define Java adds new

operators such as instanceof and >>>

Java adds labeled break and continue statements

Java adds many features required for object-oriented programming

Java and C++


Java is a true object-oriented programming language while C++ is basically C with object-
oriented extension.

Java does not support operator overloading Java


does not have template classes as in C++
Java does not support multiple-inheritance of classes. This is accomplished by a new feature
called interface
Java does not support global variables Java

does not use pointers75%


Java has replaced the destructor function with a finalize() function

Java and Internet


Java can be used to create two types of programs: applications and applets.

An application is a program that runs on your computer, under the operating system of that
computer. That is, an application created by java is more or less like one created using C or
C++.

Java is strongly associated with the Internet because of the fact that the first application
program written in Java was HotJava, a Web browser to run applets on Internet.

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 clip, or video clip.
The important difference is that an applet is an intelligent program, not just animation or media
file.
In other words, and applet is a program that can react to user input and dynamically change
not just run the same animation or sound over and over.

Java and World Wide Web


World Wide Web (WWW) is an open-ended information retrieval system designed to be used
in the Internet's distributed system.
Java was meant to be used in distributed environment such as Internet.

Since Java and WWW share the same philosophy, Java could be easily incorporated into the
Web systems.

Before Java, the WWW was limited to the display the still images and text.

Incorporation of Java into Web pages has supported animation, graphics, games,and wide
range of special effects.

Web Browsers
Web browsers are used to navigate through the information found on the Internet.

HotJava
HotJava was developed by Sun Microsystems. HotJava is written entirely in Java
programming language. HotJava is currently available for Solaris platform, Window95,
Windows NT, and windows XP.

Netscape Navigator
Netscape Navigator from Netscape Communication Corporation, is a general- purpose
browser that can run Java applets. Netscape Navigator is available for Windows 95, NT,
Solaris and Apple Macintosh. It also supports JavaScript, a language used in HTML
documents.

Internet Explorer
Internet Explorer is a popular browser developed by Microsoft for Windows 95, NT, XP. Uses
the toolbars, icons, menus, dialog boxes for easy navigation.

Hardware and Software Requirements


Some of the hardware and software requirements for Java SE 6 are listed below:

Platform Memo Browsers Disk


ry Space
Solaris SPARC 32-bit (Solaris 10) 64 MB Mozilla 1.4 or 65 MB
above
Windows 32-bit 64 MB Firefox 1.6 or 98 MB
(Window XP Professional, Windows 2000 above, IE 6.0 or
Professional) above
Windows 32-bit 128 MB Firefox 1.6 or 98 MB
(Windows Server 2003, Windows Vista) above, IE 6.0 or
above
Windows 64-bit 128 MB 64-bit OS, 32- 110 MB
(Window XP Professional, Windows Server bit JRE, IE 6.0 or
2003, Windows Vista) above
Linux 32-bit 64 MB Mozilla 1.4 or 58 MB
(RedHat 9.0, RedHat 2.1, Suse above
Enterprise Linux Server 9)
Linux 64-bit 64 MB 64-bit OS, 32- 56 MB
(RedHat Enterprise 3.0, Suse Enterprise Linux bit JRE, Mozilla 1.4
Server 9) or above

Java Support System


Below table lists the systems necessary to support Java for delivering information on the
Internet.

Support Description
System
Internet Local computer should be connected to the Internet.
Connection
Web Server A program that accepts requests for information and sends the requireddocuments.

Web Browser A program that provides access to WWW and runs Java applets.
HTML A language for creating hypertext for web.
Applet tag For placing Java applets in HTML document.
Java Code Java code is used for defining Java applets.
Byte code Compiled Java code that is referred to in the APPLET tag and transferred tothe user
computer.
Proxy Server An intermediate server between the requesting client workstation and the original
server. It is typically implemented for ensuring security.
Mail Server A computer system that facilitates exchange (sending and receiving) of e-mails across
network.

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 Application Programming Interface (API).

Java Development Kit


The Java Development Kit comes with a collection of tools that are used for
developing and running Java programs.

Tool Description
appletviewer Viewing java applets, which enables to run Java applets
javac Java compiler, which translates Java source code to byte code that the interpreter
can understand
java Java interpreter, which runs applets and applications by reading andinterpreting
byte code files
javap Java disassemble, which enables to convert byte code files into aprogram
description
javah Produces header files for use with native methods
javadoc Creates HTML format documents from Java source code files
jbd Java debugger, which helps to find errors in the program

Application Programming Interface


The Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:

Package name Description


Language Support Collection of classes and methods required for implementing
Package basic features of Java
Utilities Package Collection of classes to provide utility functions such asdate and
time

Input/Output Package Collection of classes required for input/output manipulation

Networking Package Collection of classes for communicating with othercomputers


via Internet

AWT Package Abstract Window Tool Kit package contains classes that
implements platform independent graphical user interface

Applet Package Collection classes that allows to create Java applets

Java Runtime Environment


The Java runtime Environment (JRE) facilitates the execution of programs developed in Java.
It primarily consists of:

Java Virtual Machine A program that interprets the intermediate Java byte code and
generates the desired output.
Runtime class libraries Set of core class libraries that are required for theexecution of Java
programs
User interface toolkits AWT and Swing are few examples that supports varied input
methods for the users to interact with the applicationprogram

Deployment technologies Java plug-in: Enables the execution of a Java applets on the browser
Java Web Start: Enables remote deployment of anapplication
Overview of Java Language
Introduction
Java is a general-purpose, object-oriented programming language. We can develop two types
of Java programs.

1. Standalone applications: are programs written in Java to carry out certain tasks on a
stand-alone local computer. Executing a stand-alone Java program involve two steps:

a. Compiling source code into byte code using javac compiler.

b. Executing the byte code program using java interpreter

2. Web applets: Applets are small Java programs developed for Internet applications.
An applet located on a server can be downloaded on a client using Java capable
browser.

Stand-alone programs can read and write files and perform certain operations that applets cannot
do. An applet can only run within a Web browser.

Java Source Code

Java compiler

Java Interpreter Java Browser

Output Output
Simple Java Program
class First
{
public static void main(String args[])
{
System.out.println(“Welcome to JAVA Programming”);
}
}

The first line class Firstdeclares a class. class is a keyword and First is an identifier
referring to the class name.

Every class definition in Java begins with an opening “{“ brace and ends with acorresponding
closing brace “}”.

The third line


public static void main(String args[])

defines a method main. This is starting point for the interpreter to begin the execution. Java
program must have only one main method. (Note that Java applets will not use the main
method at all). This line contains a number of keywords, public, static, and void.

public The keyword public is an access specifier that declares the main method asaccessible to all
other classes.
static Next keyword is static, which declares main method belongs to entire and not a part of any
objects of the class. Interpreter uses this method before any objects are created.

Void The keyword void is the type modifier, which states that main method does notreturn any
value.

All parameters to a method are declared inside a pair of parentheses. String args[]declares a
parameter named args, which contains an array of objects of the class type String.

The next line

System.out.println(“Welcome to JAVA Programming”);

Java is a true object oriented language, every method must be part of an object. The println
method is a member of the out object, which is a static data member of System class. This
line prints the string “Welcome to JAVA Programming”.

Java program with two classes


class Marks
{
int sub1, sub2;
void getdata(int marks1, int marks2)
{
sub1 = marks1;sub2
= marks2;
}
}
class Student
{
public static void main(String args[])
{
int total;
Marks m = new Marks();
m.getdata(85, 75);
total = m.sub1 + m.sub2;
System.out.println("Marks of subject1 = " + m.sub1);
System.out.println("Marks of subject1 = " + m.sub2);
System.out.println("Total Marks = " + total);
}
}

Java Program Structure


A Java program may contain one or more sections as show below:

Document Section Optional.


It consists of set of comment lines giving the name of the program.

Package Section Optional.


This statement declares a package name and informs compilerthat the
classes defined here belong to this package.
Import Statements Optional.
This statement instruct the interpreter to load the class containing a
package.
Interface Statements Optional.
Interface is like a class but includes group of method declaration. This is
used while implementing multiple inheritance features.

Class Definitions Optional.


Java program may have multiple class definition.
Main Method Class Essential.
Every Java stand-alone program requires a main method as itsstarting
point.

Java Tokens
Smallest individual units in a program are known as tokens. Java program is a collection of
token, comments, and white spaces. Java includes five types of tokens and they are:
1. Reserved Keywords
Java language has 50 reserved keywords. Keywords have special meaning in Java. Hence,
keywords are not used as names for variables, classes, methods, and so on. All keywords are
written in lover-case letters. Below are the list of keywords.

2. Identifiers
Identifiers are programmer-designed tokens used for naming classes, methods, variables,
objects, labels, packages, and interfaces in a program. The rules of Java identifiers:

They can have alphabets, digits, and the underscore ( _ ) and dollar ( $ ) sign characters.

They must not begin with a digit.

Upper-case and lower-case letters are distinct. They can


be of any length.

3. Literals
Literals in Java are sequence of characters such as digits, letters, and other characters that
represent constant values to be stored in variables. Different types of literals are:

Integers
Floating point

Character

String Boolean

4. Operators
Operator is a symbol that takes one or more operand(s) and operates on them to produce a
result.

5. Separators
Separators are symbols which indicate where groups of code are divided and arranged.
Different types of separators are:
parentheses ( )

braces { }
brackets [ ]

semicolon ;

comma , period

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

Diagram of Java statements

Implementing Java Program

1. Creating the program


Java program can be created using any text editor. The program should be saved as
MainMethodClassName.java, where MainMethodClassName is the class name inwhich the main
method is written. Program is also called as Source file.

Considering the example mentioned in Program with two class, the main method ispresent in
the class “Student”. Hence the program should be saved as Student.java.

2. Compiling the program


The program need to be compiled using the Java Compiler javac, with the name of the source
file on the command line.

javac Student.java

If there are no syntax errors in the source file, then compiler creates Student.classfile
containing the byte code of the program. Compiler automatically names the class file as
<classname>.class.

3. Running the program


Using the Java Interpreter, class file need to be run on a stand-alone programs. At the
command type
java Student

Java Virtual Machine


Java compiler produces an intermediate code known as byte code for a machine that does not
exist. This machine is called as Java Virtual Machine (JVM), which exists only inside the
computer memory.

Source Code --> Java Compiler --> Byte Code(Real

Machine) (JVM)

Process of converting source code into byte code

Byte Code --> Java Interpreter--> Machine Code(JVM) (Real

Machine)

Process of converting byte code into machine code

Command Line Arguments


Command line arguments are parameters that are supplied to the application program at
the time of invoking it for execution. We can write Java programs that can receive and use
the command line arguments. As stated in signature of main method, args is declared as an
array of strings. Any arguments provided in the command line are passed to the array
args as its elements.

Java Test These are command line arguments

This command line contains four arguments. These are assigned to the array argsas follows:

args[0] = These
args[1] = are args[2]

= command args[3] =

line args[4] =
arguments

Program to illustrate command line arguments

class CommandLine
{
public static void main(String args[])
{
int count, i;
count = args.length;
System.out.println("Total number of arguments = " + count);System.out.println("List of
arguments are:");
for(i=0; i<count; i++)
System.out.println("\targs[" + i + "] = " + args[i]);
}
}
Compile and run the program java CommandLine abc 123 a$ _ac as thearguments, produces the output
Total number of arguments = 4List of
arguments are:
args[0] = abc
args[1] = 123
args[2] = a$
args[3] = _ac
Programming Style
Java is a freeform language. For example, the statement

System.out.println(“Welcome to JAVA”);

can be written as

System.out.println
(“Welcome to JAVA”);

or, even as

System
.
out
.
println(
“Welcome to JAVA”
)
;
Constants, Variables, and Data
Types

Constants
Constants are referred to fixed values that do not change during the execution of aprogram.

Integer Constants
An integer constant refers to a sequence of digits. Three types of integer constant are decimal,
octal, and hexadecimal.

Decimal Integer Constants


Decimal integer constants consist of any combination of digits 0 through 9, preceded by an
optional minus sign.
Examples: 123, -321, 0

Octal Integer Constants


Octal constants consist of digits 0 through 7, with a leading 0.
Examples: 037, 07, 00, 0576

Hexadecimal Integer Constants


Hexadecimal integer constants consist of any combination of digits 0 through 9 and/or
alphabets A through F, with a leading 0x or 0X.

Examples: 0x2, 0XAF, 0x24FD, 0X2345

Real Constants
Real constants consist of a whole number and fractional number separated by dot (.).

Example: 0.025, 123.45, 34.00


A real constant can also be represented as follows:

mantissa e exponent
The mantissa is the real number expressed in decimal notation or an integer. The exponent is an
integer with an optional plus or minus sign. The letter e can be represented in lowercase or
uppercase.

Example: 0.65e4 12e-2 1.5E+5 -1.2E-1

Single Character Constant


A single character constant contains a single character enclosed between a pair ofsingle quote
marks. The character may contain an alphabet or a digit or a special character or a blank character.

Example: '5', 'x', ';' ''

String Constants
A string constant is a sequence of characters enclosed between a pair of double quote marks.
The characters may contain alphabets, digits, special characters, and blank character.

Example: “hello JAVA” “2015” “...?..” “x”

Backslash Character Constants


Java supports some backslash character constants which are used in display(output)
methods. These characters are called as escape sequences.

\b back space

\f form end

\n new line

\r carriage return

\t horizontal tab
\' single quote

\” double quote
\\ backslash

Variables
A variable is an identifier that denotes a storage location used to store a data value. A variable
may take different values at different times during the execution of the program. Variable
names may consist of alphabet, digit, the underscore ( _ ), and dollar ($) characters, subject to
following condition:

1. Must not begin with a digit


2. Uppercase and lowercase are distinct

3. Should not be a keyword


4. White space is not allowed

5. Any length

Data Types
Data type specifies the size and type of a values that can be stored. Mainly classified as
Primitive (Intrinsic) and Non-Primitive (Derived).

Java defines eight primitive 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 includes float and double, which
represent numbers with fractional precision.

 Characters - This group includes char, which represents symbols in a


character set.

 Boolean - This group includes Boolean, which is a special type for


representing true/false values.

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 integers.

The integers long need to be appended with a letter L or l at the end of the number.
Example: 123L or 123l

Floating Point Types


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, floatand double,
which represent single- and double-precision numbers,respectively. Their size and ranges are
shown here:
The float type is treaded as double-precision quantities, to force them to be in single-
precision mode, append F or F to the numbers. Example:

1.23F 5.345e3F

Character Type
In Java, the data type used to store characters is char. The char type assumes a size of 2 bytes.

Boolean Type
Java has a primitive type, called Boolean, for logical values. It can have only one of two
possible values, true or false. Boolean type is denoted by Boolean and uses only one bit of
storage.

Declaration of Variables
In Java, all variables must be declared before they can be used. The basic form of avariable
declaration is shown here:

type variable1, variable2, .................................... variableN;

int count; float

x, y;char c;

Initialization of Variables
The process of giving initial value to the variables is known as initialization. Avariable
must be given a value after it is declared and before used in an expression. Basic form of
initialization is shown here:

VariableName = value;count =

5;
x = 5.34F;
y = 3.5fc =

'x';
Read Statements
Values can be read from keyboard and may be initialized to a variable.

Scope of Variables
The area of the program where the variable is accessible (used) is called scope ofvariable. In Java,
variables are classified as three kinds:

1. instance variable

2. class variable

3. local variable

The instance variable is declared inside a class. Instance variables are created when the
objects are associated with the objects. They take different values foreach object.

The class variable is declared inside a class and are global to that class. The value of class
variable remains same to different objects of that class.

The variables declared and used inside methods are called as local variable. Local variables
are also declared inside a program block that are defined between a open
{ brace and a close } brace.

// Demonstrate block scope.class Scope


{
public static void main(String args[])
{
int x; // known to all code within mainx = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here. System.out.println("x and y: " + x + " "
+ y);x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here. System.out.println("x is " + x);
}
}
Symbolic Constants
The constants are used in the program to avoid problem in modification and understanding the
programs.

A constant is declared as follows:

final type symbolic-name = value;final int STRENGTH


= 100;
final float PI = 3.142;
1. Symbolic names take the same name form as variable names and written in
CAPITAL (Uppercase).
2. After declaring symbolic constant, they cannot be assigned any other value.

3. They cannot be declared inside a method. They should be used only as classdata
members in the beginning of the class.

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

The syntax is:


type variable1 = (type) variable2;Example:
int i = 50;

byte b = (byte) i;
The process of assigning a smaller type to a larger type is known as widening or promotion.

The process of assigning a larger type to a smaller type is known as narrowing. Narrowing may
result in loss of the data.

Casts that results in No Loss of data


From To
byte short, int, long, char, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

Automatic Conversion
Java does the conversion of the assigned value automatically without a cast. This isknown as
automatic type casting. It possible only if the destination type has enough precession to store
the source value.

Example: int is large enough to hold a byte value.


byte a=50;int b

= a;

Getting Values of Variables


Java supports the output methods that can be used to send the results to the screen.

print() method -- print and wait


The print() method prints the output on one line until a newline character is
encountered.

System.out.print(“Hello “);System.out.print(“JAVA“);

will display the words Hello JAVAon one line and waits for displaying further information on
the same line. Escape sequence \n can be used to move to the next line by printing a newline
character.
System.out.print(“\n”);

OR

System.out.print('\n');

println() method --print and move to next line


The println()method prints the output on one line and moves to the next line.

System.out.println(“Hello”);System.out.println(“JAVA”);

produces the output as

Hello
JAVA

To print a blank line we can use,


System.out.println();

Standard Default Values


Every variable has a default value in Java. Java provides default value to that variable
type automatically.
Type of Default value Type of Default value
variable variable
byte 0 float 0.0f
short 0 double 0.0
int 0 Boolean false
long 0L reference null
char Null character
Operators And Expressions

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

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

Arithmetic Operators
Java supports all the basic arithmetic operators as listed in below table.

Operat Meaning Operato Meaning


or r
+ Addition or unary plus / Division
- Subtraction or unary minus % Modulo division (Remainder)
* Multiplication

Example: a – b a+b a*b a/b a%b -a


*b
aand b may be variables or constants and known as operands.

Integer Arithmetic
Arithmetic involving only integer type of operands is called as Integer Arithmetic. Integer
arithmetic always yields an integer value.

Example: a=14 b=4

a–b = 10 a+b = 18 a*b = 56a/b

= 3 (decimal part truncated)


a%b = 2 (reminder of integer division)
Real Arithmetic
Arithmetic involving only real type of operands is called as Real Arithmetic. Real arithmetic always
yields an real value.

Example: a=20.5 b=6.4


a+b = 26.9 a-b = 14.1 a*b = 131.2
a/b = 3.20313 a%b = 1.3

Mixed-mode Arithmetic
Arithmetic involving both real and integer type of operands is called as Mixed-mode Arithmetic.

Example: 15/10.0 = 1.5

15/10 = 1

Relational Operators
The relational operators are the one which will compare two quantities (operands) and gives
the relation between quantities. The Result is either true or false.

Relational operators are used in decision statements such as if, while, do, for todecide the course of
action of a running program.

Operat Meaning Example


or
< Is less than 4.5 < 10 true
<= Is less than or equal to 10 <= 5 false
> Is greater than -3 > 10 false
>= Is greater than or equal 4 >= 4 true
to
== Is equal to 5 == 6 false
!= Is not equal to 8 != 5 true

Logical Operators
An expression which combines two or more relational expressions is called as a logical
expression or a compound relation expression.

Operat Meaning Example


or
&& Logical AND a>b && a>c
|| Logical OR a!=10 || b==15
! Logical NOT !c
op-1 op-2 Value of the expression
op-1 && op- op-1 || op-2 !op-1
2
true true true true false
true false false True false
false true false True true
false false false false true

Note: If both the operands are true, then the AND results in true and otherwise
false.

IF both the operands are false, then the OR results in false and otherwise
true.

Assignment Operator
Assignment operator are (=) used to assign value of an expression to a variable. Java also
supports shorthand assignment operators.

Statement with simple assignment Statement with shorthand operator


operator
a =a + 1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= n+1
a = a / (n+1) a /= n+1
a=a%b a %= b

Increment and Decrement Operators


The operator which add 1 to the variables and subtracts 1 from the variables areknown as
increment (++) and decrement (--) operators respectively.

The increment and decrement operators are extensively used in looping statements such as
for, while,and do.

There types are:

Type Notatio Meaning


n
Pre-increment ++a Value of the variable is incremented first and then it is used in
the expression.
Post-increment a++ Value of the variable is used first and then it is
incremented.
Pre-decrement --a Value of the variable is decremented first and then it is used in
the expression.
Post-decrement a-- Value of the variable is used first and then it is
decremented.
Conditional Operator
Java supports a ternary operator known as conditional operator (?:). The expression is as
follows:

exp1 ? exp2 : exp3

where exp1, exp2, and exp3 are the expressions. The conditional operator works asfollows:

1. The expression exp1 is evaluated first.

2. If exp1 is true, then the expression exp2 is evaluated.

3. If exp1 is false, then the expression exp3 is evaluated.

Bitwise Operators
Java supports bitwise operators for manipulation of data at bit level. Bitwise operators are
applied only to integer data types and not for floating-point data types.

Opera Meaning
tor
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive
~ One's compliment
<< Shift left
>> Shift right
>>> Shift right with zero
fill

Special Operators
Java supports two special operators 1) instanceof 2) dot (.)

instanceof Operator
The instanceof is an object reference operator and returns Boolean values.

obj_name instanceof class_name


If the object on the left-hand side is an instance of the class given on the right-hand side, then the
operator results true value otherwise false.
Dot (.) Operator
The dot operator (.) is used to access the instance variables and the methods ofclass object.

obj.num; // Reference to the instance variable numobj.getdata(); //

Reference to the method salary

Arithmetic Expressions and Evaluation


An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the programming language.

Expressions are evaluated using an assignment statement.

Algebraic Java Expression Evaluated Expression


Expression
ab-c a*b-c x = a*b-c
2
3x +2x+1 3*x*x+2*x+1 y = 3*x*x+2*x+1
(m+n)(m-n) (m+n)*(m-n) x = (m+n)*(m-n)

Precedence of Arithmetic Operators


Arithmetic expressions without any parenthesis will be evaluated from left to right using the
rules of precedence of operators.

High Priority: * / %
Low Priority: + -

Operator Precedence and Associatively


Operator Description Associativ Rank
ely
. Member selection Left to right 1
() Function call
[] Array element reference
- Unary minus Right to left 2
++ Increment
-- Decrement Logical
! negation One’s
~ complimentType
(type) Casting
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Bitwise left shift Left to right 5
>> Bitwise right shift
>>> Bitwise right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Object comparison
== Equality Left to right 7
!= Inequality

& Bitwise AND Left to right 8


^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Left to right 13
= Assignment operator Right to left 14
op= Shorthand assignment Right to left

Mathematical Functions
Java supports basic Mathematic functions such as log, sqrt, max, pow, sin, cos, and so on are
frequently used in analysis of real-life problems. These basic math functions are present in
?Math class defined in the java.lang package. These math functions should be used as follows:

Math.function_name();

Example: double y = Math.sqrt(x);

Fucntion Operation
sin(x) Returns sine of the angle x in radians
cos(x) Returns cosine of the angle x in radians
tan(x) Returns tangent of the angle x in radians
asin(y) Returns the angle whose sine is y
acos(y) Returns the angle whose cosine is y
atan(y) Returns the angle whose tangent is y
atan2(x,y) Returns the angle whose tangent is x/y
pow(x,y) Returns x raised to y (x y)
exp(x) Returns e raised to x (ex)
log(x) Returns the natural logarithm of x
sqrt(x) Returns the square root of x
ceil(x) Returns the smallest whole number greater than or equal to x (rounding up)
floor(x) Returns the largest whole number less than or equal to x (rounding down)
rint(x) Returns the truncated value of x
round(x) Returns the integer closest to the argument
abs(a) Returns absolute value of a
max(a,b) Returns the maximum of a and b
min(a,b) Returns the minimum of a and b

Note: x and y are double type parameters. A and b may be ints, longs, floats, and doubles.
Decision Making And
Branching
Introduction
Java possesses decision making capabilities and supports the following statements known as
control or decision making statements.
1. if statement

2. switch statement

3. Conditional operator statement

Simple if Statement
The Java if statement works much like the IF statement in any other language. Further, it is
syntactically identical to the if statements in C, C++. Its simplest formis shown here:

if(condition)
statement;

Here, condition is a Boolean expression. If conditionis true, then the statement is executed. If
condition is false, then the statement is bypassed. Here is an example:

if(num < 100)


System.out.println("num is less than 100");

In this case, if num contains a value that is less than 100, the conditional expression is true, and
println() will execute. If num contains a value greater than or equal to 100, then the println()
method is bypassed.

class IfSample
{
public static void main(String args[])
{
int x, y;x =
10;
y = 20;
if(x < y)
System.out.println("x is less than y");
x = x * 2;if(x
== y)
System.out.println("x now equal to y");x = x * 2;
if(x > y)
System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
OUTPUT:
x is less than yx now
equal to y
x now greater than y

The if...else Statement


The if...else statement is an extension of the simple ifstatement. The generalform is:

if (condition)
statement1;
else
statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a Boolean value.

The if..elsestatement works like this: If the condition is true, then statement1
is executed. Otherwise, statement2 is executed. For
example, consider the following:

if(a < b)
a = 0;
else
b = 0;

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. Home

Assignment: Program to illustrate if...else statement

Nesting of if...else statements


A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the
same block as the else and that is not already associated with an else. Here is an example:

if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)

As the comments indicate, the final else is not associated with if(j<20) because it isnot in the
same block (even though it is the nearest if without an else). Rather, the final else is associated
with if(i==10). The inner else refers to if(k>100) because it is the closest if within the same
block.

Home Assignment: Program to illustrate nested if...else statement

The if-else-if Ladder


A common programming construct that is based upon a sequence of if-else-ifladder. It looks
like this:

if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
...
...
else
statement;

The if statements are executed from the top to down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed. The final else acts as a default condition; that is, if all other conditional tests fail,
then the last else statement is performed. If there is no final else and all other conditions are
false, then no action will take place.

Home Assignment: Program to illustrate if...else...if ladder statement


switch Statement
The switch statement is Java’s multi way branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if- else-if statements. Here is
the general form of a switch statement:

switch (expression)
{
case value1: block-1
break;
case value2: block-2
break;
.
.
.
case valueN: block-N
break;
default: default-block
}
The expression is an integer expression or characters. Value-1, value-2, ... are constant 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 list and may contain zero or
more statements. There is no need to putbraces around these blocks but it is important to note
that case labels end with acolon (:).

The switch statement works like this: The value of the expression is compared with each of
the values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constants matches the value of the expression, then the
default statement is executed. However, the default statement is optional. If no case matches
and no default is present, then nofurther action is taken. The break statement is used inside the
switch to terminate a statement sequence. When a break statement is encountered, execution
branches to the first line of code that follows the entire switch statement. This has the effect of
“jumping out” of the switch.

Home Assignment: Program to illustrate switch statement

The Conditional ( ? : ) Operator


Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the conditional operator (?:). The general form:

expression1 ? expression2 : expression3


The conditional operator works as follows:

1. The expression1 is evaluated first.

2. If expression1 is true, then the expression2 is evaluated.


3. If expression1 is false, then the expression3 is evaluated.

Here is a program that demonstrates the ?: operator. It uses it to obtain the absolute value of a
variable.

class Ternary
{
public static void main(String args[])
{
int i, k;i = 10;
k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value
of "+i+" is "+k);i = -10;
k = i < 0 ? -i : i; // get absolute value of i System.out.println("Absolute value
of "+i+" is "+k);

}
}
OUTPUT:
Absolute value of 10 is 10
Absolute value of -10 is 10
Decision Making and Looping

Introduction
The looping statements are also called as iteration statements are for, while, and do-while.
These statements create what we commonly call loops. A loop repeatedly executes the same set
of instructions until a termination condition is met.

The while Statement


The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:

while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated. Here is a while loop that counts down from 5, printing exactly ten
lines of "tick":

// Demonstrate the while loop.class While


{
public static void main(String args[])
{
int n = 5; while(n
> 0)
{
System.out.println("tick " + n);n--;
}
}
}

OUTPUT:
tick 5
tick 4

tick 3
tick 2
tick 1
Since the while loop evaluates its conditional expression at the top of the loop, the body of the
loop will not execute even once if the condition is false to begin with. For example, in the
following fragment, the call to println() is never executed:

int a = 10, b = 20;while(a >


b)
System.out.println("This will not be displayed");

The do-while Statement


Sometimes it is desirable to execute the body of a loop at least once, even if the conditional
expression is false to begin with. In other words, there are times when you would like to test
the termination expression at the end of the loop rather than at the beginning. The do-while
loop always executes its body at least once, because its conditional expression is at the
bottom of the loop. Its general form is:

do
{
// body of loop
} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. Condition must be a Boolean expression. Here is a reworked version of the “tick”
program that demonstrates the do-while loop. It generates the same output as before.

// Demonstrate the do-while loop.class DoWhile


{
public static void main(String args[])
{
int n = 5;do
{
System.out.println("tick " + n);n--;
} while(n > 0);
}
}

The for Statement


The simplest form of the for loop is shown here:

for(initialization; condition; iteration)


{
// body
}

If only one statement is being repeated, there is no need for the curly braces. The for loop
operates as follows. When the loop first starts, the initialization portion of the loop is executed.
Generally, this is an expression that sets the value of the loop control variable, which acts as a
counter that controls the loop. Next, condition is evaluated. This must be a Boolean expression.
It usually tests the loop control variable against a target value. If this expression is true, then
the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of
the loop is executed. This is usually an expression that increments or decrements the loop
control variable. The loop then iterates, first evaluating the conditional expression, then
executing the body of the loop, and then executing the iteration expression with each pass. This
process repeats until the controlling expression is false. Here isa version of the “tick” program
that uses a for loop:

// Demonstrate the for loop.class ForTick


{
public static void main(String args[])
{
int n;
for(n=5; n>0; n--) System.out.println("tick " + n);
}
}

Nesting of for Loops


Java allows loops to be nested. That is, one loop may be inside another. For example, here is a
program that nests for loops:

class Nested
{
public static void main(String args[])
{
int i, j; for(i=0; i<5;
i++)
{
for(j=i; j<5; j++) System.out.print("*");
System.out.println();
}
}
}

OUTPUT:
*****

****

***

**

Jumps in Loops
Java supports two jump statements: break and continue. These statements transfer control to
another part of your program.

Using break
In Java, the break statement has two uses. First, it terminates a statement sequence in a switch
statement. Second, it can be used to exit a loop.

// Using break to exit a loop.class


BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 10) break; // terminate loop if i is 10System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

Using continue
In while and do-while loops, a continue statement causes control to be transferred directly to
the conditional expression that controls the loop. In a for loop, control goes first to the
iteration portion of the for statement and then to the conditional expression. For all three loops,
any intermediate code is bypassed.

Here is an example program that uses continue to cause two numbers to be printed on each
line:

// Demonstrate continue.class Continue


{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}

OUTPUT:
01
23
45
67
89

This code uses the % operator to check if i is even. If it is, the loop continues without printing
a newline.

Labeled Loops
Assignment for students.

You might also like