Introduction To Java

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

Introduction to Java FEATURES OF JAVA

1. It is simple and platform independent.


Java is an object-oriented programming language with a built-in Application 2. It is robust and secure.
Programming Interface (API) that can handle graphics and user interfaces and that 3. It supports multithreading
can be used to create applications or applets. 4. IT provides JVM and API for coding
It was developed by James Gosling in the year 1991. 5. It is distributed and dynamic in nature.

The previous name of Java was ‘Oak’.


JAVA VIRTUAL MACHINE (JVM)
Features of High Level Language JVM is a special interpreter provided by Java which converts byte code into machine
instructions. It is independent of any computer system. Java interpreter appears and
1. It provides an easy and efficient way to write a program. behave like a virtual processor chip that is why it is known as Java virtual machine.
2. It follows syntax for writing programs.
3. The program written in high level language is known as source code.
4. The source code is converted to machine code either with the help of compiler JAVA API (Application Programming Interface)
or interpreter.
5. A high level language can be classified as procedure-oriented programming Application Programming Interface is a library of codes which are used in programs.
language or object-oriented programming language. It is a collection of variables and function that programmers use in their programs.
6. Examples are: COBOL, FORTRAN, C++, Java etc JVM when combines with API form the JAVA platform.

PROCEDURE-ORIENTED PROGRAMMING LANGUAGE BYTECODE


It follows a top-down approach in execution. A group of instructions is organized into Java Bytecode is the form of instructions that the Java virtual machine executes.
functions. Data is accessed through functions. Examples : C. FORTRAN. PASCAL Each bytecode instruction is one byte in length. The bytecode is independent of the
computer system it has to run upon.
OBJECT-ORIENTED PROGRAMMING LANGUAGE It is similar to machine language but it is same on every platform.
It follows a bottom-up approach and is based on the concepts of objects. Objects UNICODE
contain functions to perform a task on a given data. Example : C++, Java
It is a two byte character code set that has character representing almost all
CONCEPTS OF OOPs character in almost all human alphabets and writing system around the world
including English, Arabic, Chinese and many more.
There are 7 OOPs concepts:
1. Class 5. Inheritance
2. Object 6. Polymorphism JAVA COMPILATION
3. Encapsulation 7. Message passing The program written by the user is known as source code. The source code is
4. Abstraction converted into machine language with the help of a compiler. The process of
converting source code into machine language is known as compilation.
FEATURES OF OOPs CONCEPTS
1. It stands for Object -Oriented Programming In Java, after compilation, the source code gets converted into a special format
2. A program contains small segments called objects where each object contains called byte code with the help of compiler. This byte code is independent of the
data and functions to perform task. computer system it has to run upon. The byte code is converted in to machine
3. Emphasis is laid on data security. Data is hidden and can be used only though language with the help of interpreter. Thus Java uses both compiler and interpreter
functions. for translation.
4. Inclusion of new data and function is easier.
Compiler Interpreter
Source code Byte code Machine language
(.java) (.class) (.exe)
3. Logical error
TYPES OF JAVA PROGRAM It occurs due to incorrect code or a bug in the program that results in an
unexpected result or abrupt termination of the program. Eg. Using a variable
There are two types of Java Programs:
before initializing.
▪ Web appilcations – It contains interactive web pages and require a web
browser to view the web pages. CLASS
▪ Stand – alone application – It runs on a computer which are either
console based or GUI based. Class is a user defined data type, which encapsulates data and method. The data
is protected inside a class and can be accessed by methods present in the class. A
TYPES OF COMMENT STATEMENTS class is created by ‘class’ keyword along with a valid name.
Example:
There are two comment styles in Java.
class HelloJava
• Single line comment ( // ) {
• Multiple line comments ( /* … */ ) public static void main (String args[]) throws IOException
{
ACCESS SPECIFIERS System.out.println (“Hello Java”);
}
}
They are used to set levels of access to classes, methods, variables etc.
eg public, private, protected and friendly
OBJECT
PACKAGE
It contains groups of similar type of classes. It can be in-built or user-defined. An object is an entity, which has got a specific identity, a specific characteristics and
There are 6 in-built packages available – a specific behaviour.
1. java.io 4. java.awt Example: A ‘person’ or a ‘chair’ or a ‘table’ can be considered as an object. All these
2. java.util 5. java.net have a name for identity, characteristics like colour, size, height and behaviour like
3. java.lang 6. Java.applet talking, walking, laughing etc.
java.lang is the default package which are automatically imported to
any java program. ENCAPSULATION

