You are on page 1of 156

Core Java

SY MCA Part – I 2019-20

Subject Teacher: Shubhashree Savant (Kadam)


Basics of Java
 Introduction
 Java Buzzwords
 Basic syntax of Java
 Identifiers
 Keywords
 Data types
 Sample Java Program
 String and Array
 Operators and expressions
 Type conversion
 comments

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

 Special java program that can transmitted over the network


and automatically executed by a java-compatible web browser

 Java compatible web browser can download java applets


without fear of viral infection and malicious agent

 Java applets can be dynamically downloaded to all the various


types of platforms connected to the internet

4 mailto: shubhashree.savant@gmail.com
The Java Development Kit (JDK)

 The JDK comes in three versions:


 J2ME - Micro Edition
 used to develop applications for mobile devices such as cell phones

 J2SE - Standard Edition


 used to develop client-side standalone applications or applets

 J2EE - Enterprise Edition


 used to develop server-side applications such as Java servlets and Java

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

 DOS text editors  BlueJ

 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

 Java compiler also does the same thing, but it produces


intermediate code, known as bytecode for a machine that does
not exist

 This machine is called as ‘Java Virtual Machine’(JVM)

 JVM is exist only inside the computer memory

8 mailto: shubhashree.savant@gmail.com
 The form of instructions that the Java virtual machine executes

 The compiled format for Java programs

 Once a Java program has been converted to bytecode, it can


be transferred across a network and executed by Java Virtual
Machine (JVM)

 Byte code files generally have a .class extension

9 mailto: shubhashree.savant@gmail.com
Java Program Java Compiler Virtual Machine

Bytecode

Fig. 1 : Process of Compilation

 The output produce by the Java compiler is not executable


code.

 It is Bytecode, highly optimized set of instructions executed by


java run time system or JVM

 JVM is the interpreter for the bytecode.


10 mailto: shubhashree.savant@gmail.com
 The virtual machine code generated by the Java interpreter is
not machine specific code, but it is acts as an intermediate
between the virtual machine and real machine

Bytecode Java Interpreter Machine code


Virtual machine Real machine

Fig. 2 : Process of converting bytecode into machine code

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

 Pure object oriented language


 Every thing in Java resides within classes

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

 Robust and secure


 Strongly typed language
 Memory management is done automatically (Automatic garbage
collection)
 Exception handling
 No pointers

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

main() method class

22
mailto: shubhashree.savant@gmail.com
Identifiers
 User defined names

 Names given to classes, variables and methods, packages etc.

 Rules for naming identifiers:


 Only letters, digits, underscore and dollar are permitted
 The name cannot start with a digit
 Uppercase and lowercase letters are distinct (Case sensitive)
 Keywords cannot be used as identifier
 Recommend meaningful identifiers
 Valid identifiers: age, $salary, sub3
 Invalid identifiers: 123sub, -salary

23 mailto: shubhashree.savant@gmail.com
Keywords (Reserved Words)

boolean abstract break class byvalue


byte final case extends cast
char native catch implements const
short private continue interface future
int protected default throws generic
long public do goto
float static else inner
double synchronized finally import operator
void transient for package outer
volatile if rest
return var
instanceof
switch
false new
throw
null super
try
true this
while

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

 The order of operations is defined through precedence

 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

Data Type Size Range


byte 1 byte -128 to 127
short 2 bytes -32768 to 32767
int 4 bytes -2,147,483,648 to 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 to-
9,223,372,036,854,775,807
float 4 bytes Approx. ± 3.4028235E+38F
double 8 bytes Approx. ± 1.7976931348623157E+308
boolean true or false NA, note Java booleans cannot be converted to
or from other types
char 2 bytes Unicode character,
\u0000 (or 0) to \uFFFF (or 65535)

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[])

 public: the method can be called by any object

 static: the method is a class method, which can be called


without the requirement to instantiate an object of the class

 void: the method doesn't return any value

 args: The formal parameter args is an array of type String,


which contains arguments entered at the command line

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

 The string created using String class cannot be modified


 Strings are immutable (fixed length)

 The string created using StringBuffer class cannot only be


modified but can also be expanded or contracted dynamically
 Strings are mutable (varying length)

 The String class is defined in the java.lang package

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

 Which of the following is true?

a) Java uses only interpreter.

b) Java uses only compiler.

c) Java uses both interpreter and compiler.

d) None of the above

