0% found this document useful (0 votes)
15 views19 pages

Java - UNIT I

The document provides an overview of Java programming, including its evolution, basic program structure, and key components such as tokens, statements, and data types. It outlines the significance of the Java Virtual Machine (JVM) and command line arguments, as well as constants, variables, and their respective data types. The document serves as an introductory guide for students in a Java programming course.
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)
15 views19 pages

Java - UNIT I

The document provides an overview of Java programming, including its evolution, basic program structure, and key components such as tokens, statements, and data types. It outlines the significance of the Java Virtual Machine (JVM) and command line arguments, as well as constants, variables, and their respective data types. The document serves as an introductory guide for students in a Java programming course.
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/ 19

III B.

Sc CS Java Programming Siri PSG Arts & Science College for Women

UNIT – I

1.1 JAVA EVOLUTION


 Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl, and
many others.
 We can use Java to write computer applications that play games, store data or do any of the
thousands of other things computer software can do.
Java Milestones
Year Development
1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer
electronic devices
1991 The team announced a new language named ‘Oak’
1992 Green Project team by Sun, demonstrated the application of their new language to control a list of
home appliances using a hand-held device
1993 WWW appeared on the Internet and transformed the text-based Internet into a graphical-rich
environment
1994 The team developed a Web browser called “HotJava” to locate and run applet programs on
Internet
1995 Oak was renamed “Java”
1996 Sun releases Java Development Kit 1.0
1997 Sun releases Java Development Kit 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 JDK 5.0 was released

1.2 SIMPLE JAVA PROGRAM


Class Classname
{
public static void main (String args[ ])
{
System.out.println (“Hai!”);
}
}

1
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Class declaration:
- Class Classname  declares a class, which is an object-oriented construct. Java is a true object-
oriented language and therefore everything must be placed inside a class. Class is a keyword.

Opening brace:
- Every class definition in java begins with an opening brace “{“and ends with matching closing brace
“}” appearing in the last line.
Main line:
- Public static void main (String args[ ]) defines a method named main. main() method is the starting
point for the interpreter to begin the execution of the program. A java application can have any
number of classes but only one of them must include a main method to initiate the execution.
- The main line contains a number of keywords
 public  An access specifier, methods can be accessed in other classes.
 static  This method belongs to entire class and not part of any object of the class. Main
must always be declared as static.
 Void  It states that the main method does not return any value.
- String args[ ] declares a parameter named args, which contains an array of objects of the class type
string.
The output line:
- The only executable statement in the program is:
System.out.println (“Hai1”);
- Where, println method is a member of the out object, which is a static data member of system class.
This line prints the string “Hai!”
- Println  appends a newline character to the end of the string. Every java statement must end with a
semicolon.

1.3 JAVA PROGRAM STRUCTURE


- Java program may contain many classes of which only one class defines a main method classes
contain data members and methods that operate on the data members of the class.
- Methods may contain data type declarations and executable statements.
- A Java Program may contain one or two more sections as shown in following Fig.

2
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Documentation section Suggested


Package section Optional
Import section Optional
Interface section
Optional
Class Definition Optional
Main method class
{ Essential
Main method definition
};

Fig: General structure of the JAVA program


Documentation section:
- It contains set of comment lines giving the name of the program, the author and other details.
Comments must explain why and what of classes and how of algorithms.
- /** … */ is known as documentation comments. It is used for generating documentation
automatically.
Package statement:
- This statement declares a package name and informs the compiler that the classes defined here
belong to this package.
Example: Package mypackage;  This statement is optional.
Import statement:
- Import statement is similar to the #include statement in C.
import mypackage.myclass;
- It instructs the interpreter to load the myclass class contained in the package student. Using import
statements, we can access to classes that are part of other named packages.
Interface statement:
- An interface is like a class but includes a group of method declarations. It is an optional section and
is used only to implement the multiple inheritance features in the program.
Class Definitions:
- A Java program may contain multiple class definitions.
- The classes are used to map the objects of real – world problems.
Main Method Class:
- The main method creates objects of various classes and establishes communications between them.
- On reaching the end of main, the program terminates and the control passes back to the operating
system.

3
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