The wrapping up of data (i.e. characteristics) and functions (i.e. behaviour) into a
import keyword single unit (called class) is known as Encapsulation.
It a predefined reserved keyword to make a package available to a program. The data is hidden inside the class and cannot be accessed outside the class. It can
only be accessed through the methods present inside the class. This hiding of data
DEBUGGING from direct access is known as Data Hiding.
It is the process of identifying and resolving errors in a program.
It is of three types: ABSTRACTION
The act of representing essential features without knowing its internal details is
1. Compile time (Syntax) error known as Anstraction
It occurs if the rules of the programming language are not followed in the
source code. It occurs due to incorrect punctuation, incorrect word etc. Example: A person need not know the internal mechanism of the working of the car.
INHERITANCE
2. Runtime error
It occurs during the execution of the program due to certain unexpected It is the process of deriving one class from another class. It transfers the properties
conditions in the program code. Eg. Division by zero of parent class to sub-class.
IDENTIFIERS
POLYMORPHISM Identifiers are the names given to different parts of the program, like variable,
constants, class object, function, arrays etc.
‘Poly’ means ‘many’ and ‘morph’ means ‘form’. The ability to take more than one
form is known as Polymorphism. It is the process of using a function for more than
Rules for naming an identifier :
one purposes.
1. An identifier can have alphabets, digits, underscore and dollar sign.
MESSAGE PASSING
2. An identifier should not be a keyword.
The calling of the function by its name to perform any task is called message
3. The name should not start with a digit.
passing.
4. The name can be of any length.
JAVA CHARACTER SET 5. Name is case sensitive which means upper case and lower case are
treated in different manner.
Character set is a set of valid characters that a language can understand. A
character represents any letter, digit or a special symbol. Java uses Unicode
character set. Example:
Sample tot_marks sum stud1
TOKENS
cust_code _CHK isDigit SALARY
The smallest individual unit in a program is known as token.
Java provides following tokens:
PUNCTUATORS (Separators)
1. Keyword 4. Operator
2. Identifiers 5. Literal Separators are the characters which are used to separate any two statements, block
3. Punctuators of statements, expressions, variables etc. There are 9 separators used in Java.

KEYWORDS () Brackets
{} Curly Braces
Keywords are reserved words which have a special meaning. They are used for a
[] Square Bracket
specific purpose. The name of the keyword is not used as the name of any identifier.
Following are the keywords used in java: ; Semilcolon
, Comma
. Full Stop
abstract default if private this
LITERALS
boolean do implements protected throw
Literals are data items which are fixed data values. Java provides following literals:
break double import public throws 1. Integer literal
2. Floating Literal
byte else instanceof return transient 3. Boolean literal
case extends int short try 4. Character Literal
5. String literal
catch final interface static void 6. Null literal
char finally long strictfp volatile
• Integer Literal
class float native super while
An integer constant has a digit and does not contain any decimal point. The
const for new switch continue digit can have a – or – sign, which means it can be either positive or negative.
Example: 4 -9 67
goto package synchronized
\’ Single quote
• Floating Literal
\” Double quote
A floating or real literal is a number having a decimal value or fractional part.
They may be written as a fraction or exponent form. DATATYPES
Example: 34.5 -17.9 135E05
• Boolean Literal Data type specifies the type of data type used in the program. There are two types
of datatypes available in Java:
A Boolean literal has two types of value, represented as true or false. The
default value of Boolean data type is false. ▪ Primitive data type
▪ Reference data type OR Non-Primitive data type
• Character Literal
Reference data type
A character literal contains one character, which is enclosed within single
quotation marks. A reference data types give the reference of the values. It refers to the memory
Example : ‘a’ ‘@’ ‘\n’ ‘c’ address of the value using a pointer. The address of the value or a set of values is
stored in the name of the variable. Class, arrays and interface are examples of
• String Literal reference data type.