43 mailto: shubhashree.savant@gmail.com
Objective:2 Ans: c
 A Java file with extension ‘.class’ contains

a) Java source code

b) HTML tags

c) Java Byte code

d) A program file written in Java programming language

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

 Write a Java program to calculate and print area of circle

Solution

48 mailto: shubhashree.savant@gmail.com
Branching
 Write a Java program to find smallest of three numbers

Solution

 Write a Java program to check whether character is


vowel or not

Solution

49 mailto: shubhashree.savant@gmail.com
Looping
 Write a Java program to check whether the entered
number is prime or not

Solution

 Write a Java program to calculate and print sum of


individual digits

Solution

50 mailto: shubhashree.savant@gmail.com
Array
 A fixed size sequence of the same type of data elements

 Data elements can be of any primitive or non-primitive data type

 The elements of an array are stored in contiguous memory


locations and each individual element can be accessed using one or
more indices or subscripts

 A subscript or an index is a positive integer value

 Arrays can be single-dimensional or multi-dimensional depending


upon the number of subscripts used

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

int[] marks = new int[5]; 2 0

3 0

Note: maximum array index is length -1 4 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:

type[] arrayName = {initializer_list};


 Example:

int[] marks = {100, 96, 78, 86, 93};

 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

public class ArrayDemo{


public static void main(String[] args){
int[] a = {1,3,2,5,6};
int size = a.length;
System.out.println(“Array size ”+size);
System.out.println(“Array Elements :”);
for(int temp : a){ //enhanced for loop
System.out.println(temp);
}
}
}

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

 They are supplied as parameters to the main() method:

 public static void main(String args[])

 “args” is declared of an array of strings

 args[0] is the first parameter, args[1] is the 2nd argument and so on

 The number of arguments passed identified by:

 args.length

 E.g. count = 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)

 Which of the following is not a correct statement?

a) It is always necessary to use new operator to initialize an array.

b) Array can be initialized using comma separated expressions


surrounded by curly braces.

c) Array can be declared and memory can be allotted in one


statement.

d) An array can be declared in one statement and memory can be


allocated in other statement.

61 mailto: shubhashree.savant@gmail.com
Objective:2 Ans: c)
 Which of the following is an incorrect array declaration?

a) int[] a = new int[10];

b) b. int [ ] a;

c) c. int[][] a = new int[10];

d) d. int[][] a = {{1, 2, 3}, {1, 2, 3}};

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

d) Dynamic memory allocation

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?

a) Any file storing data

b) Reference to standard input device, that is, keyboard

c) Reference to a scanner as an input device

d) It is a mouse as an input device

66 mailto: shubhashree.savant@gmail.com
Objective:7 Ans: a)
 Which of the following statement is incorrect?

a) Every class must contain a main() method

b) Applets do not require a main() method at all

c) There can be only one main() method in a program

d) main() method must be made public

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

 Templates or blueprints for Objects

 Data and methods are defined within Classes, data represents state and

methods behavior
 Classes must provide an implementation such that objects created from

those classes behave as those defined in the Object model.

72 mailto: shubhashree.savant@gmail.com
Objects
 An object is an Instance of a class

 The process of creating an object is called instantiation

 The attributes of an object are called instance variables

 The methods of an object are called instance methods

 Objects are created using the new keyword:

String str = new String(“Core Java”);

73 mailto: shubhashree.savant@gmail.com
Declaring and creating objects
 declare a reference (object variable)
String s;

 create an object (Instantiation)


s = new String (“Core Java”);

Object variable doesn’t


actually contain an
object. It only refers to
an object Core Java

74 mailto: shubhashree.savant@gmail.com
Defining classes
 Syntax

class class_name

//variable declaration

//method declaration

 The variables declared in the class are known as instance variables

 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:

public class Sample


{
int a;
Instance
float b;
Variables:
[... more variable definitions ...]

public void setData()


{
Methods: a = 10;
b = 4.5f;
}
public void showData()
{
// display values of a and b
}
[... more method definitions ...]
}

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

modifier type variable_name;

 Variables can have one of 4 different visibilities:


 public - can be directly accessed from anywhere

 private - can only be directly accessed from within the class

 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:

modifier return_type method_name(type name, ...) { }

 Methods have the same visibility modifiers as variables


 public - can be invoked from anywhere

 private - can only be invoked from within the class

 protected - can be invoked directly from within the class, within the