1.4 JAVA TOKENS


 Smallest individual units in a program are known as tokens. The compiler recognizes them for
building up expression and statements
 Java includes five types of token as follows:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
 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
 The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined
character derived from 24 languages
 Most of us use only the basic ASCII characters which include letters, digits and punctuation mark
used in normal English.
1. Keywords
 Keywords are important part of Java. Java language has reserved 50 words as keywords.
 Keywords have specific meaning in Java.
 We cannot use them as variable, classes and method.
 Following table shows keywords.

2. Identifiers:
 Identifiers are programmer-created tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program.
 Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.

4
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

3. Uppercase and lowercase letters are individual.


4. They can be of any length.
 Identifier must be meaningful, easily understandable and descriptive.
3. Literals:
 Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables.
 Java language specifies five major types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
4. Operator:
 An operator is symbols that specify operation to be performed may be certain mathematical and
logical operation.
 Operators are takes one or more arguments and operated on them to produce a result.
5. Separators
 Separators are symbols used to indicate where groups of code are divided and arranged.
 They basically define the shape and function of our code.

1.5 JAVA STATEMENTS


 The statements in Java are like sentences in natural languages.
 A statement is an executable combination of tokens ending with a semicolon ( : ) mark.
 Statements are usually executed in sequence in the order in which they appear.
 Java implements several types of statements as shown in following fig.

5
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Fig: Classification of Java Statement

1.6 JAVA VIRTUAL MACHINE (JVM)


 As we know that all programming language compilers convert the source code to machine code.
 Same job done by Java Compiler to run a Java program, but the difference is that Java compiler
convert the source code into Intermediate code is called as bytecode.
 This machine is called the Java Virtual machine and it exists only inside the computer memory.
 Following figure shows the process of compilation.

Fig: Process of Compilation

 The Virtual machine code is not machine specific.


 The machine specific code is generated by Java interpreter by acting as an intermediary between the
virtual machine and real machines shown below.

6
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Fig: Process of Converting Bytecode into Machine Code


 Java Object Framework act as the intermediary between the user programs and the virtual machine
which in turn act as the intermediary between the operating system and the Java Object Framework.

1.7 COMMAND LINE ARGUMENTS


 Command line arguments are parameters that are supplied to the application program at the time or
invoking it for execution.
 We can write Java programs that can receive and use the arguments provided in the command line.
In main( ) method
pub1ic static void main (String args [ ])
 args is declared as an array of strings (known as string objects). Any arguments provided in the
command line (at the time of execution) are passed to the array args as its elements.
 We can simply access the array elements and use them in the program as we wish.
Example
Class ComLineTest
{
pub1ic static void main (string args [ ])
{
int count, i=0;
String string;
Count = args.length;
System.out.println(“Number of arguments = “ +count);
While (i<count)
{
string = args [i];
i = i+1;
System.out.println(i + “ : “ + “Java is” + string + “!”);
}
}
}

7
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

 Compile and run the program with the command line as follows:
java ComLineTest Simple Object_Oriented Distributed Robust
Secure Portable Multithreaded Dynamic
 Upon execution, the command line arguments simple, Object_Oriented, etc. are passed to the
program through the array args as discussed earlier.
 That is the element args [0] contains Simple, args [1] contains Object_Oriented, and so on.
 These elements are accessed using the loop variable i as an index like
name = args[i];
 The index i is incremented using a while loop until all the arguments are accessed.
 The number of arguments is obtained by statement
count = args.length;
The output of the program:
Number of arguments = 8
1 : Java is Simple!
2 : Java is Object_Oriented!
3 : lava is Distributed!
4 : Java is Robust!
5 : Java is Secure!
6 : Java is Portable!
7 : Java is Multithreaded!
8 : Java is Dynamic!

1.8 CONSTANTS, VARIABLES AND DATA TYPES


1.8.1 CONSTANT
- Constants in java refer to fixed values that do not change during the execution of a program.

Java Constants

Numeric Constants Character Constants

Integer Constants Real Constants Character Constants String Constants

8
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Integer Constants:
- An integer constant refers to a sequence of digits. 3 types:
 Decimal integer It consists of set of digits 0 to 9, preceded by an optional minus sign.