A string literal is a combination of characters forming a word or a sentence. It Primitive data type
is enclosed within double quotation marks.
Example: “java” “How are you?” Primitive data types are the fundamental or the pure data type offered by Java. The
word ‘primitive’ means a fundamental component that may be used to create other
• Null Literal larger parts. Java supports following four types of primitive data types:

Null means ‘nothing’ or ‘no value’. A null literal has a null value, which means it ▪ Numeric Integral primitive types
is empty without any value. ▪ Fractional primitive types
▪ Character primitive types
ESCAPE SEQUENCE ▪ Boolean primitive types
Java allows nongraphic characters. The nongraphic cannot be typed directly from
the keyboard viz. backspace, carriage return, tab etc. These can be represented by i. Numeric Integral primitive types
escape sequence. An escape sequence is represented by a backslash (\) followed It stores whole numbers, which means numeric values without any decimal
by a character. Following table lists escape sequences: point. The value can be positive or negative. There are four numeric integral
types in Java.
byte int
Escape Sequence NonGraphic Character short long
\a Audible alert ii. Fractional primitive types
\b Backspace It stores numeric values having a fractional part, which means the value
\f Formfeed having a decimal point. The value can be positive or negative. They are known
as floating-point datatypes. The floatinf values are represented by two
\n New line
datatypes:
\r Carriage return float double
\t Horizontal tab
iii. Character primitive types
\v Vertical tab
\\ Backslash
It is used to store characters. A variable defined as char type stores one
character. It can represent all ASCII (American Standard Code for
Information Interchange) as well as Unicode characters. Java supports It is an identifier which holds a value. The value of variable can be changed during
Unicode, which makes the size of char type as 16 bits, i.e., 2 bytes, as the execution of a program.
compared to 1 byte character size of other programming language. Following
Declaration of a variable:
is the data type used to represent character type.
datatype variablename;
char
Example:
iv. Boolean primitive types
int sum;
Boolean type is used to represent a single value which can be either true or float salary;
false.The words true and false are the boolean values. The term boolean is
after a great Mathematician George Boole, who believed that many problems
can be solved with the help of true and false values. The datatype used to CONSTANTS
represent a boolean value is as follows:
boolean It is an identifier which holds a value but the value can not be changed during the
execution of a program. The keyword ‘final’ is added before the declaration which
makes it a constant. Hence, the value can not be changed in the program.
Following table lists the size and range of all datatypes: Declaration of constants:

Type Size Descriptio Range Remarks final datatype variablename=value;


n Example:
8 bits (1 Byte-length
-128 to +127 int max=100;
Byte byte) integer
Short
16 bits (2 -32,768 to
Short integer Advantages of Constants:
bytes) +32,767
A constant makes a program readable and error correction becomes easy. If the
32 bits (4 Integer (about) –2 billion value of the constant needs to be changed, then the only thing that has to be done
Int
bytes) to +2 billion is to change the value from where constant is declared. It changes the value of the
constant throughout the program.
64 bits (8 Long (about) –10E18 to
Long
bytes) integer +10E18

Single-
32 bits (4 precision -3.4 E + 38 to Precision upto 6
Float
bytes) Floating +3.4 E + 38 digits
point
Double-
64 bits (8 precision -1.7 E +308 to 1.7 Precision upto 15
Double
bytes) Floating E +308 digits
point
Single
16 bits (2
Char character 0 to 65,535 Unicode characters
bytes)
Java
reserves 8 Used for logical test
Boolean bits but Boolean true or false along with if
uses only 1 value statement
bit