package, or from within any subclass.


 default (no modifier specified) - can be invoked directly from within

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

 The methods have different number of parameters or different types of

parameters

Program

80 mailto: shubhashree.savant@gmail.com
Constructors
 Special method, which is used to initialize the objects at the time of their
creation

 When an object is created, all instance variables are initialized to the


default value for their type

 Constructors have the following characteristics


 no return type, not even void

 method name is the same name as the class

 Invoked automatically

 Constructors can be overloaded

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

 However, if any constructor is defined which takes parameters, the compiler


will not generate the default, no argument constructor
 If needed, define explicitly

 Constructor is also overloaded (Java allows overloading of all methods,


including constructors)

82 mailto: shubhashree.savant@gmail.com
Constructor example
public Sample() { //default
a = 10;
b = 20;
}

public Sample(int x, int y){ //para


a = x;
b = y;
}

Sample s = new Sample(); //default


Sample s1 = new Sample(5,6); //para

83 mailto: shubhashree.savant@gmail.com
Demo Program

Program1

Program2

 Write a Java program to calculate the factorial of a number


Solution

84 mailto: shubhashree.savant@gmail.com
this keyword
 refers to “this” object (object in which it is used)

 Usage:

 with an instance variable or method of “this” class

 as a function inside a constructor of “this” class

 as “this” object, when passed as parameter

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

 Therefore, changes made to the parameter of the method have no


effect on the argument used to call it

87 mailto: shubhashree.savant@gmail.com
 Call by reference
 A reference to an argument is passed to the parameter

 Inside the method this reference is used to access the actual


argument specified in the call

 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

 Static members of a class are called by using class names


instead objects

 Since the static variables and static methods contain the


properties of a class they are also known as class variables and
class methods

 Static member function can access only static members

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)

 What is the process of defining more than one method in a

class having the same name but differentiated by method

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

b) Calling another constructor in constructor chaining

c) Referring to the instance variable when local variable


has the same name

d) Passing itself to method of the same class

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

c) Any number of arguments

d) Varies from one compiler to another

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

100 mailto: shubhashree.savant@gmail.com


Single Inheritance
class A{
-----
A -----
}
B
class B extends A{
-----
-----
}

Program

101 mailto: shubhashree.savant@gmail.com


Multilevel Inheritance
class A{
-----
A -----
}
class B extends A{
B -----
-----
}
C class C extends B{
------
------
}
Program

102 mailto: shubhashree.savant@gmail.com


Hierarchical Inheritance
class A{
-----
A -----
}
class B extends A{
B C
-----
-----
}
class C extends A{
------
------
}

103 mailto: shubhashree.savant@gmail.com


Multiple Inheritance
 In java, it is not possible to class A{
implement multiple inheritance -----
directly }
 Using interface multiple interface B{
inheritance can be implemented ------
}
class C extends A implements B{
------
A B
------
}

C
Program

104 mailto: shubhashree.savant@gmail.com


Hybrid Inheritance
class A{
-----
}
A class B extends A{
-----
}
interface C{
B C
------
}
class D extends B implements C{
D ------
------
}

105 mailto: shubhashree.savant@gmail.com


Relationship in Java
 To reuse the features from one class to another

 Three types:

 Is-A Relationship

 Has-A Relationship

 Uses-A Relationship

106 mailto: shubhashree.savant@gmail.com


Is-A relationship
 In Is-A relationship one class A{
class is obtaining the
-----
-----
features of another class by Is-A Relation
}
using inheritance concept
class B extends A{
with extends keywords
-----
 In a IS-A relationship there -----
exists logical memory space }

107 mailto: shubhashree.savant@gmail.com


Has-A relationship
 In Has-A relationship an class A{
-----
object of one class is created
-----
as data member in another } Has-A Relation
class the relationship class B
between these two classes is {
A ob = new A();
Has-A
-----
 In Has-A relationship there -----
existed physical memory }
space
108 mailto: shubhashree.savant@gmail.com
Uses-A relationship
class A{
 A method of one class is
-----
using an object of another }
class the relationship class B
{
between these two classes is Uses-A
Relation
known as Uses-A void show()
relationship {
A ob = new A();
-----
}
}
109 mailto: shubhashree.savant@gmail.com
Using super
 Used to refer to super class of current class

 Can be used to refer to super class methods, variables


 Needed when there is a name conflict with current class

 Useful when overriding is used and to keen the old behavior


but add new behavior to it
 Syntax:
