Professional Documents
Culture Documents
2 mailto: shubhashree.savant@gmail.com
Introduction
Java is an High level object-oriented language developed by
James Gosling at Sun Microsystems in the mid 1990s.
Originallanguage called Oak
Intended for embedded systems
Sun describes it as
"Asimple, object-oriented, distributed, interpreted, robust, secure,
architecture neutral, portable, high-performance, multi-threaded
and dynamic language.“
HotJava
The first Java-enabled Web browser
3 mailto: shubhashree.savant@gmail.com
Java and Internet
Java’s new innovation named applet has completely changed
the internet programming
4 mailto: shubhashree.savant@gmail.com
The Java Development Kit (JDK)
ServerPages
5 mailto: shubhashree.savant@gmail.com
The JDK is a set of command line tools for developing Java
applications:
javac - Java Compiler
java - Java Interpreter (Java VM)
Appletviewer - Run applets without a browser
javadoc - automated documentation generator
Jdb - Java debugger
The JDK is not an IDE (Integrated Development Environment)
Command line only, No GUI
6 mailto: shubhashree.savant@gmail.com
Text editors and IDE (Integrated Development
Environment)
Notepad Jcreator
Notepad++ Eclipse
Textpad Netbeans
Borland Jbuilder
Jdeveloper
7 mailto: shubhashree.savant@gmail.com
Bytecode and JVM
All language compilers translate source code into machine code
for a specific computer
8 mailto: shubhashree.savant@gmail.com
The form of instructions that the Java virtual machine executes
9 mailto: shubhashree.savant@gmail.com
Java Program Java Compiler Virtual Machine
Bytecode
11 mailto: shubhashree.savant@gmail.com
Java Buzzwords (Characteristics)
Simple Small and Familiar
Object oriented
Compiled and interpreted
Robust and secure
Architecture neutral / Portable
Distributed
High performance
Multi threaded
Dynamic and extensible
Platform independence
12 mailto: shubhashree.savant@gmail.com
Simple Small and Familiar
Does not use pointers, pre-processors, go to statement
Eliminates operator overloading, multiple inheritance
Similar to C and C++ that makes it familiar
Object-oriented
Follows Object-Oriented model
Encapsulation
Inheritance
Polymorphism
13 mailto: shubhashree.savant@gmail.com
Compiled and Interpreted
Java compiles to byte-code (not machine code).
Byte code is interpreted.
JVM interprets the byte code into machine instructions during runtime
14 mailto: shubhashree.savant@gmail.com
Architecture neutral / Portable
Compiled Java (byte code) will run on any platform which has a Java Virtual
Machine, byte code helps Java to achieve portability
The Java Virtual Machine is available for almost all platforms...
Even mainframes code
The size of the primitive data types is m/c independent
Distributed
Designed for internet
Built-in support for TCP/IP
Gives remote access to the internet users via applets
Resources are shared
15 mailto: shubhashree.savant@gmail.com
High-Performance
With the use of Just-In-Time compilers, Java enables high performance
The incorporation of multithreading enhances the execution speed of java
program
Java architecture is also designed to reduce overheads during runtime
Multi-Threaded
Processes contain multiple threads of execution
Similar to multi-tasking but all threads share the same memory space
16 mailto: shubhashree.savant@gmail.com
Dynamic and extensible
Makes heavy use of dynamic memory allocation
Libraries are dynamically linked during runtime
Classes can be dynamically loaded at any time
Java can use efficient functions available in C/C++
Platform Independence
Java has been described as WORA (Write once, Run Anywhere)
Java code can be executed anywhere an interpreter is available
17 mailto: shubhashree.savant@gmail.com
Java Virtual Machine
Javasource files (.java) are compiled to Java bytecode (.class)
Bytecode is interpreted on the target platform within a Java
Virtual Machine
i386 VM
Java Java
Source.java SPARC VM
Compiler Bytecode
Source.class
PPC VM
18 mailto: shubhashree.savant@gmail.com
How Java Works?
19 mailto: shubhashree.savant@gmail.com
HelloWorldApp.class
The Interpreter's
are sometimes
referred to as the
Java Virtual
Machines
20 mailto: shubhashree.savant@gmail.com
Basic Syntax of Java
Case Sensitivity
Identifier Sum and sum would have different meaning in Java
Class Names
For all class names the first letter should be in Upper Case
For Ex.: class MyFirstJavaClass
Method Names
All method names should start with a Lower Case letter
For Ex.: public void getData()
Program File Name
Name of the program file should exactly match the public class name (main()
method class)
21 mailto: shubhashree.savant@gmail.com
Structure of Java Program
Documentation Section
Package statement
Import statement
Interface statement
Class definitions
22
mailto: shubhashree.savant@gmail.com
Identifiers
User defined names
23 mailto: shubhashree.savant@gmail.com
Keywords (Reserved Words)
reserved for
future use.
24 mailto: shubhashree.savant@gmail.com
Operators
An operator is a symbol that operates on one or more operands to
produce a result
Java provides rich sets of operators
Operator Name Operators
Arithmetic Operator +, -, *, /, %
Relational Operator >, >=, <, <=, ==, !=
Logical Operator &&, ||, !
Assignment Operator = (+=, -=, *=, /=, %=)
Increment and decrement ++, --
Operator Prefix (++a), postfix (a++)
Conditional Operator ? : (exp1 ? exp2 : exp3)
Bitwise Operator ~, &, |, ^, >>, <<, >>>
Special Operator instanceof .(dot) ,(comma)
25 mailto: shubhashree.savant@gmail.com
Expression
Expression are the combination of operands and operators
For Ex.:
x = 10 + 2 * 6
= 10 + 12
= 22
26 mailto: shubhashree.savant@gmail.com
Type conversion (Casting)
Javaautomatically converts the source type into target type
This is known as automatic type conversion
For ex.:
float a = 10.6f;
int b;
b = a; //output 10
Type casting refers to the type conversion that is performed
explicitly
For Ex.:
int x;
byte n = (byte)x;
long m = (long)x;
27 mailto: shubhashree.savant@gmail.com
Casting example
i = (int)l; Narrowing
l = i;
(long)i; Widening
l long l;
int i;
i
int long
32 bit 64 bit
28 mailto: shubhashree.savant@gmail.com
Comments
Java supports three types of comments
Line
comments
C style comments
javadoc
The general forms are as follows:
// line comment. All text from the first // to the end of the
// line is a comment.
/* C-Style Comment. These comments can span multiple lines. The compiler ignores all text
up until */
/** Javadoc comment. The compiler ignores this text too. However, the javadoc program
looks for these comments and interprets tags for documentation generation purposes:
@author SSS
@version 1.7
@see java.lang.Object
*/
29 mailto: shubhashree.savant@gmail.com
Data Types
30 mailto: shubhashree.savant@gmail.com
Java Sample Application Program
//First java program HelloWorld.java
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
31 mailto: shubhashree.savant@gmail.com
main() method
public static void main(String[] args)
public static void main(String args[])
32 mailto: shubhashree.savant@gmail.com
Java Sample Applet Program
import java.awt.*;
import java.applet.*;
class HelloWorld extends Applet {
public void paint( Graphics g ) {
g.drawString( "Hello World!", 30, 30 );
}
}
<HTML>
<APPLET
CODE = HelloWorld.class
HEIGHT = 300 WIDTH = 200 >
</APPLET>
</HTML>
33 mailto: shubhashree.savant@gmail.com
Input from keyboard
34 mailto: shubhashree.savant@gmail.com
Standard input object,
System.in, enables applications
to read bytes of information Scanner class Demo
typed by the user.
Scanner object translates
these bytes into types that can
be used in a program
35 mailto: shubhashree.savant@gmail.com
Strings
In Java, a string is an object that is created either using String
or StringBuffer class
String is the only class which has "implicit" instantiation
36 mailto: shubhashree.savant@gmail.com
String class
Creating string object with new keyword:
String city;
city = new String(“Aurangabad”);
or
String city = new String(“Aurangabad”);
String objects can be created "implicitly":
String city;
city = “Aurangabad”;
String can also be created using + operator
String greet = “Good” + “Morning”;
37 mailto: shubhashree.savant@gmail.com
String class methods
Method Description
str1.length() Returns the length of the string str1
str1.equals(str2) Returns true if string str1 is equal to str2
str1.compareTo(str2) Returns negative is str1<str2, positive is str1>str2,
otherwise 0
str1.concat(str2) Concatenates string str1 and str2
str1 = str2.trim() Removes all the white spaces at the beginning and end of
the string str2 and assigns it to str1
str1 = str2.replace(‘a’,’b’) Replaces all a appearing in the string str2 with b and assigns
it to str1
str1.toLowerCase() Converts letters in the str1 to lowercase
str1.toUpperCase() Converts letters in the str1 to uppercases
str1.indexOf(‘a’) Gives the position of the first occurrence of ‘a’ in str1
str1.indexOf(‘a’,n) Gives the position of the first occurrence of ‘a’ that occurs
after nth position in the string str1
38 mailto: shubhashree.savant@gmail.com
String Demo programs
Program1
Program2
39 mailto: shubhashree.savant@gmail.com
StringBuffer class
Strings created using String class are of fixed length, whereas
strings created using StringBuffer class are of varying length
Creating StringBuffer object:
StringBuffer str;
str = new StringBuffer(“Java Programming”);
or
StringBuffer str = new StringBuffer(“Java Programming”);
StringBuffer Demo
40 mailto: shubhashree.savant@gmail.com
StringBuffer class Methods
Method Description
str1.append(str2) Append the string str2 at the end of the string str1
str1.insert(n,str2) Inserts the string str2 at the position n of the string str1
str1.setCharAt(n,’s’) Sets the nth character of the string str1 to s
str1.setLength() Sets the length of the string str1 to n, if n<str1.length(),
str1 is truncated. If n>str1.length(), null characters are
added at the end of str1
str1.reverse() Reverses the string str1
str1.delete(m,n) Deletes characters of the string str1 from mth index to (n-
1)th index
str1.deleteCharAt(m) Removes character of the string str1 at mth index
str1.replace(m,n,”str2”) Replaces the portion of the string str1 from mth index to
(n-1)th index with the string str2
41 mailto: shubhashree.savant@gmail.com
Quiz1
42 mailto: shubhashree.savant@gmail.com
Objective:1 Ans: c
43 mailto: shubhashree.savant@gmail.com
Objective:2 Ans: c
A Java file with extension ‘.class’ contains
b) HTML tags
44 mailto: shubhashree.savant@gmail.com
Objective:3 Ans:b
Which of the following is a Class in Java?
a) int
b) String
c) short
d) double
45 mailto: shubhashree.savant@gmail.com
Objective:4 Ans: c
What is the length of the applet window made by this program?
import java.awt.*;
import java.applet.*;
public class myApplet extends Applet{
Graphic g;
g.drawString("A Simple Applet", 20, 20);
}
a) 20
b) The same as the computer screen
c) Compilation error
d) Runtime error
46 mailto: shubhashree.savant@gmail.com
Objective:5 Ans:b
Which of the following cannot be used for a variable
name in Java?
a) identifier
b) final
c) malloc
d) calloc
47 mailto: shubhashree.savant@gmail.com
Sequential Programs
Write a Java program to swap the values of two variables
Solution
Solution
48 mailto: shubhashree.savant@gmail.com
Branching
Write a Java program to find smallest of three numbers
Solution
Solution
49 mailto: shubhashree.savant@gmail.com
Looping
Write a Java program to check whether the entered
number is prime or not
Solution
Solution
50 mailto: shubhashree.savant@gmail.com
Array
A fixed size sequence of the same type of data elements
51 mailto: shubhashree.savant@gmail.com
Declaring and creating 1-D Array
Creating an array is a 2 step process
It must be declared (declaration does not specify size)
Declaration syntax:
type[] arrayName; //note the location of the []
For ex.:
int[] marks; //declaration
It must be created (i.e. memory must be allocated for the array)
marks = new int[5]; //create array
//specify size
52 mailto: shubhashree.savant@gmail.com
Memory map
When an array is created, all of its elements are automatically
initialized
0 for integral types
marks
0.0 for floating point types
false for boolean types
0
null for object types
0
array indices 1 0
3 0
53 mailto: shubhashree.savant@gmail.com
Array Initialization
The array is automatically created
The array size is computed from the number of items in the list
Syntax:
Array length
arrayName.length;
int size = marks.length;
54 mailto: shubhashree.savant@gmail.com
Multi-dimensional Array
Arrays with multiple dimensions can also be created
Declaration syntax:
type[][] arrayName;
For ex.:
int[][] a; //declaration
It must be created (ie. memory must be allocated for the array)
a = new int[3][2]; //create array
//specify size
55 mailto: shubhashree.savant@gmail.com
Example - Array
//Demo of one dimensional array
//ArrayDemo.java
56 mailto: shubhashree.savant@gmail.com
Array Programs
Write a Java program to initialize array of 10 elements calculate and
print sum
Solution
Write a Java program to initialize 2x3 matrix. Calculate and print
sum
Solution
Write a Java program to accept array elements and print odd and
even elements
Solution
57 mailto: shubhashree.savant@gmail.com
Command Line Arguments
Command line arguments provide one of the ways for supplying input data
at the time of execution instead of including them in the program
args.length
58 mailto: shubhashree.savant@gmail.com
Example
public class CmdLineArg{
public static void main(String[] args){
int count = args.length;
System.out.println(“No. of arguments: ”+count);
for(String temp : args){
System.out.println(temp);
}
}
}
java CmdLieArg Hello World Program1
Output:
No. of arguments: 2
Hello
World Program2
59 mailto: shubhashree.savant@gmail.com
Quiz2
60 mailto: shubhashree.savant@gmail.com
Objective:1 Ans: a)
61 mailto: shubhashree.savant@gmail.com
Objective:2 Ans: c)
Which of the following is an incorrect array declaration?
b) b. int [ ] a;
62 mailto: shubhashree.savant@gmail.com
Objective:3 Ans: d)
Which of the following is not an object-oriented
programming paradigm?
a) Encapsulation
b) Inheritance
c) Polymorphism
63 mailto: shubhashree.savant@gmail.com
Objective:4 Ans: d)
Which of the following specification is not valid in the
main() method declaration?
a) void
b) public
c) static
d) private
64 mailto: shubhashree.savant@gmail.com
Objective:5 Ans: b)
Java is a platform independent programming language because
a) It is written almost similar to English language.
b) It compiles to an intermediate code targeting a virtual
machine, which can be interpreted by an interpreter for a
given OS.
c) Java compiler translates the source code directly to the
machine level language.
d) It follows the concept of “write once and compile
everywhere”.
65 mailto: shubhashree.savant@gmail.com
Objective:6 Ans: b)
Scanner sc = new Scanner(System.in);
What is System.in in this declaration?
66 mailto: shubhashree.savant@gmail.com
Objective:7 Ans: a)
Which of the following statement is incorrect?
67 mailto: shubhashree.savant@gmail.com
Objective:8 Ans: c)
What is the return type of a method that does not return
any value?
a) int
b) float
c) void
d) double
68 mailto: shubhashree.savant@gmail.com
Objective:9 Ans: c)
What is the output of this program?
class Increment {
public static void main(String args[]) {
int i = 3;
System.out.print(++i * 8);
}
}
a) 24
b) 25
c) 32
d) Runtime error
69 mailto: shubhashree.savant@gmail.com
Objective:10 Ans: c)
public class Test{
public static void main(String args[]){
int x = 9;
if (x == 9) {
int x = 8;
System.out.println(x);
}
}
}
a) 8.
b) 9.
c) Compilation error.
d) Runtime error.
70 mailto: shubhashree.savant@gmail.com
Classes in Java
classes and objects
Introduction to methods
Overloading methods
Constructors
this keyword
Overloading constructors
Using object as parameter
Returning objects
static
Command line arguments
71 mailto: shubhashree.savant@gmail.com
Classes
User defined data types
Data and methods are defined within Classes, data represents state and
methods behavior
Classes must provide an implementation such that objects created from
72 mailto: shubhashree.savant@gmail.com
Objects
An object is an Instance of a class
73 mailto: shubhashree.savant@gmail.com
Declaring and creating objects
declare a reference (object variable)
String s;
74 mailto: shubhashree.savant@gmail.com
Defining classes
Syntax
class class_name
//variable declaration
//method declaration
The variables and methods declared within class body are collectively
known as members of the class
75 mailto: shubhashree.savant@gmail.com
Example Class Definition
in Sample.java:
76 mailto: shubhashree.savant@gmail.com
Defining Instance Variables
Instance variables are declared using the same syntax as ordinary variables
Variables can be prefixed with a visibility modifier
protected - can be access directly from within the class, within the package, or
from within any subclass.
default (no modifier specified) - the variable can be accessed directly from within
the package
To preserve encapsulation, instance variables should be declared private
77 mailto: shubhashree.savant@gmail.com
Defining Instance Methods
Syntax:
protected - can be invoked directly from within the class, within the
the package
78 mailto: shubhashree.savant@gmail.com
Invoking Instance Methods
To invoke a method on an object, use the . (dot) operator
objectReference.methodName(parameters);
Ex.
s.setData(5,6);
If there is a return value, it can be used as an expression
Ex.
System.out.println(s.calSum());
Program
79 mailto: shubhashree.savant@gmail.com
Overloading Methods
Java allows for method overloading
A Method is overloaded when the class provides several implementations of
the same method, but with different parameters
The methods have the same name
parameters
Program
80 mailto: shubhashree.savant@gmail.com
Constructors
Special method, which is used to initialize the objects at the time of their
creation
Invoked automatically
81 mailto: shubhashree.savant@gmail.com
Types of constructor
Default constructor
Parameterized constructor
If no constructors are defined for a class, the compiler automatically
generates a default, no argument constructor
All instance variables are initialized to default values
82 mailto: shubhashree.savant@gmail.com
Constructor example
public Sample() { //default
a = 10;
b = 20;
}
83 mailto: shubhashree.savant@gmail.com
Demo Program
Program1
Program2
84 mailto: shubhashree.savant@gmail.com
this keyword
refers to “this” object (object in which it is used)
Usage:
85 mailto: shubhashree.savant@gmail.com
this :: with a variable
refers to “this” object’s data member
class Sample {
int a;
int b;
public Sample (int a, int b ) {
this.a = a;
this.b = b;
}
}
86 mailto: shubhashree.savant@gmail.com
Argument Passing
Two ways to pass arguments to a method
Call by value
Call by reference
Call by value
This method copies the value of an argument into the formal
parameter of the method
87 mailto: shubhashree.savant@gmail.com
Call by reference
A reference to an argument is passed to the parameter
This means that changes made to the parameter will affect the
argument used to call the method
88 mailto: shubhashree.savant@gmail.com
Object as parameter
class Sample{ public class ObjectArg{
int n; public static void main(String[] args){
Sample(){} //explicitly defined Sample S1 = new Sample(10);
Sample(int x){ Sample S2 = new Sample(20);
n = x; Sample S3 = new Sample();
} S3.sum(S1,S2);
void sum(Sample s1,Sample s2){ S1.show();
n = s1.n + s2.n; S2.show();
} S3.show();
void show(){ }
System.out.println(“n = ”+n); }
}
}
89 mailto: shubhashree.savant@gmail.com
Returning Object
class Sample{ public class RetObject{
int n; public static void main(String[] args){
Sample(){} //explicitly defined Sample S1 = new Sample(10);
Sample(int x){ Sample S2 = new Sample(20);
n = x; Sample S3 = new Sample();
} S3 = S1.sum(S2);
Sample sum(Sample s2){ S1.show();
Sample s3 = new Sample(); S2.show();
s3.n = n + s2.n; S3.show();
return(s3); }
} }
void show(){
System.out.println(“n = ”+n); Program
}
}
90 mailto: shubhashree.savant@gmail.com
Static members
Static members are associated with the class as a whole,
rather than with individual objects
91 mailto: shubhashree.savant@gmail.com
Example - static
class Test{ public class StaticDemo{
int n; public static void main(String[] args){
static int c; Test t1 = new Test();
void setD(){ Test t2 = new Test();
n = ++c; t1.setD();
} t2.setD();
void show(){ Test.showC();
System.out.println(“n = “ + n); Test t3 = new Test();
} t3.setD();
static void showC(){ Test.showC();
System.out.println(“c = “ + c); t1.show();
} t2.show();
} t3.show();
}
} Program
92 mailto: shubhashree.savant@gmail.com
Quiz3
93 mailto: shubhashree.savant@gmail.com
Objective:1 Ans: b)
signature?
a) Method overriding
b) Method overloading
c) Encapsulation
d) Inheritance
94 mailto: shubhashree.savant@gmail.com
Objective:2 Ans: d)
Which of the following is called when a method having
the same name as that the name of the class where it is
defined?
a) abstract
b) this
c) final
d) constructor
95 mailto: shubhashree.savant@gmail.com
Objective:3 Ans: d)
What is not the use of “this” keyword in Java?
a) Passing itself to another method
96 mailto: shubhashree.savant@gmail.com
Objective:4 Ans: a)
class Box {
int width; int height; int length;
}
classTest {
public static void main(String args[]) {
Box b1 = new Box();
Box b2 = new Box();
b1.height = 1;b1.length = 2;b1.width = 3;
b2 = b1;
System.out.println(b2.height);
}
a. 1 b. 2 c. 3 d. NULL
97 mailto: shubhashree.savant@gmail.com
Objective:5 Ans: c)
What is the maximum number of arguments that can be
passed to a method in Java?
a) No arguments
b) One
98 mailto: shubhashree.savant@gmail.com
Inheritance
Basics
Using super
Method overriding
Abstract methods and class
Using final with inheritance
Packages
Importing packages
Interfaces
99 mailto: shubhashree.savant@gmail.com
Inheritance (basics)
Inheritance is a fundamental Object Oriented concept
A class can be defined as a "subclass" of another class
The subclass inherits all data attributes and methods of its
superclass
Add new functionality, use inherited functionality and
override inherited functionality
Inheritance is declared using the "extends" keyword
Program
C
Program
Three types:
Is-A Relationship
Has-A Relationship
Uses-A Relationship
b) private
c) protected
d) Default
a) public member
b) private member
c) protected member
d) default member
c) Multilevel inheritance
d) Single inheritance
c) Random order
a) super
b) this
c) extent
d) extends
a) Code sharing
b) Code maintainability
c) Code reusability
method it is overriding
Program
java
Graphics
Image
package packagename;
package p2;
public class Courses
{………..}
public class Student
{………………..}
133 mailto: shubhashree.savant@gmail.com
Levels of Access Control
Non-subclass in Yes No No No
other package
package p1 package p2
class C3 class C4
C1 c1; C1 c1;
c1.x cannot be read c1.x cannot be read
or modified nor modified
package p1 package p2
class C3 class C4
C1 c1; C1 c1;
c1.x can be read or c1.x cannot be read
modified nor modified
package p1 package p2
class C3 class C4
C1 c1; C1 c1;
c1.x can be read or c1.x cannot be read
modified nor modified
package p1 package p2
class C3 class C4
C1 c1; C1 c1;
c1.x can be read or c1.x can be read nor
modified modified
set CLASSPATH=c:\
a) Abstract class
b) A normal class
c) Final Class
d) An interface
d) None
b) implements
c) extends
d) package
a) public
b) private
c) protected
a) class C implements A, B { }
d) class C extend A, B { }
a) public
b) protected
c) private
http://docs.oracle.com/javase/tutorial
javavids –YouTube
www.nptelvideos.com/java/java_video_lectures_tutorials.php
155 Mail@shubhashree.savant@gmail.com
Thank You