VARIABLE
OPERATORS IN JAVA == Equal to
An operator is a symbol used to perform calculation. The objects on which the != Not equal to
operator operates are known as operands. Depending upon the number of
operands, there are two types of operators:
Unary Operator: It operates on only one operand. LOGICAL OPERATOR
These operators are used to check for multiple conditions. When there are more
+ - than one if conditions , then they can be used.
• Unary Plus ( + ) Operator Meaning
&& Logical AND
• Unary Minus ( - )
|| Logical OR
Example: ! Logical NOT
If a = 6, then –a means –6
If a = -10, then +a means –10
Logical AND (&&- Ampersand)
If a = 34, then +a means 34
It checks for two conditions, it evaluates to true if both the conditions are true else
Binary Operator: It operates on two operands. it returns false.
+- * / % Condition 1 Condition 2 Result
Example: True True True
5 + 6, results in 11 True False False
a * 2, results in 8, if a=4 False True False
False False False

ARITHMETIC OPERATOR : Example:


It performs arithmetic calculations. if (a>b && a>c)
System.out.println (“a is greatest”);
Operator Meaning Logical OR ( || - Pipe)
+ Addition
It checks for two conditions, it evaluates to true if either of the conditions is true
- Subtraction else it returns false.
* Multiplication
/ Division (returns quotient after dividing) Condition 1 Condition 2 Result
True True True
% Modulus (returns remainder after dividing) True False True
False True True
False False False
RELATIONAL OPERATOR :
A relational operator compares two operands to determine whether one is greater Example:
than, greater than or equal to, less than, less than or equal to the other: if (ch=’a’ || ch=’e’ || ch=’i’ || ch=’o’ || ch=’u’ )
System.out.println(“It is a vowel”);
Operator Meaning Logical NOT ( ! )
> Greater than It negates the value. It returns true, if the condition is false and vice- versa.
< Less than
>= Greater than equal to Condition Result
True False
<= Less than equal to False True
Example:
%= x%=y x=x %y
int a=10;
while ( ! a == 7)
{
More Examples:
System.out.println(a);
a--; 1. x = x + ( y * 1 ) can be written as x+=(y*1)
}
2. x = x / ( a – b ) can be written as x/=(a–b)
Output
10
Diference between = & ==
9
8 =(equal to) is an assignment operator. It is used to assign a value to a variable or
The loop will stop when the value of ‘a’ is equal to 7. constant.
Example: a=10; //means 10 is assigned to variable a
ASSIGNMENT OPERATOR
==(double equal to) is a relational operator. It is used to check for equality and
‘=’ is the assignment operator which is used to assign a value to a variable. used with if statement.
Java provides shorthand notation for assignment operator. Example: if (a==10) // it checks whether 10 is present in ‘a’ or not
Example:
Operator + with Strings
a = a + 1;
The ‘+’ operator is used for concatenation (joining), when used with strings. With
can be written as : a++; numbers, it acts as an arithmetic operator and with strings; it is used as a joining
operator.
SHORTHAND NOTATION
Example:
Java provides short hand notation for assignment. System.out.println (10+20); // will return 30
Syntax: System.out.println (“10”+ “20”); // will return 1020
var = var operator expression
is same as : System.out.println (“JDK”+ “1.5”); // will return JDK1.5
var operator expression

Example: Increment / Decrement operator (++/- -)


a = a + 5;
can be written as a++ Post Increment
a + = 5; ++a Pre Increment
is equivalent to a=a+1
Assignment Shortcuts
a-- Post Decrement
Operator Example Meaning
--a Pre decrement
+= x+=y x=x+y
is equivalent to a = a – 1
-= x-=y x=x-y
‘Post’ means ‘after’ and ‘Pre’ means ‘before’. Post increment means the expression
*= x*=y x=x*y is solved first and then increment is done. In pre increment, first the increment is
done and then the expression is solved. Same is the case with Post decrement and
/= x/=y x=x/y
pre decrement.
Pre – Increment (Change – then – use ) CONDITIONAL OPERATOR OR TERNARY OPERATOR