super(para); //call super class constructor
super.fieldname; //access super class field
super.methodname; //or method
Program
110 mailto: shubhashree.savant@gmail.com
Quiz4

111 mailto: shubhashree.savant@gmail.com


Objective:1 Ans: c)
 Which of the following statements is/ are incorrect?

a) public members of a class can be accessed by any code in the


program
b) private members of class can only be accessed any members in the
same class
c) private members of a class can be inherited by a subclass, and
become protected members in subclass
d) protected members of a class can be inherited by a subclass, and
become private members of the subclass

112 mailto: shubhashree.savant@gmail.com


Objective:2 Ans: a)
 Which of the following access specifier must be used for
class so that a sub class can inherit it?
a) public

b) private

c) protected

d) Default

113 mailto: shubhashree.savant@gmail.com


Objective:3 Ans: b)
 A class member declared as protected becomes member
of subclass of which type?

a) public member

b) private member

c) protected member

d) default member

114 mailto: shubhashree.savant@gmail.com


Objective:4 Ans: a)
 Which inheritance in Java programming is not supported?
public member

a) Multiple inheritance using classes

b) Multiple inheritance using interfaces

c) Multilevel inheritance

d) Single inheritance

115 mailto: shubhashree.savant@gmail.com


Objective:5 Ans: a)
 Order of execution of constructors in Java Inheritance is

a) Base to derived class

b) Derived to base class

c) Random order

d) No execution of a constructor in the derived class

116 mailto: shubhashree.savant@gmail.com


Objective:6 Ans: a)
 Which of this keyword can be used in a subclass to call the
constructor of superclass?

a) super

b) this

c) extent

d) extends

117 mailto: shubhashree.savant@gmail.com


Objective:7 Ans: d)
 Advantage(s) of inheritance in Java programming is/are

a) Code sharing

b) Code maintainability

c) Code reusability

d) All of the above

118 mailto: shubhashree.savant@gmail.com


Method overriding
 Subclasses inherit all methods from their super class
 Sometimes, the implementation of the method in the super class does not

provide the functionality required by the subclass


 In these cases, the method must be overridden

 To override a method, provide an implementation in the


subclass
 The method in the subclass MUST have the exact same signature as the

method it is overriding

119 mailto: shubhashree.savant@gmail.com


Example
class A{ class MethodOverriding{
void show(){ public static void main(String[] args){
System.out.println(“A”); B ob = new B();
ob.show(); //B show()
}
}
}
}
class B extends A{
void show(){
System.out.println(“B”);
}
}

120 mailto: shubhashree.savant@gmail.com


Using final keyword
 finalkeyword can be applied to variables, methods and classes
 Final Variables
 the value of a variable can be prevented from being modified by
declaring a variable as final
 Example:
final int MAX = 10;
 Final methods
 A method can be prevented from being overridden by the subclass by
declaring the method as final
 Example:
final void show(){ //cannot be overridden
------
}

121 mailto: shubhashree.savant@gmail.com


 Final classes
 A class which cannot be further inherited or cannot have any subclass is
known as final class (prevent from inheritance)
 To make a class final, the class declaration is preceded by the final
keyword
 If a class is declared as final, all of its methods are automatically declared
as final
 Example:
final class A { //cannot be inherited
------
}
class B extends A{ //error
-------
}

122 mailto: shubhashree.savant@gmail.com


Abstract class and method
 Java allows abstract classes
 use the modifier abstract on a class header to declare an abstract class
abstract class Shape
{…}

 An abstract class is a placeholder in a class hierarchy that represents


a generic concept
 An abstract class cannot be instantiated
 An abstract class often contains abstract methods

 Abstract methods consist of only methods declarations, without


any method body

123 mailto: shubhashree.savant@gmail.com


Example abstract class and method

Program

124 mailto: shubhashree.savant@gmail.com


Packages
 Provides a mechanism for grouping a variety of classes and / or
interfaces together

 Grouping is based on functionality

 Two types of packages:


1. Java API packages

2. User defined packages

125 mailto: shubhashree.savant@gmail.com


Java API Packages (Application Program Interface)

A large number of classes grouped into different packages


based on functionality

java

lang util awt net applet io

126 mailto: shubhashree.savant@gmail.com


Example
Java
Package containing awt package
awt

Color Package containing classes

Graphics

Image

127 mailto: shubhashree.savant@gmail.com