(Ex: 12450)
 Octal Integer  It consists of any combination of digits from the set 0 to 7 with leading 0.
(Ex: 037)
 Hexadecimal integer  It consists of sequence of digits proceeded by 0x or 0X. It may also
include alphabets A through F or ’a’ to ‘f’. It represents the number 10 to 15. (Ex: 0X2, 0X9F)
Real Constants:
- Numbers containing fractional part are called real constants.
Ex: 215.03, 0.75, -0.52, 0.0083
- It have a whole number followed by a decimal point and the fractional part. It is possible that the
number may not have digits before the decimal point or digits after the decimal point.
Ex: 215.00, 0.95, -0.71
- A real number may also be expressed in exponential or scientific notation.
Ex: 215.65  2.1565e2
Where e2 means multiply by 102. The general form is:

Syntax: Mantissa e exponent

- The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an
integer with an optional plus or minus sign.
- A floating point constant has 4 parts:
 a whole number
 a decimal point
 a fractional part
 an exponent.
Single Character Constants:
- A single character constant contains a single character enclosed within a pair of single double quote
marks. Ex: ’6’, ‘y’, ‘;’ , ‘ ‘
String Constants:
- A string contains is a sequence of characters enclosed between double quotes. The characters may be
alphabets, digits, special characters and blank spaces.
Ex: “hello java” “1979” “welcome”, “r”

9
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

1.8.2 VARIABLE
- A Variable is an identifier that denotes a storage location used to store a data value. The name can be
chosen by the programmer in a meaning way.
- Variable names consist of alphabets, digits, underscore (-) and dollar characters, subject to following
conditions:
Rules:
 They must not begin with a digit.
 Upper case and Lower case letters are distinct.
 It should not be a keyword.
 White space is not allowed.
 Variables names can be of any length.

1.8.3 DATA TYPES


- Data types specify the size and types of values that can be stored. The variety of data types available
allows the programmer to select the type appropriate to the needs of the application.
- Data types in Java under various categories are shown in following Fig

Data types

Primitive Non - Primitive

Numeric Non -Numeric Classes Arrays


types in
JAVA

Integer Floating point Character Boolean Interface

Fig: Data types in Java


Integer types:
 A whole number without decimal point. It can hold whole numbers.
 The size of the values depends on the integer data type.
 The size of the values that can be stored depending on the integer type.
 Java does not support the concept of unsigned types. So it may be signed ie positive or negative.
 Java supports four types of integers. They are:

10
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Type Size Minimum value Maximum value


byte 1 byte -128 127
short 2 byte -32,768 32,767
int 4 byte -2,147,483,648 2,147,483,647
long 8 byte -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Table: Size and Range of Integer Types


Floating-point types:
- A whole number with decimal point. There are two kinds of floating point storage in Java.
 The float type values are single-precision numbers while the double types represent double-
precision numbers.
 Double precision types are used when we need grater precision in storage of floating point
numbers.
 Append ‘f ‘or ‘F’ to single precision mode numbers. Ex: 1.23f, 7.5694e5f.
 Mathematical functions such as sin, cos and sqrt return double type values.

Type Size Minimum Value Maximum Value


Float 4 bytes 3.4e – 038 1.7e + 0.38
Double 8 bytes 3.4e – 038 1.7e + 308

Table: Size and Range of Floating Point Types


Character type:
- Java provides a character data type called char. It assumes a size of 2 bytes but it can hold only a
single character.
Boolean type:
 It is used to test a particular condition during the execution of the program.
 There are only two values: true or false.
 This data type is denoted by the keyword Boolean and use only one bit of storage.
 Boolean values are often used in selection and iteration statement.

1.8.4 DECLARATION OF VARIABLES


- After designing suitable variable names, we must declare them to the compiler.
- Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration decides the scope of the variable.
11
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

- A variable must be declared before it is used in the program.


- The general form of declaration of a variable is:

type variable2, variable2,…….., variableN;

- Variables are separated by commas. It must end with a semicolon.


Ex:
int count;
Float x, y;
Char c1, c2, c3;

1.8.5 GIVING VALUES TO VARIABLES