In pre increment, first the increment is done and then the expression is solved. The ?: operator is known as conditional operator or ternary operator. It requires
three operands to operate, hence the name Ternary Operator. It is a shortcut and
int a=5, b=2; easier method to use if…else statement. The condition is written before ‘?’ followed
b = b * ( + + a ); by true statement and after ‘:’ follows the false statements.
=2*(++5)
=2*6 Syntax
= 12 var = condition ? True: False
After change : a = 6, b=12 Example
if(a>b)
Post – Increment (Use – then – change ) x=a;
else
Post increment means the expression is solved first and then increment is done. x=b;

int a=5, b=2;


b = b * ( a + + ); is written as :
= 2 * ( 5 + + ) // first use then increment
=2*5 x = a > b?
= 10 a : b;
After change : a = 6, b=10

Example: Use of Ternary Operator


If a=5, b=3, then
This ternary operator's most common usage is to make a terse simple conditional
1. x = ( a + + ) + b assignment statement. For example, if we wish to implement some C code to
=5+3 change a shop's opening hours to 12 o'clock in weekends, and 9 o'clock on
=8 (a=5, b=3 and then a is incremented to 6, weekdays, we may use
a=6,b=3)
int opening_time = (day =7) ? 12 : 9;
2. x = ( + + a ) + b
=6+3 instead of the more verbose
=9 (a is first incremented to 6 & then added to b)
int opening_time;
3. x = (a + + ) + b + a
=5+3+6 if (day == 7)
= 14 (After assigning 5 to a, it is incremented to 6) opening_time = 12;
else
4. x = ( + + a ) + b + a opening_time = 9;
=6+3+6
= 15 (First a is incremented & then assigned to a)
The two forms are nearly equivalent. Keep in mind that the ?: is an expression and
if-then-else is a statement. Note that neither value if true nor value if false
expressions can be omitted from the ternary operator without an error report upon
parsing. This contrasts with if..else statements, where the else clause can be
omitted.
OPERATOR PRECEDENCE Problems :
It determines the order in which the expression is solved. Depending upon the
precedence, the operator is given priority while solving an expression Q 1. If a=10, b=3, c=7, then solve the following expressions:

Precedence from higher to lower 1. x = a + b * c


x=a+(b*c) // Multiplication gets high precedence
[ ],( ) Bracket Left to Right = 10 + ( 3 * 7 )
*, /,% Multiply, Divide, Modulus Left to Right = 10 + 21
+, - Add, Subtract Left to Right = 31

Brackets [ ], ( ) are given higher priority which means brackets are solved first. It is 2. x = a + c – b
followed by Multiplication, Division, Modulus then Addition and Subtraction. x=(a+c)–b // Addition & Subtraction have same
Multiply, Division, Modulus are at the same priority level, hence to solve them, the precedence, so Left to Right
rule of Left to Right is followed, which means the operator present at the left side = ( 10 + 7 ) – 3
is solved first. Same is the case with Add and Subtract. Both are at the same level, = 17 – 3
so rule of Left to Right is followed. = 14
3. x = a + ( c – b )
Example: = 10 + ( 7 – 3 ) // First bracket is solved
x=a+b-c = 10 + 4
In this expression, since + & - are at the same level, left to right is followed which = 14
means first a+b is solved and then c is subtracted from the result. 4. x = ( a + b + c ) % a
But if bracket is present in the expression then the expression is solved according = ( 10 + 3 + 7 ) % 10
to the bracket = 20 % 10
x=a+(b–c) =0

Since bracket gets a higher precedence, hence first the expression inside the 5. x = a * b % c
bracket is solved. First (b-c) is solved and then the result is added to a. x=(a*b)%c // Multiplication & Division are at the same level,
so Left to Right
= ( 10 * 3 ) % 7
OPERATOR ASSOCIATIVITY
= 30 % 7
=2
An associativity rule determines the grouping of operands and operators. In the
expression, more than one operator is present having the same precedence. When
the precedence of the operators is same, then the expression in evaluated from left
to right.