Accessing Classes in a Package
 Fully Qualified class name:
Example:java.awt.Color
 import packagename.classname;
Example: import java.awt.Color;
or
 import packagename.*;
Example: import java.awt.*;
 Import statement must appear at the top of the file, before any
class declaration

128 mailto: shubhashree.savant@gmail.com


Creating packages
 Declare the package at the beginning of a file using the form

package packagename;

package mypack; or package pack.subpack;

 Define the class that is to be put in the package and declare it


public

 Package statement should be on top of the file

 The import statement should follow the package statement and no


other statements should be between these two statements

129 mailto: shubhashree.savant@gmail.com


Example1-Package
package p1; import p1.*;
public class ClassA class PkgTest
{ {
public void displayA( ) public static void main(String args[])
{ {
System.out.println(“Class A”); ClassA obA=new ClassA();
} obA.displayA();
} }
}
Source file – ClassA.java Source file-PkgTest.java
Subdirectory-p1 PkgTest.java and PkgTest.class
ClassA.Java and ClassA.class->p1 ->in a directory of which p1 is
subdirectory.

130 mailto: shubhashree.savant@gmail.com


Example 2-Package
package p2; import p1.*;
public class ClassB import p2.*;
{
protected int m =10; class PkgTest1
public void displayB() {
{ public static void main(String args[])
System.out.println(“Class B”); {
System.out.println(“m= “+m); ClassA obA=new ClassA();
} Classb obB=new ClassB();
} obA.displayA();
obB.displayB();
}
}

131 mailto: shubhashree.savant@gmail.com


Example 3- Package
import p2.ClassB; class PkgTest2
class ClassC extends ClassB {
{ public static void main(String args[])
int n=20; {
void displayC() ClassC obC = new ClassC();
{ obC.displayB();
System.out.println(“Class C”); obC.displayC();
System.out.println(“m= “+m); }
System.out.println(“n= “+n); }
}
}

132 mailto: shubhashree.savant@gmail.com


Classes with identical names
package p1; import p1.*;
public class Teacher import p2.*;
{………….}
public class Student p1.Student student1;
{……………..} p2.Student student2;

package p2;
public class Courses
{………..}
public class Student
{………………..}
133 mailto: shubhashree.savant@gmail.com
Levels of Access Control

public protected friendly private


(default)
Same class Yes Yes Yes Yes

Subclass in the Yes Yes Yes No


same package

Other class in Yes Yes Yes No


the same
package
Subclass in Yes Yes No No
other packages

Non-subclass in Yes No No No
other package

134 mailto: shubhashree.savant@gmail.com


Access Modifier private

package p1 package p2

class C1 class C2 extends C1

private int x x cannot be read or


modified in C2

class C3 class C4

C1 c1; C1 c1;
c1.x cannot be read c1.x cannot be read
or modified nor modified

135 mailto: shubhashree.savant@gmail.com


Access modifier default

package p1 package p2

class C1 class C2 extends C1

int x x cannot be read or


modified in C2

class C3 class C4

C1 c1; C1 c1;
c1.x can be read or c1.x cannot be read
modified nor modified

136 mailto: shubhashree.savant@gmail.com


Access modifier protected

package p1 package p2

class C1 class C2 extends C1

protected int x x can be read or


modified in C2

class C3 class C4

C1 c1; C1 c1;
c1.x can be read or c1.x cannot be read
modified nor modified

137 mailto: shubhashree.savant@gmail.com


Access modifier public

package p1 package p2

class C1 class C2 extends C1

public int x x can be read or


modified in C2

class C3 class C4

C1 c1; C1 c1;
c1.x can be read or c1.x can be read nor
modified modified

138 mailto: shubhashree.savant@gmail.com


CLASSPATH (Environment variable)
 It is a set of directories where Java class files are located

 Java runtime searches for class files in the directories specified


in the class path in the order specified

 The CLASSPATH environment variable is used to direct the


compiler and interpreter to where programmer defined
imported packages can be found

 To set the CLASSPATH variable use the following command:

set CLASSPATH=c:\

139 mailto: shubhashree.savant@gmail.com


interface
 An interface declares (describes) methods but does not supply
bodies for them

 All the methods are implicitly public and abstract

 Cannot instantiate an interface

 An interface may also contain constants (final variables)

 Interfaces can inherit from other interfaces, and a single


interface can inherit from multiple other interfaces

140 mailto: shubhashree.savant@gmail.com


