OOC Mod2@AzDOCUMENTS - in
OOC Mod2@AzDOCUMENTS - in
OOC Mod2@AzDOCUMENTS - in
Syllabus:
Data types and other tokens: Boolean variables, int, long, char, operators,
arrays, white spaces, literals, assigning values; Creating and destroying
objects; Access specifiers.
Beautiful thought:” You cannot change your future but, you can change your habits & surely your habits will
change your future”- Dr. APJ Abdul kalam.
Introduction: Java is a general purpose programming language. We can develop two types
of Java application. They are:
(1). Stand alone Java application.
(2). Web applets.
Stand alone Java application: Stand alone Java application are programs written in
Java to carry out certain tasks on a certain stand alone system. Executing a stand-alone
Java program contains two phases:
(a) Compiling source coded into bytecode using javac compiler.
(b) Executing the bytecodede program using Java interpreter.
Java applet: Applets are small Java program developed for Internet application. An
applet located on a distant computer can be downloaded via Internet and execute on local
computer.
Java Environment:
Java Features:
3. Object oriented
In java everything is an Object. Java can be easily extended since it is based on the
Object model.java is a pure object oriented language.
5. Distributed.
Java is designed for the distributed environment of the internet.java applications can
open and access remote objects on internet as easily as they can do in the local system.
Java is designed to be easy to learn. If you understand the basic concept of OOP java
would be easy to master.
With Java's multi-threaded feature it is possible to write programs that can do many
tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
8. High performance
Description:
(1) Class declaration: “class sampleone” declares a class, which is an object-
oriented construct. Sampleone is a Java identifier that specifies the
name of the class to be defined.
(2) Opening braces: Every class definition of Java starts with opening
braces and ends with matching one.
(3) The main line: the line “ public static void main(String args[]) “ defines a
method name main. Java application program must include this main. This
is the starting point of the interpreter from where it starts executing. A
Java program can have any number of classes but only one class will have
the main method.
(4) Public: This key word is an access specifier that declares the main
method as unprotected and therefore making it accessible to the all
other classes.
(5) Static: Static keyword defines the method as one that belongs to the
entire class and not for a particular object of the class. The main must
always be declared as static.
(6) Void: the type modifier void specifies that the method main does not
return any value.
(7) The println: It is a method of the object out of system class. It is
similar to the printf or cout of c or c++.
2. Save the above program with .java extension, here file name and class name should
be same, ex: Sampleone.java,
3. Open the command prompt and Compile the above program
javac Sampleone.java
From the above compilation the java compiler produces a bytecode(.class file)
4. Finally run the program through the interpreter
java Sapleone.java
More Examples:
Java program with multiple lines:
Example:
import java.lang.math;
class squreroot
{
public static void main(String args[])
{
double x = 5;
double y;
y = Math.sqrt(x);
System.out.println(“Y = “ + y);
}
}
Java command line arguments: Command line arguments are the parameters that
are supplied to the application program at the time when they are invoked. The main()
method of Java program will take the command line arguments as the parameter of the
args[ ] variable which is a string array.
Example:
Class Comlinetest
{
public static void main(String args[ ] )
{
int count, n = 0;
string str;
count = args.length;
System.out.println ( “ Number of arguments :” + count);
While ( n < count )
{
str = args[ n ];
n = n + 1;
System.out.println( n + “ : “ + str);
}
}
}
Run/Calling the program:
javac Comlinetest.java
java Comlinetest Java c cpp fortran
Output:
1 : Java
2:c
3 : cpp
4 : fortran
Java API:
Java standard library includes hundreds of classes and methods grouped into several
functional packages. Most commonly used packages are:
(a) Language support Package.
(b) Utilities packages.
(c) Input/output packages
(d) Networking packages
(e) AWT packages.
(f) Applet packages.
Java Tokens
Constants: Constants in Java refers to fixed value that do not change during the
execution of program. Java supported constants are given below:
Integers Type: Java provides four types of Integers. They are byte, sort, Int, long. All
these are sign, positive or negative.
Byte: The smallest integer type is byte. This is a signed 8-bit type that has a range
from –128 to 127. Bytes are useful for working with stream or data from a network or file.
They are also useful for working with raw binary data. A byte variable is declared with the
keyword “byte”.
byte b, c;
Short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This
data type is most rarely used specially used in 16 bit computers. Short variables are
declared using the keyword short.
short a, b;
int: The most commonly used Integer type is int. It is signed 32 bit type has a
range from –2147483648 to 2147483648.
int a, b, c;
long: Long is a 64 bit type and useful in all those occasions where Int is not enough.
The range of long is very large.
long a, b;
Floating point types: Floating point numbers are also known as real numbers are useful
when evaluating a expression that requires fractional precision. The two floating-point
data types are float and double.
float: The float type specifies a single precision value that uses 32-bit storage.
Float keyword is used to declare a floating point variable.
float a, b;
double: Double DataTips is declared with double keyword and uses 64-bit value.
Characters: The Java data type to store characters is char. char data type of Java uses
Unicode to represent characters. Unicode defines a fully international character set that
can have all the characters of human language. Java char is 16-bit type. The range is 0 to
65536.
Boolean: Java has a simple type called boolean for logical values. It can have only one of
two possible values. They are true or false.
Key Words: Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Most statement
contains an expression that contains the action carried out on data. The compiler recognizes
the tokens for building up the expression and statements. Smallest individual units of
programs are known as tokens. Java language includes five types of tokens. They are
(a) Reserved Keyword (d) Operators
(b) Identifiers (e) Separators.
(c) Literals.
(1) Reserved keyword: Java language has 60 words as reserved keywords. They
implement specific feature of the language. The keywords combined with
operators and separators according to syntax build the Java language.
(2) Identifiers: Identifiers are programmer-designed token used for naming
classes methods variable, objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.
(3) Literals: Literals in Java are sequence of characters that represents constant values
to be stored in variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
(4) Operators: An operator is a symbol that takes one or more arguments and operates
on them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code are divided
and arranged. Some of the operators are:
1. Parenthases()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .
Java character set: The smallest unit of Java language are its character set used to write
Java tokens. This character are defined by unicode character set that tries to create
character for a large number of character worldwide.
The Unicode is a 16-bit character coding system and currently supports 34,000
defined characters derived from 24 languages of worldwide.
Variables: A variable is an identifier that denotes a storage location used to store a data value.
A variable may have different value in the different phase of the program. To declare one
identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
Declaring Variable: One variable should be declared before using. The syntax is
Variable-name = Value;
Initializing by read statements: Using read statements we can get the values in the
variable.
Scope of Variable: Java variable is classified into three types. They are
Class Variable: Class variable is global to the class and belongs to the entire set of object
that class creates. Only one memory location is created for each class variable.
Local Variable: Variable declared inside the method are known as local variables. Local
variables are also can be declared with in program blocks. Program blocks can
be nested. But the inner blocks cannot have same variable that the outer blocks are
having.
Arrays in Java
Array which stores a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
Example:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
JDK 1.5 introduced a new for loop known as for-each loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
1.9
2.9
3.4
3.5
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
Example :
public class Test
{
public static void main(String[] args)
{
int i = 100; Output :
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required Int value 100
System.out.println("Int value "+i); Long value 100
System.out.println("Long value "+l); Float value
System.out.println("Float value "+f); 100.0
}
Example :
Java operators:
Java operators can be categorized into following ways:
(1) Arithmetic operator
(2) Relational operator
(3) Logical operator
(4) Assignment operator
(5) Increment and decrement operator
(6) Conditional operator
(7) Bitwise operator
(8) Special operator.
Relational Operator:
< : Is less then
<= : Is less then or equals to
: Is greater then
>= : Is grater then or equals to
== : Is equals to
!= : Is not equal to
Logical Operators:
&& : Logical AND
|| : Logical OR
! : Logical NOT
Assignment Operator:
+= : Plus and assign to
-= : Minus and assign to
*= : Multiply and assign to.
/= : Divide and assign to.
%= : Mod and assign to.
= : Simple assign to.
Increment and decrement operator:
Example:
Bitwise operator works on bits and performs bit-by-bit operation. Assume if
a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Binary Left Shift Operator. The left operands value is moved left by A << 2 will give 240
<<
the number of bits specified by the right operand. which is 1111 0000
Binary Right Shift Operator. The left operands value is moved right A >> 2 will give 15 which
>>
by the number of bits specified by the right operand. is 1111
Shift right zero fill Operator. The left operands value is moved right
A >>>2 will give 15
>>> by the number of bits specified by the right operand and shifted values
which is 0000 1111
are filled up with zeros.
Special Operator:
Instanceof operator: The instanceof operator is a object reference operator
that returns true if the object on the right hand side is an instance of the class given in
the left hand side. This operator allows us to determine whether the object belongs to the
particular class or not.
Person instanceof student
The expression is true if the person is a instance of class student.
Dot operator: The dot(.) operator is used to access the instance variable
or method of class object.
Example Programs
class arithmeticop
{
public static void main(String args[])
{
float a=20.5f; float b=6.4f;
System.out.println("a = " + a);
System.out.println("b = " + b );
System.out.println("a + b = " + (a+b));
}
}
class Bitlogic
{
public static void main(String args[])
{
String binary[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"};
int a = 3;
int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a&b)|(a & ~b);
System.out.println("a or b :"+binary[c]);
System.out.println("a and b : "+binary[d]);
System.out.println("a xor b : "+binary[e]);
System.out.println("(~a&b)|(a & ~b) : "+binary[f]);
}
}
Control Statements
Decision making statements:
1.Simple If statement:
The general form of single if statement is :
If ( test expression)
{
statement-Block;
}
statement-Blocks;
2. If- Else statement:
The general form of if-else statement is
If ( test expression)
{
statement-block1;
}
else
{
statement-block2
}
3. Else-if statement:
statement block2;
}
}
else
{
statement block 3
}
5. The switch statements:
Loops In Java: In looping a sequence of statements are executed until a number of time or until
some condition for the loop is being satisfied. Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
(1) While loop:
The general structure of a while loop is:
Initialization
While (test condition)
{
body of the loop
}
(2) Do loop:
The general structure of a do loop is :
Initialization
do
{
Body of the loop;
}
while ( test condition);
Continue statement: The “continue” statement will cause skipping some part of the loop.
Labeled loops: We can put a label for the loop. The label can be any Java recognized
keyword. The process of giving label is
Label-name : while (condition)
{
Body ;
}
class BreakTest
{
public static void main(String args[])
{
boolean t= true;
first:
{
second:
{
third:
{
System.out.println("Third stage");
if(t)
break second;
System.out.println("Third stage complete");
}
System.out.println("Second stage");
}
System.out.println("First stage");
}
}
}
class ContinueTest
{
public static void main(String args[])
{
outer: for(int i=0;i<10;i++)
{
for(int j = 0; j<10;j++)
{
if(j>i)
{
System.out.println("\n");
continue outer;
}
System.out.print(" "+(i*j));
}
}
//System.out.println(" ");
}
}
class ReturnTest
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return");
if(t) return;
System.out.println("After return");
}
}
Methods, Variables and Constructors that are declared private can only be
accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.
A class, method, constructor, interface etc declared public can be accessed from
any other class. Therefore fields, methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the
public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by
its subclasses.
Variables, methods and constructors which are declared protected in a superclass can
be accessed only by the subclasses in other package or any class within the package of the
protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.A variable or method declared without any access control
modifier is available to any other class in the same package. The fields in an interface are
implicitly public static final and the methods in an interface are by default public.
Advantages of JAVA:
• It is an open source, so users do not have to struggle with heavy license fees each year.
• Platform independent.
• Java API's can easily be accessed by developers.
• Java perform supports garbage collection, so memory management is automatic.
• Java always allocates objects on the stack.
• Java embraced the concept of exception specification.
• Multi-platform support language and support for web-services.
• Using JAVA we can develop dynamic web applications.
• It allows you to create modular programs and reusable codes.
Questions
1. List & explain the characteristics features of java language. (10 Marks)
2. Briefly discuss about the java development tool kit. (07 Marks)
3. Explain the process of building and running java application program (05Marks).
4. Explain the following: a)JVM b)Type casting. (05Marks)
5. Class Example{
public static void main(String s[]) {
int a;
for(a=0;a<3;a++){
int b=-1;
System.out.println(“ “+b);
b=50;
System.out.println(“ “+b);
}
}}
What is the output of the above code? If you insert another ‘int b’ outside the for loop
what is the output. (05Marks)
6. With example explain the working of >> and >>>. (06Marks)
7. What is the default package & default class in java? (02Marks)
8. Write a program to calculate the average among the elements {4, 5, 7, 8}, using for
each in java. How for each is different from for loop? (07Marks)
9. Briefly explain any six key consideration used for designing JAVA
language.(06Marks)
10. Discuss three OOP principles. (06Marks)
11. How compile once and run anywhere is implemented in JAVA language? (04Marks)
12. List down various operators available in JAVA language. (04Marks)
13. What is polymorphism? explain with an example. (04Marks)
14. Explain the different access specifiers in java, with examples. (06Marks)
15. a)int num,den;
if(den!=0&&num|den>2)
{
}
b)int num,den;
if(den!=0&num|den==2)
{
}
Compare & explain the above two snippets. (02Marks)
16. Write a note on object instantiation. (02Marks)
17. Explain type casting in JAVA
18. With a program explain break, continue and return keyword in java