Example:
x = a + b - c;
In the above example, + & - have the same precedence. In this case, it is
evaluated from left to right, i.e. first addition is done followed by subtraction. If the
expression is given as
x = a + ( b – c );
In this example, brackets are given high priority, so first subtraction is done and
then addition.
OUTPUT STATEMENT Difference between Interpreter and Compiler

The output statement or the print statement is used to print the result or output on Interpreter is a translator, which converts a source code into machine code, line by
the screen. The print statement in Java is line.
Compiler is a translator, which converts a source code into machine code, all at
System.out.print ( ); once.

There are two types of print statements:


1. System.out.print ( )
It prints the next output in the same line.
Example:
for (i=0;i<=5;i++) End of Theory
System.out.print (i);
Output:
12345
2. System.out.println ( ):
It prints the output in a new line.
Example:
for (i=0;i<=5;i++)
System.out.println (i);
Output:
1
2
3
4
5

Example:
System.out.println (“HELLO JAVA”);
Output : Hello Java
System.out.println (“Sum is”+ sum);
Output : Sum is 30
System.out.println (a+b);
Output : 20 30
System.out.println (“a=”+a);
Output : a=20
System.out.println (“a=”+ a +”b=”+ b);
Output : a=10 b=20
Q3. What will be the output of
PRACTICE WORKSHEET
(i) 42 / 7 =_____ (ii) 42 % 7 =_____ (iii) 15/4 =_____ (iv) 15%4 = _____
Q1. Solve the following expression:
Q4. If a = 57, b=3, then int c= a / b ____________
(i) if x = 2, then evaluate: a) ++x > =5 b) x ++ < =5
(ii) if x = 82, then evaluate: a) y = ++x b) y = x ++ Q5. What will be the output for the following program segment?
(iii) if x=20, evaluate a) y= (++x) % 4 b) y = (x++) % 4 i) int a = 10,b=30,c=40;
(iv) If x = 9, y = 5, determine the value of x after executing x += (++x) % y a= --b + c * a / 2;
(v) If a = 6, b = 4.5, then solve the following expression: System.out.print("a" + a);
a) x = ( ++a) + b + a b) x = ( a++) % b c) x = a * b % a System.out.print("b " +b );
vi) What will be the value of x after evaluating x += x ++ + --x + 4 ; ii) int x=13, y=5 ;
if x = 3 before the evaluation? System.out.println (x++ + x + --y );
vii) What will be the value if x=3 initially, x+=x++---x+x -- iii) int c=900, x, n =2000;
viii) What will be the value if a=5 initially a- - + ++a%4
x = n+ c >2550? 1350 : 1500 ;
(ix) What will be the result stored in x and y after evaluating the following: System.out.println(x);
Assume that initially x = -2 and y = 5. Q6. Write the output of following statements :
(i) x = ++y – x (ii) y + = x class Demo
(x) Find the result of the following expression if the values of x=10, y=5 & z=11 {
(i) x++ * y + z (ii) ++x * y + z public void fmn( )
(xi) If x = 10 , y= 5, calculate the value of z = ++x - y-- + x++ + y – x {
int a=12,b=10;
(xii) If a = 10, then solve the following expression:
System.out.println (“a++=”+a++);
a) x = ( a++) + (a++) + ( ++a)
System.out.println (“a>b=”+a>b);
b) x = a + ( a++) + ( ++a) + (++a) + (a++) % a
System.out.println (“++a=”+++a);
c) a+=a + (++a) + (a++) + a + a++
System.out.println (“--a=”+--a);
d) x= ++a + ++ a + ++a + a++ -a
System.out.println (“a!=(a+b)=”+a!=(a+b));
e) a+=++a /a
}
Q2. Suppose A,B,C are integer variables where A = 3, B = 3, C = 5 and X,Y,Z }
are the floating point variables where X = 8.8, Y = 3.5, Z = -5.2. Determine the
value of the following expressions:
End of Worksheet
i) A%C iv) X / Y
ii) ( A * C ) % B
iii) X / ( X+Y ) v) (int) X % (int) Y

You might also like