Unit1- Introduction to Java
Unit1- Introduction to Java
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.
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.
Polymorphism
Abstraction
Encapsulation
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.
No explicit pointer
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.
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
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.
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.
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).
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
AWT Package Abstract Window Tool Kit package contains classes that
implements platform independent graphical user interface
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:
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 compiler
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 “}”.
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.
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 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.
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.
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.
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.
Machine) (JVM)
Machine)
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
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.
Real Constants
Real constants consist of a whole number and fractional number separated by dot (.).
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.
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.
\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:
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.
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
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:
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.
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.
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.
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.
= a;
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');
System.out.println(“Hello”);System.out.println(“JAVA”);
Hello
JAVA
Introduction
Java operators can be classified into a number of related categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic Operators
Java supports all the basic arithmetic operators as listed in below table.
Integer Arithmetic
Arithmetic involving only integer type of operands is called as Integer Arithmetic. Integer
arithmetic always yields an integer value.
Mixed-mode Arithmetic
Arithmetic involving both real and integer type of operands is called as Mixed-mode Arithmetic.
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.
Logical Operators
An expression which combines two or more relational expressions is called as a logical
expression or a compound relation expression.
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.
The increment and decrement operators are extensively used in looping statements such as
for, while,and do.
where exp1, exp2, and exp3 are the expressions. The conditional operator works asfollows:
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.
High Priority: * / %
Low Priority: + -
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();
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
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:
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
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
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.
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.
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.
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.
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":
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:
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.
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:
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 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:
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.