Example - interface
interface Area{ public class InterfaceTest{
final static float PI = 3.14f; public static void main(String[] args){
float compute(float r); Circlr c = new Circle();
} System.out.println(“Area: “ +
c.compute(2.2f));
class Circle implements Area{ }
public float compute(float r){ }
return(PI * r * r);
}
}

141 mailto: shubhashree.savant@gmail.com


Quiz5

142 mailto: shubhashree.savant@gmail.com


Objective:1 Ans: a)

 If a class inheriting an abstract class does not define all of its

methods, then it will be known as

a) Abstract class

b) A normal class

c) Final Class

d) An interface

143 mailto: shubhashree.savant@gmail.com


Objective:2 Ans: c)
 Does a subclass inherit both member variables and methods?

a) No—only member variables are inherited

b) No—only methods are inherited

c) Yes—both are inherited - but not those are declared as


private

d) Yes—only the members/ methods with protected are


inherited

144 mailto: shubhashree.savant@gmail.com


Objective:3 Ans: b)
 Can an object subclass another object?
a) Yes—as long as single inheritance is followed.

b) No—inheritance is only between classes.

c) Only when one has been defined in terms of the other.

d) Yes—when one object is used in the constructor of another.

145 mailto: shubhashree.savant@gmail.com


Objective:4 Ans: b)
 For which purpose packages are used in Java?
a) Categorizes data

b) Organizing java classes into namespaces

c) For faster compilation

d) None

146 mailto: shubhashree.savant@gmail.com


Objective:5 Ans: d)
 Which of the following keywords is used to define a package in
Java?
a) class

b) implements

c) extends

d) package

147 mailto: shubhashree.savant@gmail.com


Objective:6 Ans: d)
 Which of the following is an incorrect statement about
packages?

a) Package defines a namespace in which classes are stored

b) A package can contain other package within it

c) Java uses file system directories to store packages

d) A package can be renamed without renaming the directory in


which the classes are stored.

148 mailto: shubhashree.savant@gmail.com


Objective:7 Ans: a)
 Which of these access specifiers can be used for an interface?

a) public

b) private

c) protected

d) All of the above

149 mailto: shubhashree.savant@gmail.com


Objective:8 Ans: a)
 Which one is correct declaration for implementing two
interfaces?

a) class C implements A, B { }

b) class C implements A, implements B { }

c) class C implements A extends B { }

d) class C extend A, B { }

150 mailto: shubhashree.savant@gmail.com


Objective:9 Ans: d)
 The fields in an interface are implicitly specified as

a) public

b) protected

c) private

d) static and final

151 mailto: shubhashree.savant@gmail.com


Objective:10 Ans: d)
 Let us consider the following piece of code in Java
interface A {
int i = 111;
}
class B implements A {
void methodB() {
i = 222;
System.out.printl(i);
}
}
a) There is no main () method so the program is not executable
b) The value of i will be printed as 111, as it is static and final by default
c) The value of i will be printed as 222, as it is initialized in class B
d) Compile time error

152 mailto: shubhashree.savant@gmail.com


Objective:11 Ans: d)
 Which of the following is/are true?
a) Every class is a part of some package

b) All classes in a file are part of the same package

c) If no package is specified, the classes in the file go into a


special unnamed package

d) If no package is specified, a new package is created with


folder name of class and the class is put in this package

153 mailto: shubhashree.savant@gmail.com


Objective:12 Ans: c)
class Base { public static void main(String[ ] args) {
public void show() { Base bb = new Derived();;
System.out.println("Base show()"); bb.show();
} }
} }
class Derived extends Base {
public void show() {
a) Base show() called
System.out.println("Derived show()");
} b) Main show() called
}
class Main { c) Derived show() called
public void show() {
d) Compile time error
System.out.println("Main show() ");
}

154 mailto: shubhashree.savant@gmail.com


References
 Herbert Schildt: “The Complete Reference Java2”, 5t h Edition TMH
Publications.

 Cay S Horstmann, Fary Cornell Core Java Vol I : Sun Microsystems


Press

 http://docs.oracle.com/javase/tutorial

 javavids –YouTube

 www.nptelvideos.com/java/java_video_lectures_tutorials.php

 www.spoken-tutorial.org (NMEICT IIT Bombay Java videos)

155 Mail@shubhashree.savant@gmail.com
Thank You

156 mailto: shubhashree.savant@gmail.com

You might also like