- A variable must be given a value after it has been declared but before it is used in an expression. This
can be achieved in two ways:
1. By using an assignment statement.
2. By using a read statement.
Assignment statement
- A simple method of giving value to a variable is through the assignment statement as follows:
variableName = value;
For ex, initialvalue = 0;
Finalvalue = 100;
Yes = ‘x’;
- It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
Type variablename = value;
Ex: int finalvalue = 100;
Char yes = ‘x’;
- The process of giving initial values to variables is known as the initialization.The ones that are not
initialized are automatically set to zero.
Ex: float x, y,z;
int m = 0, n = 5;
Read Statement
- We may also give values to variables interactively through the keyboard using the readLine()
method.
- The readLine() method reads the input from the keyboard as a string which is then converted to the
corresponding data type using the data type.

12
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

1.9 OPERATORS
- Java supports a rich set of operators. An operator is a symbol that is used to perform certain
mathematical or logical manipulations.
- Operators are used in programs to manipulate data and variables.

1.9.1 TYPES OF OPERATORS


- Java operators can be classified into number of related categories.
 Arithmetic Operator
 Relational Operator
 Logical Operator
 Assignment Operator
 Increment and Decrement Operator
 Conditional Operator
 Bit-wise Operator
 Special Operators

ARITHMETIC OPERATOR:
- The operators +,-,*, / and % all work the same way as they do in other languages. We can’t use these
operators on Boolean type.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo division

- These can operate on any built-in numeric data type of java. The unary minus operator, multiplies
its single operand by -1. A number preceded by a minus sign changed its sign.
Arithmetic operators are used as follows:
Example: a+b, a-b, a*b, a/b, a%b where a & b are operands

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

13
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Example: a = 14 b = 4
a - b = 10 a * b = 56 a % b = 2 a + b = 18 a / b = 3
Real Arithmetic:
- An arithmetic operation involving only real operands is called real arithmetic. A real operand may
assume values either in decimal or exponential notation.
- Floating point values are rounded to the number of significant digits permissible; the final value
approximates the correct result.
Example: a= 20.5F b= 6.4F means
a + b = 26.9
a - b = 14.1
a * b = 131.2
a / b = 3.2031
a % b = 1.3
Mixed-mode arithmetic:
- When one of the operands is real and the other is integer, the expression is called mixed-mode
arithmetic expression.
- If either operand is of the real type, then the other operand is converted to real and the real arithmetic
is performed.
Example:
15 / 10.0 produce the result 1.5
15 / 10 produce the result 1

RELATIONAL OPERATORS:
- The comparisons can be done with the help of relational operators.

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

- A simple relational expression contains only one relational operator.


Syntax: ae-1 relational operator ae-2

14
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

- Where, ae-1 and ae-2 are arithmetic expressions, which may be a simple constant, variable or
combinations of them.
Example: Expression Value
7 < 10 true
2.5 > 1.5 false
20 > 8+5 false
LOGICAL OPERATORS:
- Java language has three logical operators. They are:

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

- These operators are used to combine two or more relations to form compound conditions. It is
termed as logical expression or compound relational expressions. It also yields a value of true or
false.
Example: a >b && x = = 10
- Combines two or more relational expression is termed as a logical expression or a compound
relational expression.
Truth table
Value of expression
Op-1 Op-2
Op-1 && Op-2 Op-1 || Op-2
True True True True
True False False True
False True False True
False False False False

Example: if (age > 20 && salary < 5000)


If (number = 0 || number > 10)

ASSIGNMENT OPERATORS:
- Assignment operators are used to assign the values of an expression to a variable. Assignment
operator is = (equal to).

15
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

Syntax: V op = expression;

- Where, V is a variable; exp is an expression, op is a binary operator. The operator op = is known as


the shorthand assignment operator.
Example:
x = x + 1 is equal to x += 1
y = y + 5 is equal to y += 5
a = a * (n+1) is equal to a *= n + 1
a = a – 1 is equal to a -= 1
Advantages:
 What appears on the left-hand side need not be repeated.
 The statement is more concise and easier to read.
 The shorthand operator results in a more efficient code.

INCREMENT AND DECREMENT OPERATORS:


