Module 2-Introduction To JAVA
Module 2-Introduction To JAVA
Module 2-Introduction To JAVA
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.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 1
Object Oriented Concepts-Module 2 10CS44
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 2
Object Oriented Concepts-Module 2 10CS44
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 environment includes a large number of development tools and hundreds of classes and
methods. The Java development tools are part of the systems known as Java development kit (JDK)
and the classes and methods are part of the Java standard library known as Java standard Library
(JSL) also known as application program interface (API).
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 3
Object Oriented Concepts-Module 2 10CS44
Java Features:
(1) Compiled and Interpreted
(2) Architecture Neutral/Platform independent and portable
(3) Object oriented
(4) Robust and secure.
(5) Distributed.
(6) Familiar, simple and small.
(7) Multithreaded and interactive.
(8) High performance
(9) Dynamic and extendible.
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.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 4
Object Oriented Concepts-Module 2 10CS44
8. High performance
Because of the intermediate bytecode java language provides high performance
Java Development kits(java software:jdk1.6): Java development kit comes with a number of
Java development tools. They are:
(1) Appletviewer: Enables to run Java applet.
(2) javac: Java compiler.
(3) java : Java interpreter.
(4) javah : Produces header files for use with native methods.
(5) javap : Java disassembler.
(6) javadoc : Creates HTML documents for Java source code file.
(7) jdb : Java debugger which helps us to find the error.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 5
Object Oriented Concepts-Module 2 10CS44
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
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 6
Object Oriented Concepts-Module 2 10CS44
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 7
Object Oriented Concepts-Module 2 10CS44
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.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 8
Object Oriented Concepts-Module 2 10CS44
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.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 9
Object Oriented Concepts-Module 2 10CS44
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:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 10
Object Oriented Concepts-Module 2 10CS44
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;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 11
Object Oriented Concepts-Module 2 10CS44
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
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
(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.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 12
Object Oriented Concepts-Module 2 10CS44
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:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 13
Object Oriented Concepts-Module 2 10CS44
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
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 14
Object Oriented Concepts-Module 2 10CS44
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:
Example:
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:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 15
Object Oriented Concepts-Module 2 10CS44
The array elements are accessed through the index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.
Example:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
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:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 16
Object Oriented Concepts-Module 2 10CS44
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
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:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 17
Object Oriented Concepts-Module 2 10CS44
1.9
2.9
3.4
3.5
Type Casting: It is often necessary to store a value of one type into the variable of
another type. In these situations the value that to be stored should be casted to
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;
Widening Casting(Implicit)
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 18
Object Oriented Concepts-Module 2 10CS44
Example :
Output :
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 19
Object Oriented Concepts-Module 2 10CS44
Output :
Java operators:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 20
Object Oriented Concepts-Module 2 10CS44
! : 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:
++ : Increment by One {Pre/Post)
-- : Decrement by one (pre/post)
Conditional Operator: Conditional operator is also known as ternary operator.
The conditional operator is :
Exp1 ? exp2 : exp3
Bitwise Operator: Bit wise operator manipulates the data at Bit level. These operators are
used for tasting the bits. The bit wise operators are:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 21
Object Oriented Concepts-Module 2 10CS44
Special Operator:
Instanceof operator: The instanceof operator is a object refrence 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]);
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 22
Object Oriented Concepts-Module 2 10CS44
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:
The general form of else-if statement is:
If ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
statement block3;
}
4. Nested if – else statement:
The general form of nested if-else statement is:
If ( test condition)
{
if ( test condition)
{
statement block1;
}
else
{
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 23
Object Oriented Concepts-Module 2 10CS44
statement block2;
}
}
else
{
statement block 3
}
5. The switch statements:
The general form of switch statement is:
Switch ( expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
......
default:
default block;
break;
}
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);
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 24
Object Oriented Concepts-Module 2 10CS44
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");
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 25
Object Oriented Concepts-Module 2 10CS44
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");
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 26
Object Oriented Concepts-Module 2 10CS44
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.
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
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 27
Object Oriented Concepts-Module 2 10CS44
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.
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);
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 28
Object Oriented Concepts-Module 2 10CS44
}
}}
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
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 29