- The operator ++ and – is the increment and decrement operators. These two are very useful
operators.
- The ++ operator adds 1 to the operand and -- subtracts 1 from the operand. Both are unary operator
and may be used in the forms.
 ++m (or) m++
 --m (or) m--
 ++m is equivalent to m=m+1 or m+=1
 --m is equivalent to m=m-1 or m-=1
- These two operators are used in for and while loops.
Ex:
m=8 m=8
y = ++ m y = m++
Ans: y = 9 y = 8 then at next turn y = 9
- A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. A
postfix operator first assigns the value to the variable on left and then increments the operand.

CONDITIONAL OPERATOR:
- The character pair?: is a ternary operator. This operator is used to construct conditional expression
of the form:
exp1? exp2: exp3

16
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

- Where exp1, exp2 and exp3 are expressions. The exp1 is evaluated first. If it is true, then the
expression exp2 is evaluated and becomes the value of the conditional expression.
- If exp1 is false, exp3 is evaluated and its value becomes the value of the conditional expression.
Example: Equivalent to
a = 50, b = 10 if(a>b)
x = (a>b)? a : b;  x = a;
else
x = b;

BITWISE OPERATORS:
- It is used for testing the bits or shifting them to the right to left. It may not be applied to float or
double.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement or bitwise unary NOT
<< Shift left
>> shift right
>>> Shift right with zero fill
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
<<= Shift left assignment
>>>= Shift right zero fill assignment

Examples
1010  0101 (bitwise NOT)
1010 & 1111  1010 (bitwise AND- produces a 1 bit if both operands are also 1, otherwise 0)
1010 | 1110  1111 (bitwise OR- produces a 1 bit if either of the bits in the operands is a 1, otherwise 0)
1010 ^ 1111  0101 (bitwise XOR – produces a 1 bit if exactly one operand is 1, otherwise 0)

17
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

SPECIAL OPERATORS:
- Java contains two special operators. They are:
 Instance of operator.
 Member selection operator (.)

Instance of Operator:
- It is an object reference operator and returns true if the object on the left-hand side is an instance of
the class given on the right-hand side. It allows us to determine whether the object belongs to a
particular class or not.
Example: person instance of student
- It returns ‘true’ if the object person belong to class student, otherwise it is ‘false’.
Dot (.) operator:
- The dot operator is used to access the instance variables and methods of class objects.
Example: person.age; // reference to variable age
person.salary ( ); // reference to method salary ()

1.10 EXPRESSIONS
ARITHMETIC EXPRESSIONS
- An arithmetic expression is a combination of variables, constants, and operators arranged as per the
syntax of the language.

Algebraic expression Java expression

Axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c

EVALUATION OF EXPRESSION
- Expressions are evaluated using an assignment statement of the form

Variable = expression

- When the statement is encountered, the expression is evaluated first and the result then replaces the
previous value of the variable on the left-hand side.
Ex:
X = a * b – c;
Z = a – b / c + d;

18
III B.Sc CS Java Programming Siri PSG Arts & Science College for Women

1.10.1 PRECEDENCE OF ARITHMETIC OPERATORS


- An arithmetic expression without any parentheses will be evaluated from left to right using
the rules of precedence of operators.
- There are two distinct priority levels of arithmetic operators in java:
High priority * / %
Low priority + -
- During the first pass, the high priority operators are applied as they are encountered.
- During the second pass, the low priority operators are applied as they are encountered.

1.10.2 TYPE CONVERSIONS IN EXPRESSIONS


Automatic Type conversion
- If the operands are of different types, the ‘lower’ type is automatically converted to the ‘higher’ type
before the operation proceeds. The result is of the higher type.
- The final result of an expression is converted to the type of the variable on the left of the assignment
sign before assigning the value to it.
- The following changes are introduced during the final assignment.
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long to int causes dropping of the excess higher order bits.

Casting a value
- Java performs type conversions automatically.
- There are instances when we want to force a type conversion in a way that is different from the
automatic conversion.
Ex: Ratio = (float) female_number / male_number;
- The process of such a local conversion is known as casting a value. The general form is

(type-name) expression

Ex:
X = (int) 7.5 // 7.5 is converted to integer by truncation
Z =(int) a+b // a is converted to integer and then added to b;

________________________________END OF UNIT – I_______________________________________

19

You might also like