Java Programming For MSBTE I Scheme (IV - Comp. - 2
Java Programming For MSBTE I Scheme (IV - Comp. - 2
The book uses plain, lucid language to explain fundamentals of this subject. The book
provides logical method of explaining various complicated concepts and stepwise
methods to explain the important topics. Each chapter is well supported with necessary
illustrations, practical examples and solved problems. All chapters in this book are
arranged in a proper sequence that permits each topic to build upon earlier studies. All
care has been taken to make students comfortable in understanding the basic concepts
of this subject.
Representative questions have been added at the end of each section to help the
students in picking important points from that section.
The book not only covers the entire scope of the subject but explains the philosophy of
the subject. This makes the understanding of this subject more clear and makes it more
interesting. The book will be very useful not only to the students but also to the subject
teachers. The students have to omit nothing and possibly have to cover nothing more.
We wish to express our profound thanks to all those who helped in making this book a
reality. Much needed moral support and encouragement is provided on numerous
occasions by our whole family. We wish to thank the Publisher and the entire team of
Technical Publications who have taken immense pain to get this book in time with
quality printing.
Any suggestion for the improvement of the book will be acknowledged and well
appreciated.
Authors
A. A. Puntambekar
Prashant P. Sawant
Swati T. Ghorsad
Dedicated to God.
(iii)
Syllabus
Java Programming (22412)
Teaching Credit Examination Scheme
Scheme (L+T+P)
L T P Theory Practical
(iv)
Unit - II 2a. Use Constructors for 2.1 Constructors and methods, types of 18
Derived the given programming constructors, nesting of methods,
Syntactical problem. argument passing the 'this' keyword,
Constructs 2b. Identify scope and command line arguments, varargs:
in Java lifetime of a variable in variable-length arguments, garbage
the given program collection, finalize() method, the object
code. class.
2d. Write the programs by 2.3 Arrays and Strings: Types of arrays.
implementing arrays to creating an array, strings, string classes
solve the given and string buffer, vectors, wrapper
problem. classes, enumerated types.
(v)
Unit - IV 4a. Distinguish the errors 4.1 Errors and Exception : Types of errors, 12
Exception and exceptions (if any) exceptions, try and catch statement,
Handling in the given example. nested try statement, throws and Finally
and 4b. Develop program for statement, build-in exceptions, chained
Multithread handling the given exceptions, creating own exception
-ing exception. (throw clause), subclasses.
(vi)
Table of Contents
1.8.3 Nested if-else Statement . . . . . . . . . . . . . . 1 - 21
Unit - I
1.8.4 If-else-if Ladder . . . . . . . . . . . . . . . . . . . . 1 - 21
1.8.5 Switch Statement. . . . . . . . . . . . . . . . . . . . 1 - 21
Chapter - 1 Basic Syntactical Constructs in
Java (1 - 1) to (1 - 30) 1.8.6 Nested Switch Statement . . . . . . . . . . . . . 1 - 22
1.8.7 The while Statement . . . . . . . . . . . . . . . . . 1 - 22
1.1 Java Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 1
1.8.8 The do while Statement. . . . . . . . . . . . . . . 1 - 24
1.2 Java Programming Environment . . . . . . . . . . . . 1 - 2
1.2.1 Java Development Kit (JDK) . . . . . . . . . . . 1 - 2 1.8.9 The for Statement . . . . . . . . . . . . . . . . . . . 1 - 24
®
TM
®
TM
UNIT - I
directly. This makes it impossible to accidentally Java is popularly recognised as an object oriented
reference memory that belongs to other programs programming language.
or the kernel. It supports various object oriented features such as
2. The output of Java compiler is not executable code data encapsulation, inheritance, polymorphism
but it is a bytecode. The instructions of bytecode is and dynamic binding.
executed by the Java Virtual Machine (JVM). That Everything in Java is an object. The object
means JVM converts the bytecode to machine oriented model of Java is simple and can be
readable form. JVM understand only the bytecode extended easily.
and therefore any infectious code can not be 5. Java is multithreaded and interactive language
executed by JVM. No virus can infect bytecode. Java supports multithreaded programming which
Hence it is difficult to trap the internet and network
allows a programmer to write such a program that
based applications by the hackers.
can perform many tasks simultaneously.
3 In programming languages like C or C++ the
This ultimately helps the developer to develop more
memory management is done explicitly by the user.
interactive code.
TM
Technical Publications
(1 --An
1) up thrust for knowledge
Java Programming 1-2 Basic Syntactical Constructs in Java
Following are the steps that illustrate execution As the name suggests, it is a virtual computer that
process of the application program - resides in the real computer. Java can achieve its
1. The user creates the Java source code in the text platform independence feature due to Java Virtual
editor. Machine.
2. The source code is compiled using the javac The execution of any Java program is carried out as
command. shown in Fig. 1.2.2
3. The javadoc tool can be used to create the HTML
files that document the source program.
4. On compiling the source program a class file gets
generated which consists of the byte code.
5. The developer may use javah tool for generating
the required header files.
6. The class file produced by javac can be interpreted
using java in order to produce an executable.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-4 Basic Syntactical Constructs in Java
3. Define JDK. List the tools available in JDK programming language. object oriented
explain any one in detail.
language. programming
MSBTE : Summer 15, Marks 4
language.
1.3 Difference between Java and other
Programming Languages 7. In C we can use In C++ we can In Java there is
MSBTE : Winter 16, Marks 4 the pointers. use the no concept of
pointers. pointers.
Sr. C C++ Java
No. 8. In C there is no In C++ we can In Java, there
class. The write a program must be at least
1. C is a language The C++ is a The Java is a structure is used without a class. one class
that needs to be language that language that instead of that. present.
compiled. needs to be gets interpreted
compiled. and compiled. Board Question
1. How java is different than other programming
2. C is platform C++ is platform Java is a language ?
dependent. dependent. platform MSBTE : Winter 16, Marks 4
independent.
1.4 How to Write and Execute Java Program
3. C does not C++ does not Java supports Java programs are always stored by filename extension
support multi- support multi- multi- java.
threading threading threading. The name of the Java program must be similar to its
programming. programming. class.
4. C does not C++ does not Using Java, one These java programs can be written using simple
have facility to have facility to can design very notepad file and executed on command prompt.
create and create and interactive and The structure of Java program is as follows -
implement the implement the user friendly Documentation section
graphical user graphical user graphical user
Package statements section
interface. interface. interface.
Import statements section
5. C does not have C++ has Java has Class definition
any exception exception exception
Main Method class
handling handling handling {
mechanism. mechanism mechanism public static void main(String[] args)
using try-catch using try-catch {
//main method definition
block. and throw.
}
}
6. C does not C++ supports Java does not
supports any multiple support Documentation section : The documentation section
object oriented inheritance. It multiple provides the information about the source program. This
programming is an object inheritance section contains the information which is not compiled by
concept. It is a oriented however it the Java. Everything written in this section is written as
procedure programming makes use of comment.
oriented interface.It is an
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-5 Basic Syntactical Constructs in Java
Package section : It consists of the name of the package by using the keyword package. When we use the
classes from this package in out program then it is necessary to write the package statement in the beginning of
the program.
Import statement section : All the required java API can be imported by the import statement. There are
some core packages present in the java. These packages include the classes and method required for java
programming. These packages can be imported in the program in order to use the classes and methods of the
program.
Class definition section : The class definition section contains the definition of the class. This class normally
contains the data and the methods manipulating the data.
Main method class : This is called the main method class because it contains the main() function. This class
can access the methods defined in other classes.
Note that we can write the
Example of My First Java Program program in simple Notepad.
Java Program[Firstprog.java]
How to Execute?
The output of this program can be generated on the command prompt using the commands.
Open command prompt and type javac command. The syntax of execution of Java program is
javac filename.java
java filename
Here is illustration -
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-6 Basic Syntactical Constructs in Java
Concept of Class
A single class can create any number of objects.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-8 Basic Syntactical Constructs in Java
Example 1.5.2 : Write a program to create a class account 1.6 Java Tokens
having variable accno, accname and balance. Define deposite MSBTE : Winter 16, Summer 17, 18, Marks 4
( ) and withdraw ( ) methods. Create one object of class and
perform the operation. The smallest individual and logical unit of the java
MSBTE : Winter 16, Marks 8 statements are called tokens. In Java there are five types
Solution : of tokens used. These tokens are -
public class Account 1. Reserved keywords 2. Identifiers
{
private double balance; 3. Literals 4. Operators
public void initialize() 5. Separators
{
Reserved keywords
balance=1000;
} Keywords are the reserved words which are enlisted as
public void deposit(double amount) below-
{
balance = balance + amount; abstract default int super
}
assert double interface switch
public void withdraw(double amount) boolean else long this
{
balance = balance - amount; byte extends native throw
}
break final new throws
public double getBalance()
{ case for package transient
return balance;
} catch float private try
public static void main(String args[])
{ char goto protected void
Account ac=new Account();
class if public volatile
ac.initialize();
System.out.println("Depositing some amount"); const implements return while
ac.deposit(100);
System.out.println("Total Balance is: "); continue import short true
ac.balance();
do instanceof static false
System.out.println("Withdrawing some amount");
ac.withdraw(200); null
System.out.println("Total Balance is: ");
ac.balance(); Identifiers
} Identifiers are the kind of tokens defined by the
}
programmer. They are used for naming the classes,
Board Questions methods, objects, variables, interfaces and packages in
1. Define a class and object. Write syntax to create the program.
class and object with an example. Following are the rules to be followed for the identifiers-
MSBTE : Summer 18, Marks 4
1. The identifiers can be written using alphabets, digits,
2. What is the use of new operator ? Is it necessary to
be used whenever object of the class is created ? underscore and dollar sign.
Why ? 2. They should not contain any other special character
MSBTE : Winter 16, Marks 4 within them.
3. There should not be a space within them.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-9 Basic Syntactical Constructs in Java
Separator
The variables have a scope which defines their visibility
and a lifetime.
() Parenthesis are used to - enclose the
1.6.2 Data Types
arguments passed to it to define precedence
Various data types used in Java are byte, short, int, long,
in the expression. For surrounding cast char, float, double and boolean.
type
byte
{} Curly brackets are used for - initialising This is in fact smallest integer type of data type. Its width
array for defining the block is of 8-bits with the range –128 to 127. The variable can
be declared as byte type as -
[] Square brackets are used for - declaring byte i,j;
array types dereferencing array values
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 10 Basic Syntactical Constructs in Java
int */
class DatatypeDemo
This is the most commonly used data type for defining the
{
numerical data. The width of this data type is 32-bit
public static void main(String args[])
having a range 2,147,483,648 to 2,147,483,647. The
{
declaration can be -
byte a=10;
int p,q;
short b=10*128;
long int c=10000* 128;
long d=10000*1000*128;
Sometimes when int is not sufficient for declaring some
double e=99.9998;
data then long is used. The range of long is really very
char f='a';
long and it is –9,223,372,036,854,775,808 to
boolean g=true; dynamic initialization
9,223,372,036,854,775,807. The declaration can be -
boolean h=false;
long x,y;
System.out.println("The value of a=: "+a);
float System.out.println("The value of b=: "+b);
To represent the real number (i.e. number that may have System.out.println("The value of c=: "+c);
System.out.println("The value of d=: "+d);
decimal point) float data type can be used. The width is
System.out.println("The value of e=: "+e);
32-bit and range of this data type is 1.4e – 045 to
System.out.println("The value of f=: "+f);
3.4e+038.
f++;
double System.out.println("The value of f after increment=: "+f);
To represent the real numbers of large range the double System.out.println("The value of g=: "+g);
System.out.println("The value of h=: "+h);
data type is used. Its width is 64-bit having the range
}
4.9e–324 to 1.8e+308.
}
Char
Output
This data type is used to represent the character type of
The value of a=: 10
data. The width of this data type is 16-bit and its range is
0 to 65,536. The value of b=: 1280
The value of c=: 1280000
Let us see one simple Java program which makes use of
various data types. The value of d=: 1280000000
The value of e=: 99.9998
boolean
The value of f=: a
Boolean is a simple data type which denotes a value to be The value of f after increment=: b
either true or false. The value of g=: true
Constants
Constants mean the fixed values that do not change during the execution of a program.
In Java various types of constants are used and these are as shown in following Fig. 1.6.1.
Numeric constants
Numeric constants are used for representing the numerical values. The numeric values can be integer or real
type. Hence there exists the integer and real constants.
Integer constants
Integers mean sequence of digits. There are three types of integers -
Decimal integer : The decimal integers consist of a set of digits 0 through 9. These numbers can be unary
numbers. That means these can be preceded by unary minus. For example - 111, – 200, 455
Octal integer : The octal integer constants consists of set of 0 to 7 having a zero at the beginning.
For example - 033, 0431, 0633
Hexadecimal integer : Along with the 0 to 9 digits, it also consists of the letters A to F.
Real constants : The real constants contain the floating point parts. For example - 0.045, 0.567, 0.3211
Character constants : A single character constant is enclosed within a pair of single quotes.
For example - ‘a’, ’T’, ‘1’
String constant : A string is a collection of characters enclosed between double quotes. The characters can be
alphabets, numbers, white spaces or special characters.
For example - “India” ,”Best10”, “s?ss”
Symbolic Constants
There are two problems that are associated with the constants and those are-
1. Modifiability : The constants may need to be modified during the program. For example : The value of
pi may be 3.14 at one place in the program and it may be required as 3.14159 at some other place in the
same program for the accuracy.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 12 Basic Syntactical Constructs in Java
Output Defintition:
A= 10
Type casting means explicit conversion between
The class variables are global to the corresponding incompatible data types.
class. This variable can be accessed by the objects of For casting the values we use following syntax:
that class.
(type) variable
Example of class variable
class VarScopeDemo Example:
{ double a;
private static int A;//class or static variable int b;
public static void main(String args[]) b=(int) a;
{ In the following Java program, we use the type casting
A=10;
System.out.println("A = "+A); Java Program[TypeCastProg.java]
} public class TypeCastProg
} {
Output public static void main(String[] args)
A= 10 {
double x;
1.6.6 Typecasting int y;
x=25.50;
Java allows the automatic conversion between these
System.out.println("Value of [double] x: "+x);
data types. System.out.println("Conversion of double to integer");
But Java performs type conversion between the y=(int)x;
compatible data type elements. System.out.println("Value of [integer] y: "+y);
int m;
For instance: If we assign an integer value to a float double n;
type element then Java automatically makes this m=10;
conversion. However, this automatic conversion can n=(double)m;
System.out.println("Value of [integer] m: "+m);
not be done between any data type, rather such a
System.out.println("Conversion of integer to double");
conversion is done with the compatible data type System.out.println("Value of [double] n: "+n);
elements.
}
Conditions in which Java allows automatic conversion
}
When two data types are compatible to each other.
When the target data type element is larger than the Output
source data type Value of [double] x: 25.5
Conversion of double to integer
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 14 Basic Syntactical Constructs in Java
Output Output
Performing arithmetic operations
a= 10 Performing Relational operations
b= 20 a= 10
b= 20
Addition of two numbers is 30
The a<b is true
PreIncrementing a 12
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 17 Basic Syntactical Constructs in Java
bitwise and & Binary AND Operator copies a bit to the result if it exists in both A&B=00100011 &
operands. 00001110= 00000010
Truth Table
A B Output
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0 = 00101111 i.e. 47
0 1 1
1 0 1
1 1 0
bitwise XOR ^ Binary XOR Operator copies the bit if it is set in one operand but A^B
not both. =
Truth Table 00100011 ^ 00001110
A B Output =00101101
0 0 0 i.e. 45
0 1 1
1 0 1
1 1 0
bitwise complement ~ Binary ones complement operator is unary and it has effect of ~A=11011100 = ~36
flipping bits.
Left shift << The left operands value is moved left by the number of bits 00100011<<2
specified by the right operand. =1000 1100
Right shift >> The left operands value is moved right by the number of bits 00100011>>2
specified by the right operand. =0000 1000
Zero fill right shift >>> The left operands value is moved right by the number of bits 00100011>>>2
specified by the right operand and shifted values are filled up == 0000 1000
with zeros.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 18 Basic Syntactical Constructs in Java
1.7.7 Instance of Operators and Dot Operators 3 (type type cast Right -> Left
cast) object creation
There are two special operators used in Java- new
instanceof and dot operators.
For determining whether the object belongs to 4 * multiplication Left -> Right
particular class or not an instanceof operator is used. / division
% modulus (remainder)
For example -
Ganga instanceof River 5 +- addition, subtraction Left -> Right
If the object Ganga is an object of class River then it + String concatenation
returns true otherwise false.
6 << Left shift Left -> Right
The dot operator is used to access the instance variable
>> Signed right shift
and methods of class objects. >>> Unsigned or zero-fill
For example - Right shift
Customer.name //for accessing the name of the
7 < Less than Left -> Right
customer
<= Less than or equal to
Customer.ID //for accessing the ID of the customer > Greater than
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 19 Basic Syntactical Constructs in Java
15 = Assignment and short Right -> Left acos(double val) Returns the angle whose cosine is val
+= hand assignment atan(double val) Returns the angle whose tan is val
-= operators
b
*= pow(double a, It computes a
/= double y)
%= exp(double a) It computes e
a
&=
^= sqrt(double a) It computes square root of a
|= max(a,b) It computes the maximum of a and b
<< =
>> = min(a,b) It computes the minimum of a and b
>>> = log(val) It computes the logarithmic values of
val
1.7.9 Evaluation of Expression
abs(val) It computes the absolute value of val
Expression is a combination of operators and operands
in specific manner. ceil(val) It returns the smallest whole number
which is greater than or equal to val
For example
floor(val) It returns the largest whole number
c=a+b*c; // Expression with arithmetic operators
which is lesser than or equal to val.
(a>b)&&(b<c)// Expression with logical operators and
relational operators Following is an example of Java program which makes
use of mathematical function -
The evaluation of expression is an order of evaluating
the expression using precedence and associativity Example 1.7.1 : Write a simple Java program to illustrate use
of mathematical function.
rules. Solution :
For example -
Java Program[MathDemo.java]
To evaluate 2+3*4 we will first perform 3*4=12, then
class MathDemo
add 2 to 12 and the result of this expression will be 14. {
This is because multiplication has higher precedence public static void main(String[] args)
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 20 Basic Syntactical Constructs in Java
Syntax
The maximum of 10 and 20 is 20
if(apply some condition)
{
The minimum of 10 and 20 is 10
statement 1
statement 2
The sin of 25.0 is -0.13235175009777303
.
.
The cos of 25.0 is 0.9912028118634736
.
statement n
Board Questions
}
1. Describe any two relational and any two logical
operators in Java with simple example. 1.8.2 if else Statement
MSBTE : Summer 16, Marks 4
The syntax for if…else statement will be -
2. Explain any two relational operators in Java with if(condition)
example. statement
MSBTE : Summer 17, Marks 4 else
3. ‘? :’ What this operator is called ? Explain with statement
suitable example.
MSBTE : Summer 15, Winter 15, Marks 4 For example
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 21 Basic Syntactical Constructs in Java
{ System.out.println(First Class");
System.out.println(“I will go out”); else
System.out.println(“And will meet my friend”); System.out.println(" Distinction!!!.");
System.out.println(“we will go for a movie”); }
System.out.println(“Any how I will enjoy my life”); }
}
Output
1.8.3 Nested if-else Statement First Class
Solution : break;
}
Sr. if statement switch statement }
No. }
1 if-else statement test for switch statement tests Output
equality as well as for only for equality. PHP
logical expression.
Program Explanation : In above Program,
2 The if statement evaluates The switch statement
As value of a=1, the control will enter in the outer switch
integer, character pointer, evaluates only character
with case 1.
floating point or boolean or integer value.
values. As value of b=2,the control will enter in the inner switch
3 The if-else statement uses switch statement uses
with case 2.
multiple statements for single expression for Hence the output is “PHP”.
multiple choices. multiple choices.
1.8.7 The while Statement
4 Either if statement will be Switch statements
This is one form of statement which is used to have
executed or else statement executes one case after
will be executed. other until it reads break iteration of the statement for the any number of times.
statement. The syntax is,
while(condition)
1.8.6 Nested Switch Statement {
Nested Switch statement is a switch statement inside statement 1;
statement 2;
another switch statement.
statement 3;
For example - Consider following Java program …
public class Test statement n;
{ }
public static void main(String[] args)
{ For example
int a,b; int count=1;
a=1;b=2; while(count<=5)
switch(a) {
{ System.out.println(“I am on line number “+count);
case 1: count++;
switch(b) }
{ Let us see a simple Java program which makes the use of
case 1:System.out.println("Java");
while construct.
break;
case 2:System.out.println("PHP");
Java Program [whiledemo.java]
break;
/*
}
This is java program which illustrates
break;
while statement
case 2:
*/
switch(b)
class whiledemo
{
{
case 1:System.out.println("HTML");
public static void main(String args[])
break;
{
case 2:System.out.println("XML");
int count=1,i=0;
break;
while(count<=5)
}
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 23 Basic Syntactical Constructs in Java
i=i+1; Solution :
System.out.println("The value of i= "+i);
public class DigitSum
count++;
{
}
int num;
}
public void initialize()
}
{
Output num=123;
The value of i= 1 System.out.println("The number is: "+num);
The value of i= 2 }
The value of i= 3 public void display()
The value of i= 4 {
The value of i= 5 int sum=0;
while(num > 0)
Example 1.8.2 : Define a class having one 3 digit number,
num as data member, initialize and display reverse of that {
number. sum = sum + (num % 10);
MSBTE : Summer 15,16, Marks 4 num = num / 10;
Solution : }
System.out.println("The sum of digits is: "+sum);
public class NumReverse
}
{
public static void main(String[] args)
int num;
{
public void initialize()
DigitSum obj=new DigitSum();
{
obj.initialize();
num=123;
obj.display();
System.out.println("The number is: "+num);
}
}
}
public void display()
{ Output
int rev=0; The number is: 123
System.out.print("Reverse of number is: "); The sum of digits is: 6
while(num > 0)
Example 1.8.4 : Write a program to find the number of and
{
sum of all integers greater than 100 and less than 200 that are
rev = rev * 10 + (num % 10); divisible by 7. MSBTE : Winter 16, Marks 4
num=num/10; Solution :
}
System.out.println(rev); public class DigitRange
} {
public static void main(String[] args) public static void main(String[] args)
{ {
NumReverse obj=new NumReverse(); int sum=0;
obj.initialize();
System.out.println("\n Numbers between 100 to 200
obj.display(); which is divisible by 7");
}
for(int i=101;i<200;i++)
}
{
Output if(i%7==0)
The number is: 123
{
Reverse of number is: 321
System.out.print(" "+i);
Example 1.8.3 : Write a program to find sum of digit of sum= sum + i;
number entered by user.
MSBTE : Winter 16, Summer 17, Marks 4 }
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 24 Basic Syntactical Constructs in Java
executed at least once. for is a keyword used to apply loops in the program. Like
This means that - other control statements for loop can be categorized in
o The statement inside the do…while body gets simple for loop and compound for loop.
executed first and then the while condition is Simple for loop :
checked for next execution of the statement. for (statement 1;statement 2;statement 3)
o Whereas in the while statement first of all the execute this statement;
condition given in the while is checked first and Compound for loop :
then the statements inside the while body get for(statement 1;statement 2; statement 3)
executed when the condition is true. {
execute this statement;
Syntax execute this statement;
do execute this statement;
{ that’s all;
}
statement 1;
Here
statement 2;
… Statement 1 is always for initialization of conditional
statement n; variables,
}while(condition); Statement 2 is always for terminating condition of the for
loop,
For example
Statement 3 is for representing the stepping for the next
Java Program [dowhiledemo.java] condition.
/*
For example :
This is java program which illustrates
for(int i=1;i<=5;i++)
do…while statement
{
*/
System.out.println(“Java is an interesting language”);
class dowhiledemo
System.out.println(“Java is a wonderful language”);
{
System.out.println(“And simplicity is its beauty”);
public static void main(String args[])
}
{
int count=1,i=0; Let us see a simple Java program which makes use of for
do loop.
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 25 Basic Syntactical Constructs in Java
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 26 Basic Syntactical Constructs in Java
Output {
1 1 1 1 1 System.out.print("*");
2 2 2 2 }
3 3 3 System.out.println("");
4 4
}
5
}
Example 1.8.8 : Write a java program to display all the odd }
numbers between 1 to 30 using for loop and if statement.
MSBTE : Summer 18, Marks 8 Output
Solution : *
***
public class Test
*****
{
*******
public static void main(String[] args)
*********
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 28 Basic Syntactical Constructs in Java
Example 1.8.10 : Write a Java program to display following label is the name of the block which need to be
number pattern
1 skipped.
1 2 Following program demonstrates the use of labeled
1 2 3
1 2 3 4
break.
1 2 3 4 5
Example Program
Solution :
class breakLblDemo
class NumberPatternDisplay {
{ public static void main(String args[])
public static void main(String[] args) {
{ int i=5;
first:
int i,j;
{
for(i=1; i<=5; i++)
second:
{ {
for(j=1; j<=i; j++) third:
{ {
System.out.print(j+" "); System.out.println("Before the break.");
if(i==5)
}
break second; // break out of second block
System.out.println("");
System.out.println("Inside third block.");
} }
} System.out.println("Inside second block.");
} }
System.out.println("Inside first block.");
Output
}
}
}
Output
Before the break.
Inside first block.
specific instruction. This can be done using the The labelled continue is basically a continue statement
statements like goto. with label.
Java provides the support for jump statement using The syntax is
labeled break. continue label;
The syntax for labelled break is Example Program : Following java program,
break label; illustrates the labeled continue statement.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 29 Basic Syntactical Constructs in Java
The for-each element is used to access each element of 2. Explain break and continue statements with
example. MSBTE : Summer 16, Marks 4
an array.
3. State syntax and describe working of ‘for each’
There are two advantages of for-each statement - version of for loop with one example.
i) It eliminates the possibility of bug. MSBTE : Summer 16, Marks 4
ii) It makes the code more readable and 4. Illustrate with example the use of switch case
statement. MSBTE : Winter 17, Marks 4
understandable.
5. Describe break and continue statement with
example. MSBTE : Winter 15, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 30 Basic Syntactical Constructs in Java
Notes
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-1 Derived Syntactical Constructs in Java
UNIT - II
2 Derived Syntactical
Constructs in Java
7. When we declare the constructor explicitly then we
2.1 Constructors and Method must declare the object of that class.
Definition : The constructor is a specialized method Difference between Constructor and Method
for initializing objects.
Sr. Constructor Method
Name of the constructor is same as that of its class No.
name. In other words, the name of the constructor and
1. The name of the The name of the method
class name is same.
constructor must be should not be the class
Class Test same as the class name.
{ Class Name name.
TM
Technical Publications (2 --An
1) up thrust for knowledge
Java Programming 2-2 Derived Syntactical Constructs in Java
This constructor is automatically called when the Program Explanation : In above program,
object of the class is created. 1) We have created parameterized constructor by passing
Example Program the parameters id and Name. Note that these
class Test constructors will be called at the time of creation of
{ objects p1 and p2.
Test() <-- This is default constructor
{ 2) Then using these objects we can invoke the method
System.out.print("This message is from constructor"); display().
}
public static void main(String args[]) Board Questions
{ 1. What is constructor? Describe the use of
Test t=new Test(); parameterized constructor with suitable example.
} MSBTE : Winter 15, Marks 4
}
2. Define constructor. Explain parameterized
Output constructor with example.
MSBTE : Summer 16, Marks 4
This message is from constructor
3. Enlist types of constructor. Explain any two with
2) Parameterized Constructor example. MSBTE : Summer 18, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-3 Derived Syntactical Constructs in Java
1. Call by value 2. Call by reference In the function Fun we are changing the values of a
and b by adding 5 to them. But these incremented
In the call by value method the value of the actual
values will remain in the function definition body only.
argument is assigned to the formal parameter. If any
After returning from this function these values will not
change is made in the formal parameter in the
get preserved. Hence we get the same values of a and b
subroutine definition then that change does not reflect
before and after the function call.
the actual parameters.
On the contrary the parameter passing by reference
Following Java program shows the use of parameter
allows to change the values after the function call. But
passing by value -
use of variables as a parameter does not allow to pass
Example : Java Program
the parameter by reference.
public class ParameterByVal
{ For passing the parameter by reference we pass the
void Fun(int a,int b) object of the class as a parameter.
{
Creating a variable of class type means creating
a=a+5;
b=b+5; reference to the object. If any changes are made in the
} object made inside the method then those changes get
public static void main(String args[]) preserved and we can get the changed values after the
{
function call.
ParameterByVal obj1=new ParameterByVal();
int a,b;
a=10;b=20;
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-4 Derived Syntactical Constructs in Java
Solution : Output
class CommandLineDemo D:\MSBTE_JAVA _Programs> javac
{ CommandLineDemo.java
public static void main(String args[]) D:\MSBTE_JAVA _Programs> java CommandLineDemo 25
{ The square root is: 5.0
int num=Integer.parseInt(args[0]);
if(num%2==0) 2.7 Varargs : Variable Length Arguments
System.out.print("The number is even");
If we want to pass variable length arguments to the
else
System.out.print("The number is odd");
method then varargs is used.
} Syntax : Following is the syntax of using Varargs -
} access_specifier static void method name(object
…arguments)
Output
{
D:\MSBTE_JAVA _Programs> javac
//Method body
CommandLineDemo.java
}
D:\MSBTE_JAVA _Programs> java CommandLineDemo 5
The number is odd The ellipsis (…) is used while representing the
Example 2.6.2 : Write a program to accept two numbers as varargs.
command line arguments and print the addition of those Thus with the help of three dots one can specify
numbers. MSBTE : Summer 17, Marks 4
variable length arguments for a particular method.
Solution :
class CommandLineDemo Following simple Java program makes use of varargs.
{
public static void main(String args[]) Java Program [varargsDemo.java]
{ public class varargsDemo
int num1=Integer.parseInt(args[0]); {
int num2=Integer.parseInt(args[1]); public static void main(String[] args)
int result=num1+num2; {
System.out.print("The addition is: "+result); test("Archana","Supriya");
Method uses varargs
} test("Jayashri","Snehal","Rohini");
} }
public static void test(String...Student)
Output {
D:\MSBTE_JAVA _Programs> javac for(String name:Student)
CommandLineDemo.java
System.out.println("Welcome "+name);
D:\MSBTE_JAVA _Programs> java CommandLineDemo 5
}
10
}
The addition is: 15
Output
Example 2.6.3 : Write a program to accept number from
Welcome Archana
command line and print square root of the number.
MSBTE : Winter 17, Marks 4 Welcome Supriya
Solution : Welcome Jayashri
Welcome Snehal
class CommandLineDemo
Welcome Rohini
{
public static void main(String args[])
Program Explanation :
{
int num=Integer.parseInt(args[0]); In above program,
double result=Math.sqrt(num); 1) We have used two methods(named test) - To the first
System.out.print("The square root is: "+result);
method two arguments are passed and to the second
}
} method three arguments are passed.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-6 Derived Syntactical Constructs in Java
2) While defining the method test we have used three 2.9 The Object Class
dots and a collection which is named as Student. That Winter 16, 17, Marks 6
means in the collection(sort of array) Student , all the In Java there is a special class named Object.
declared strings can be stored. Object is a superclass of all other classes by default.
3) Hence we get the output as names of all the students The object can be obtained using getObject() method.
which are passed to the method as variable length
For example –
arguments. Object obj=getObject();
a[9]=10; a[i][j]=k+10;
System.out.println("The element at a[5] is: "+a[5]); k=k+10;
} }
} }
When you run this program you will get a[5] to be 6. System.out.println("You have stored...");
Another way of initialization of array is for(int i=0;i<3;i++)
int a[ ]= {1,2,3,4,5,6,7,8,9,10}; {
for(int j=0;j<3;j++)
Two Dimensional Arrays {
The two dimensional arrays are the arrays in which System.out.print(" "+a[i][j]);
}
elements are stored in rows as well as in columns. For
System.out.println();
example
}
}
}
Output
Storing the numbers in array
You have stored...
10 20 30
The two array can be declared and initialized as follows 40 50 60
70 80 90
Syntax
data_type array_name=new data_type[size];
The typical application of two dimensional arrays is
performing matrix operations.
For example
Example 2.11.1 : Define a class ‘employee’ with data
members empid, name and salary.
int a=new int[10]; Accept data for five objects using array of objects and print it.
MSBTE : Summer 15, Marks 6
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-9 Derived Syntactical Constructs in Java
Example Program
equal or not. We use method equals() for that purpose.
class charAtProg This method is of Boolean type. That is, if two strings are
{ equal then it returns true otherwise it returns false.
public static void main(String args[]) The syntax is –
{ boolean equals(String Str);
String fruit=new String("mango");
Let us see one illustrative program –
char ch;
ch=fruit.charAt(2); //It will output character n Example program
System.out.println(ch); class StringCompareDemo
} {
} public static void main(String[] args)
{
3) The compareTo()
String str1=new String(“INDIA”);
The java string compareTo() method compares the given String str2=new String(“india”);
string with current string lexicographically. It returns if(str1.equals(str2)==true)
System.out.println(“\n The two strings are equal”);
positive number, negative number or 0.
else
If s1>s2 it returns positive number
System.out.println(“\n The two strings are not equal”);
If s1<s2 it returns negative number }
If s1==s2 It returns 0 }
Example Program
class cmpareTo
{
public static void main(String args[])
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 11 Derived Syntactical Constructs in Java
We can look for the desired substring from the given 5) The equalsIgnoreCase()
string using a method substring(). The syntax of method It returns true if characters of both strings are equal
substring() is as follows – ignoring case otherwise it returns false.
String substring(int start_index,int end_index)
Example Program
Example program class Test
class SubstringDemo {
{ public static void main(String args[])
public static void main(String[] args) {
{ String s1="java";
String str1=new String(“I love my country very much”); String s2="JAVA";
System.out.println(“\n One substring from the given String s3="PHP";
sentence is:”+str1.substring(2,6)); System.out.println(s1.equalsIgnoreCase(s2));//returns
System.out.println(“\n And another substring //true
is:”+str1.substring(18)); System.out.println(s2.equalsIgnoreCase(s3));//returns
} //false
} }
}
charAt(int index) It returns a specific character from the sequence which is specified by the index.
delete(int start,int end) It deletes the characters from the string specified by the starting and ending index.
insert(int offset,char ch) It inserts the character at the position specified by the offset.
setCharAt(int index,char ch) The character specified by the index from the stringbuffer is set to ch.
replace(int start,int end,String str) It replaces the characters specified by the new string
1. The length of string object is fixed. The length of stringBuffer can be increased.
2. The String object is immutable, that means we can not The stringBuffer class is immutable.
modify the string once created.
Example 2.12.1 : Write a JavaProgram illustrating the difference between the capacity and length function of StringBuffer
Solution :
public class StringBuffDemo{
public static void main(String args[]) creating string buffer in str
{
StringBuffer str=new StringBuffer("Java");
Finding length of str
System.out.println("The String Buffer is "+str);
System.out.println("The length is "+str.length());
System.out.println("The capacity is "+str.capacity());
Finding capacity of str
}
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 13 Derived Syntactical Constructs in Java
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 14 Derived Syntactical Constructs in Java
2.13 Vector
void insertElementAt(object For inserting the element in
MSBTE : Winter 15, 16, Summer 15, 16, 17, Marks 8
obj,int pos) the vector specified by its
Vector is a class in Java that implement the dynamic
position.
array. This class stores any number of objects of any
data type. boolean removeElement This method removes the
This class is defined by java.util package. (object ele) specified element.
In vector one can store the elements of any data type.
That means in a single vector you store integer, string, void removeAllElements() This method is for removing
double or any other data type elements altogether. all the elements from the
Vector can be created like this - vector
vector myvector=new vector(); //declaring vector
void removeElementAt(int The element specified by its
without size
pos) position gets deleted from the
vector yourvector= new vector(5);//declaring vector
with size. vector.
We can directly add the We can not directly add the vector.
simple data type element in simple data type element in the void setSize(int size) This method is for setting the
the array. vector we need to add an object. size of the vector.
Advantages of vectors over array Example 2.13.1 : Write a program to create a vector with
1. Vectors contain elements of varying data types. seven elements as (10, 30, 50, 20, 40,10, 20). Remove element
at 3rd and 4th position. Insert new element at 3rd position.
2. The size of vector can be changed whenever required. Display the original and current size of the vector.
3. It can store simple objects. MSBTE : Winter 15, Marks 8
Following are some most commonly used methods of OR Write a program to implement a vector class and its
vector class - method for adding and removing elements. After remove
display remaining list.
MSBTE : Summer 16, Marks 8
Method Description
Solution:
void addElement(object ) For adding some element in
import java.io.*;
the vector this method is used.
import java.util.*;
Object elementAt(int index) It returns the element present class VectorProg
at specified location(index) in {
public static void main(String[] args)throws IOException
vector.
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 15 Derived Syntactical Constructs in Java
4. What is : i) Add Element ( ) and ii) Element At Suppose an object for holding an integer value is
( ) command in vector created then we can retrieve the integer value from it
MSBTE : Winter 16, Marks 4
using typevalue() method. For instance the object obj
2.14 Wrapper Classes contains an integer value then we can obtain the
MSBTE : Summer 15, Winter 17, Marks 8 integer value from obj. It is as follows -
Wrapper classes are those classes that allow primitive int num=obj.intValue();
data types to be accessed as objects. Similarly we can use floatValue(), doubleValue() and
The wrapper class is one kind of wrapper around a longValue().
primitive data type. The wrapper classes represent the Similarly in order to convert the numerical value to
primitive data types in its instance of the class. string the toString() method can be used. For instance
Following table shows various primitive data types and str=Integer.toString(int_val)
the corresponding wrapper classes - The varibale int_val can be converted to string str.
For converting the string to numerical value the
Primitive data type Wrapper class
parseInt or parseLong methods can be used.
boolean Boolean
Points to remember about wrapper classes
byte Byte
1. The wrapper classes do not contain the constructors.
char Character 2. The methods of the wrapper classes are static.
3. After assigning the values to the wrapper class we
double Double
cannot change them.
float Float
Example : Java Program
int Integer import java.io.*;
import java.lang.*;
long Long class WrapperDemo
{
short Short public static void main(String[] args)
{
void Void System.out.println("Creating an object for value 10");
Integer i=new Integer(10);
Methods to handle wrapper classes are enlisted in the
System.out.println("Obtaining the value back from the
following table - object: "+i.intValue());
String str="100";
Method used Description
System.out.println("The string is: "+str);
System.out.println("Obtaining the numeric value from the
Integer val=new An object is created for the integer
string: "+ Integer.parseInt(str));
Integer(int_var) variable int_var. }
}
Float val=new An object is created for the Float
Float(f_var) variable f_var.
Output
Double val=new An object is created for the double Creating an object for value 10
Obtaining the value back from the object: 10
Double(d_var) variable d_var.
The string is: 100
Obtaining the numeric value from the string: 100
Long val=new An object is created for the Long
Long(Long_var) variable Long_var.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 17 Derived Syntactical Constructs in Java
Example 2.14.1 Define wrapper class. Give the following 2) Wrapper classes are used to convert numeric value to
wrapper class methods with syntax and use : string using wrapper class.
1) To convert integer number to string.
2) To convert numeric string to integer number. 3) Wrapper class is a medium to store primitive data type
3) To convert object numbers to primitive numbers sing type in an object.
value ( ) method. 4) Using the typeValue() method we can retrieve value
MSBTE : Summer 15, Marks 8
of the object as its primitive data type.
Solution : Wrapper class – Refer section 2.14.
class WrapperDemo1 Board Question
{ 1. What is the use of wrapper classes in Java ?
public static void main(String args[]) Explain float wrapper with its methods.
{ MSBTE : Winter 17, Marks 4
System.out.println("\tInteger to String Conversion");
int i=100; 2.15 Enumerated Types
String str=Integer.toString(i);
The enumerated data types can be denoted by the
System.out.println("int Value: "+i);
System.out.println("Equivalent String: "+str);
keyword enum.
System.out.println("\tString to Integer Conversion"); The enum helps to define the user defined data type.
str="500";
The value can also be assigned to the elements in the
int j=Integer.parseInt(str);
System.out.println("String: "+str);
enum data type.
System.out.println("Equivalent int: "+j); Java Program[EnumDemo.java]
System.out.println("\tobject to Primitive number using public class EnumDemo
typeValue Conversion"); {
Integer a=new Integer(1000);//creating object for float enum Fruit
value {
int val=a.intValue(); Mango,
System.out.println("Integer: "+a); Guava,
Orange,
System.out.println("Equivalent int value: "+val);
Apple
Float b=new Float(2000);//creating object for float value
}
float f=b.floatValue(); public static void main(String[] args)
System.out.println("Float: "+b); {
System.out.println("Equivalent float value: "+f); for(Fruit f:Fruit.values())
} {
} Test(f);
}
Output }
Integer to String Conversion private static void Test(Fruit f)
int Value: 100 {
Equivalent String: 100 if(f.equals(Fruit.Mango))
String to Integer Conversion System.out.println("Mango is yellow");
if(f.equals(Fruit.Orange))
String: 500
System.out.println("The color and name of orange is the
Equivalent int: 500 same");
object to Primitive number using typeValue }
Conversion }
Integer: 1000
Output
Equivalent int value: 1000 Mango is yellow
Float: 2000.0 The color and name of orange is the same
Equivalent float value: 2000.0
Uses of Wrapper Class
1) Wrapper classes are used to convert numeric strings
into numeric values.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 18 Derived Syntactical Constructs in Java
Notes
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-1 Inheritance, Interface and Package
UNIT - II
Part I : Inheritance
3.1 Inheritance
Definition: Inheritance is a mechanism in Java by
which derived class can borrow the properties of base
class and at the same time the derived class may have
some additional properties. Fig. 3.1.1
The inheritance can be achieved by incorporating the
3.2 Types of Inheritance
definition of one class into another using the keyword
MSBTE : Summer 15, 17, 18, Winter 16, 17, Marks 8
extends.
1. Single inheritance :
Inheritance Features:
In single inheritance there is one parent per derived
1) It helps in reduced code.
class. This is the most common form of inheritance.
2) It makes use of reusability of code.
3) It enhances readability of code.
4) Execution of code is efficient.
The parent class is called base class and child class is 2. Multiple inheritance :
called derived class. In multiple inheritance the derived class is derived from
For example more than one base class.
Class A This is Base class
{
…
}
Class B extends A This is Derived class
{
… // uses properties of A
}
Fig. 3.2.2 Multiple inheritance
TM
Technical Publications (3 --An
1) up thrust for knowledge
Java Programming 3-2 Inheritance, Interface and Package
Output
The value of a= 10
The value of b= 20
Fig. 3.2.4 Hybrid inheritance The value of c= 200
Output
Name: Ankita
age: 27
Employee Designation: Manager
Employee Salary: 10000.0
MSBTE : Summer 15, Marks 4 Example 3.2.3 : Create a class ‘Rectangle’ that contains
Solution : ‘length’ and ‘width’ as data members. From this class derive
class box which has additional data member ‘depth’. Class
class Person ‘Rectangle’ consists of a constructor and an area ( ) function.
{ The derived ‘Box’ class have a constructor and override
String name; function named area ( ) which returns surface area of ‘Box’ and
int age; a volume ( ) function. Write a java program calling all the
member function.
void get_personInfo(int ag,String nm)
MSBTE : Winter 16, Marks 6
{
age=ag;
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-4 Inheritance, Interface and Package
public static void Sum(int num1,int num2,int num3) 3.4 Constructor Overloading
{ MSBTE : Winter 17, Marks 8
int ans;
Constructor overloading in Java allows to have more
ans=num1+num2+num3;
System.out.println(ans);
than one constructor inside one Class.
} Multiple constructor with different signatures is called
} as overloaded constructor.
Output Following is a simple Java program that illustrates the
Sum of two integers concept of constructor overloading.
30
Example Program
Sum of two double numbers
public class Rectangle2
30.9
{
Sum of three integers
int height,width;
60
double ht,wd;
Rectangle2(int h,int w)//constructor with two integer
Program Explanation
//values
In above program, we have used three different methods {
possessing the same name. Note that, height=h;
width=w;
on line A }
We have invoked a method to which two integer Rectangle2(double h,double w)//constructor with two
//double values
parameters are passed. Then compiler automatically
{
selects the definition public static void Sum(double ht=h;
num1,double num2) to fulfil the call. Hence we get the wd=w;
output as 30 which is actually the addition of 10 and 20. }
Rectangle2(int val)//constructor with single integer value
on line B {
height=val;
We have invoked a method to which two double
}
parameters are passed. Then compiler automatically void area1()
selects the definition public static void Sum(double {
num1,double num2) to fulfill the call. Hence we get the System.out.println("Now, The function is called...");
int result=height*width;
output as 30.9 which is actually the addition of 10.5 and
System.out.println("The area is "+result);
20.4. }
void area2()
on line C
{
We have invoked a method to which the three integer System.out.println("Now, The function is called...");
parameters are passed. Then compiler automatically double result=ht*wd;
selects the definition public static void Sum(int System.out.println("The area is "+result);
}
num1,int num2,int num3) to fulfil the call. Hence we
void area3()
get the output as 60 which is actually the addition of 10, {
20 and 30. System.out.println("Now, The function is called...");
int result=height*height;
Board Question System.out.println("The area is "+result);
1. Explain method overloading with example. }
MSBTE : Winter 15, Marks 4 }
class OverLoadConstr
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-7 Inheritance, Interface and Package
Output
Definition: Method overriding is a mechanism in
Enter data for Person#1
Enter Adhar Number: which a subclass inherits the methods of superclass
123 and sometimes the subclass modifies the
Enter Name: implementation of a method defined in superclass.
AAA
Enter Pan Number: The method of superclass which gets modified in
AAA12 subclass has the same name and type signature.
Enter data for Person#2
The overridden method must be called from the
Enter Adhar Number:
222
subclass.
Enter Name: Consider following Java Program, in which the
BBB method(named as fun ) in which a is assigned with
Enter Pan Number:
some value is modified in the derived class. When an
BBB22
Enter data for Person#3 overridden method is called from within a subclass, it
Enter Adhar Number: will always refer to the version of that method
333 redefined by the subclass. The version of the method
Enter Name:
defined by the superclass will be hidden.
CCC
Enter data for Person#4 Example Program
Enter Adhar Number:
444 class A
Enter Name: {
DDD int a=0;
Enter data for Person#5 void fun(int i)
Enter Adhar Number: {
555 this.a=i;
Enter Name: }
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-9 Inheritance, Interface and Package
Output {
Operating System final void fun()
Windows Operating System {
Unix Operating System System.out.println("\n Hello, this another function");
}
Program Explanation : In above program,
}
1) The base class is OS, and two classes namely
Output
WindowsOS and UNIXOS is derived from it. Test.java:10: fun() in Test1 cannot override fun() in Test;
2) In main method, the objects for these three classes are overridden method is final
final void fun()
created.
^
3) The reference variable ref for base class is also 1 error
created. Now this reference is assigned with each of
these three objects. Program Explanation : The above program,
4) The display method (which is actually overridden 1) on execution shows the error. Because the method fun
method) is invoked using the objects. Thus is declared with the keyword final and it cannot be
appropriate display() method is invoked at runtime. overridden in derived class.
method overriding is avoided. That means the methods 3.8 Use of Super
those are declared with the keyword final cannot be MSBTE : Summer 16, Winter 15, 17, Marks 6
overridden. Super is a keyword used to access the immediate parent
Consider the following Java program which makes use class from subclass.
of the keyword final for declaring the method - There are three ways by which the keyword super is
Example Program used.
class Test
{
final void fun()
{
System.out.println("\n Hello, this function declared using
final");
}
} Fig. 3.8.1 Use of super
class Test1 extends Test
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 11 Inheritance, Interface and Package
Output
B:In fun1
A:In fun2
C:In fun1 Example Program
A:In fun2 class StaticProg
{
Program Explanation : In above program, static int a=10;
static void fun(int b)
1) The class A is a superclass. It is an abstract class as
{
well. The name of this class is preceded by the
keyword abstract. This class is abstract because it System.out.println("b= "+b);
contains an abstract method fun1. The method is System.out.println("a= "+a);
called abstract because it does not have any definition
}
body. Note that the abstract method should be
}
declared with the keyword abstract.
class AnotherClass
2) There are two classes B and C which are subclasses of {
superclass A. The function definition fun1 is public static void main(String[] args)
class the static members of class StaticProg are accessed Difference between Class and Interface
without using any object. Note that we have simple used
An interface is similar to a class but there lies some
a syntax
difference between the two.
ClassName.staticMember
Hence by using StaticProg.a and StaticProg.fun we can Class Interface
access static members
The class is denoted by a The interface is denoted
Restrictions on Static
keyword class. by a keyword interface.
The static methods must can access only static data.
The static method can call only the static method and The class contains data The interfaces may
members and methods. But the contain data members and
can not call a non static method.
methods are defined in class methods but the methods
The static method can not refer to this pointer. implementation. Thus class are not defined. The
The static method can not refer to super method. contains an executable code. interface serves as an
outline for the class.
Board Question
1. Which are the restrictions present for static By creating an instance of a You can not create an
declared methods ? MSBTE : Summer 18, Marks 4 class the class members can be instance of an interface.
accessed.
Part II : Interface
The class can use various The interface makes use of
3.11 Definition of Interface access specifiers like public, only public access
MSBTE : Summer 16, 17, Marks 8 private or protected. specifier.
Syntax of Interface
The members of a class can be The members of interfaces
The interface can be defined using following syntax constant or final. are always declared as
access_modifier interface name_of_interface final.
{
return_type
Features of Interface
method_name1(parameter1,parameter2,…parametern);
… 1) An interface can contain any number of methods.
return_type
2) Interface can be written in a file with .java extension.
method_name1(parameter1,parameter2,…parametern);
type static final variable_name=value; 3) An interface does not contain any constructor.
… 4) All the methods in interface are abstract(i.e. they are
not defined;only declared)
}
5) An interface not be extended by class ; it is
The access_modifier specifies the whether the
implemented by class.
interface is public or not. If the access specifier is not
specified for an interface then that interface will be Board Questions
accessible to all the classes present in that package 1. Write syntax of defining interface. Write any major
only. But if the interface is declared as public then it two differences between interface and class.
will be accessible to any of the class. MSBTE : Summer 16, Marks 6
2. What is meant by interface ? State its need and
The methods declared within the interface have no
write syntax and features of interface.
body. It is expected that these methods must be defined MSBTE : Summer 17, Marks 8
within the class definition.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 15 Inheritance, Interface and Package
Java Program[InterfaceDemo.java]
class A implements my_interface
{ Defining the method declared in the
public void my_method(int i) interface
{
System.out.println("\n The value in the class A: "+i);
}
public void another_method() //Defining another method not declared in interface
{
System.out.println("\nThis is another method in class A");
}
}
class InterfaceDemo
{
public static void main(String args[])
Object of class A is of type
{ my_interface. Using this object
my_interface obj=new A(); method can be accessed
//or A obj=new A() is also allowed
A obj1=new A();
obj.my_method(100);
obj1.another_method();
}
}
Step 3 : Compile the program created in step 2 and get the following output
The value in the class A: 100
Program Explanation :
In above program,
1) The interface my_interface declares only one method i.e. my_method. This method can be defined by
class A.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 16 Inheritance, Interface and Package
2) There is another method which is defined in class A and that is another_method. Note that this method is
not declared in the interface my_interface. That means, a class can define any additional method which is
not declared in the interface.
Board Question
1. What is meant by an interface ? State its need and write syntax and features of an interface. Give one
example. MSBTE : Winter 15, Marks 8
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 17 Inheritance, Interface and Package
Example Program
Step 2 : Write a simple Java program having two classes 1. The selection of method MyMsg is done at the
runtime and it depends upon the object which is
having their own implementation of MyMsg method.
assigned to the reference of the interface.
Java Program[Test.java]
2. We have created reference inter for the interface in
import java.io.*;
which the method MyMsg is declared.
import java.util.*;
class Class1 implements interface1 3. Then the objects obj1 and obj2 are created for the
{ classes class1 and class2 respectively. When the obj1
private String s; is assigned to the reference inter then the message
public void MyMsg(String s) “Hello User1” will be displayed because the string
{ passed to the method MyMsg is “User1”. Similarly,
System.out.println("Hello "+s); when the obj2 is assigned to the reference inter then
} the message “Hello User2” will be displayed because
} the string passed to the method MyMsg is “User2”.
class Class2 implements interface1
4. Thus using the same interface different
{
implementations can be selected.
private String s;
public void MyMsg(String s) 3.14 Variables and Methods Interfaces
{
System.out.println("Hello "+s); The variables can be assigned with some values within
} the interface. They are implicitly final and static. Even
} if you do not specify the variables as final and static
they are assumed to be final and static.
class Test
{ The members (variables and methods) of interface are
public static void main(String[] args) static and final because -
{ 1) The reason for being static - The members of
interface1 inter;
interface belong to interface only and not object.
Class1 obj1=new Class1();
Class2 obj2=new Class2();
2) The reason for being final - Any implementation
inter=obj1; can change value of fields if they are not defined as
inter.MyMsg("User1"); final. Then these members would become part of
inter=obj2; the implementation. An interface is pure
inter.MyMsg("User2"); specification without any implementation.
}
} 3.15 Extending Interfaces
MSBTE : Winter 16, 17, Summer 15, 16, 17, 18, Marks 8
Step 3 : Execute the program. Interfaces can be extended similar to the classes. That
means we can derive subclasses from the main class using
the keyword extend, similarly we can derive the
subinterfaces from main interfaces by using the keyword
extends.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 18 Inheritance, Interface and Package
Output
Name: Parth
Roll_No: 10
Marks m1= 90.0 m2 = 95.0
MSBTE : Winter 16, Marks 6 The percentage marks: 92.5
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 19 Inheritance, Interface and Package
Output
Name: Parth
Basic Salary: 10000.0
The Gross Salary: 12200.0
} interface Area{
} void display();
class Test
}
{
}
public static void main(String[] args)
{ class Test implements Rectangle.Area
interface1 inter;//interface reference {
inter=new A(); public void display()
inter.MyMsg("User"); {
} System.out.println("Formula for calculating area =
} length*breadth");
}
Step 2 : The output can be obtained as-
public static void main(String args[])
D:\MSBTE_JAVA _Programs> javac interface1.java
{
D:\MSBTE_JAVA _Programs> javac Test.java
Rectangle.Area obj=new Test();//upcasting here
D:\MSBTE_JAVA _Programs> java Test
obj.display();
Hello User
}
Program Explanation : In above program, }
1) We have written a simple interface class named Output
interface1. The method declared in this interface is
MyMsg.
2) Now we have also written a Test class for defining the
method MyMsg.
3) Inside the main method, the interface reference in
variable inter is created. We can access the method of
a class using this interface reference. Note that this
reference variable is initialized by instance of a class
A.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 21 Inheritance, Interface and Package
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 22 Inheritance, Interface and Package
That is the class Math invokes the method max. This method finds the maximum of the two. This class is
present in the package lang.
Every package name be unique. Because the duplicate package names may cause the runtime errors.
According to the naming conventions of packages it is suggested to make use of domain names as prefix to
predefined package names.
Fig. 3.21.1
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 23 Inheritance, Interface and Package
This helps to find the CLASSPATH for the executable file. If there is an hierarchy of packages then it can be
mentioned by names of packages separated by dots. For example
package.my_package.another_package;
Note that one of the class in the java package must be public.
The main advantage of using packages is that we can arrange the classes systematically.
Board Questions
1. What is package ? How to create package ? Explain with suitable example. MSBTE : Winter 15, Marks 6
2. What is package ? How do we create it ? Give the example to create and to access package.
MSBTE : Winter 17, Marks 8
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 24 Inheritance, Interface and Package
In above example, then that variable is accessible by that class only and
o We have created two packages are created namely - its subclass can not access it.
Test and another_Test.
Board Questions
o Inside the package Test there are two classes 1. Write the effect of access specifiers public, private
defined – class1 and class2 and protected in package
o Inside the package another_Test there is only one MSBTE : Summer 15, Marks 4
class defined and i.e. class3. 2. What is package ? State how to create and access
user defined package in Java.
o There are three data fields – a, b and c. The data
MSBTE : Summer 17, Marks 6
field a is declared as public, b is defined as default
3. Which are the ways to access package from
and c is defined as private. another package ? Explain with example.
o The variable a and method fun1() both are MSBTE : Summer 18, Marks 4
accessible from the classes class2 and class3(even
3.23 Import Statement
if it is in another package). This is because they are MSBTE : Summer 16, Marks 4
declared as public.
All the standard classes in Java are stored in named
o The variable b and method fun2() both are packages.
accessible from class2 because class2 lies in the There is no standard class present in Java which is
same package. But they are not accessible from unnamed. But it is always complicated to write the
class3 because class3 is defined in another class name using a long sequence of packages
package. containing dot operator. Hence the import statement is
o The variable c and method fun3() both are not needed.
accessible from any of the class, because they are The import statement can be written at the beginning
declared as private. of the Java program, using the keyword import.
Protected mode is another access specifier which is There are two ways of accessing the classes stored in
used in inheritance. The protected mode allows the core package.
accessing the members to all the classes and subclasses 1. Method 1 : We import the java package class using the
in the same package as well as to the subclasses in keyword import. Suppose we want to use the Data class
other package. But the non subclasses in other package stored in the java.util package then we can write the
can not access the protected members. import statement at the beginning of the program. It is as
The effect of access specifiers for class, subclass or follows -
package is enlisted below -
private Yes - -
2. Method 2 : There are some situations in which we want
protected Yes Yes Yes to make use of several classes stored in a package. Then
we can write it as
public Yes Yes Yes
import java.util.*
For example, if some variable is declared as protected,
Here * means any class in the corresponding package.
then the class itself can access it, its subclass can
Example 3.23.1 : Design a package containing a class which
access it, and any class in the same package can also
defines a method to find area of rectangle. Import it in Java
access it. Similarly if the variable is declared as private application to calculate area of a rectangle.
MSBTE : Summer 16, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 25 Inheritance, Interface and Package
Step 2 : Now create another program outside this In order to avoid unnecessary use of static class members
MyPack folder. This program will invoke the above like Math. and System, we should use static import.
defined class and use the methods defined in above The above code can be changed by using static import,
created Java class. Just note the difference between these two programs -
Java Program[PackageDemo.java]
Java Program[StaticImport.java]
import static java.lang.System.out;
import MyPack.A;
import static java.lang.Math.sqrt;
class PackageDemo Use of static import
class StaticImport
{
{
public static void main(String args[]) throws
public static void main(String args[])
NoClassDefFoundError
{
{
double a=25;
A obj=new A();
double val=sqrt(a);//using sqrt function without specifying
obj.set_val(10,20);
the class name - Math
obj.calculate_area();
out.println("The square root of "+a+" is "+val); //without
}
specifying System class
}
}
Step 3: }
Output Now compile and execute the above program and you
D:\> cd MyPack will get the same output i.e.
D:\MyPack> javac A.java
The square root of 25.0 is 5.0.
D:\MyPack> cd..
D:\> javac PackageDemo.java Note that ambiguous static import is not allowed. That
D:\> java PackageDemo means the two different classes referencing the same
The area is: 200.0
functionality is not allowed.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 26 Inheritance, Interface and Package
UNIT - IV
TM
Technical Publications (4 --An
1) up thrust for knowledge
Java Programming 4-2 Exception Handling and Multithreading
4. Passing the parameters that is not in the valid There is another block defined by the keyword catch
range. which is responsible for handling the exception thrown
5. Converting invalid string to numbers. by the try block.
6. Trying to illegally change the state of thread. As soon as exception occurs it is handled by the catch
7. Trying to access the character which is out of block.
bounds of a string. The catch block is added immediately after the try
Board Question block.
1. State and explain types of errors in Java.
Syntax :
MSBTE : Summer 18, Marks 4
try
4.3 Concept of Exception {
//exception gets generated here
Exception is an unusual condition that can occur in the
}
program. This condition is caused due to run time error catch(Type_of_Exception e)
in the program. {
In Java, whenever the exception occurs then it creates //exception is handled here
an exception object and throws it. }
If the exception object is not caught and handled If any one statement in the try block generates
properly then the interpreter will display an error exception then remaining statements are skipped and
message. And ultimately the program will terminate. the control is then transferred to the catch statement.
Even though the exception occur and if we want to
Example Program
continue the execution of remaining code then it is
class RunErrDemo
necessary to handle the error condition properly by
{
displaying the appropriate messages. This mechanism public static void main(String[] args)
is called the exception handling mechanism. {
In Java Exception handling is done with the help of int a,b,c;
various keywords like try, catch, throw and throws. a=10;
b=0;
Exception occurs because the
4.4 try-catch Statement try
{ element is divided by 0.
MSBTE : Summer 15,18, Winter 15,16 17, Marks 8
c=a/b;
} Exception is handled
catch(ArithmeticException e)
using catch block
{
System.out.println("\n Divide by zero");
}
System.out.println("\n The value of a: "+a);
System.out.println("\n The value of b: "+b);
}
}
Output
Divide by zero
Fig. 4.4.1 Exception handling mechanism
The statements that are likely to cause an exception are The value of a: 10
enclosed within a try block. For these statements the
exception is thrown. The value of b: 0
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-3 Exception Handling and Multithreading
Note that even if the exception occurs at some point, the program does not stop at that point.
Board Questions
1. Define an exception. How it is handled ? MSBTE : Summer 15,Winter 15,16 Marks 4
2. What is exception ? Why the exception occurred in program ? Explain with suitable example.
MSBTE : Winter 17,Marks 8
3. With syntax and example explain try and catch statement. MSBTE : Summer 18, Marks 4
Java Program[NestedtryDemo.java]
class NestedtryDemo
{
public static void main (String[] args)
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int ans = 0;
try
{
ans = a / b;
System.out.println("The result is "+ans);
} Inner try-catch Outer try-catch
catch (ArithmeticException e)
{
System.out.println("Divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect type of data");
}
}
}
Output
D:\>javac NestedtryDemo.java
D:\>java NestedtryDemo 20 10
The result is 2
D:\>java NestedtryDemo 20 0
Divide by zero Inner catch handles the error
}
Let us understand this exception handling mechanism with the help of simple Java program.
Java Program
/* This programs shows the exception handling mechanism using throws
*/
class ExceptionThrows
{
static void fun(int a,int b) throws ArithmeticException
{
int c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Caught exception: "+e);
}
}
Output
Caught exception: java.lang.ArithmeticException: / by zero
Program Explanation:
In above program the method fun is for handling the exception divide by zero. This is an arithmetic exception
hence we write
static void fun(int a,int b) throws ArithmeticException
This method should be of static type. Also note as this method is responsible for handling the exception the
try-catch block should be within fun.
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-5 Exception Handling and Multithreading
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-6 Exception Handling and Multithreading
}
} IOException When an illegal
input/output operation
Output
In catch block: java.lang.ArithmeticException: / by zero is performed then this
Finally block executes on occurrence of exception exception is raised.
if(b==0)
IllegalStateException This exception shows {
that a method has been ArithmeticException ex = new
invoked at an illegal or ArithmeticException("This is arithmetic exception");
ex.initCause( new IOException(" is cause") );
inappropriate time.
throw ex;
That means when Java }
environment or Java else
application is not in an {
System.out.println(a/b);
appropriate state then
}
the method is invoked. }
public static void main(String[] args)
4.10 Chained Exception {
Chained exception is a newly added feature in Java. It try
{
allows to relate one exception with other exception. That
divide(100, 0);
means using one exception we can obtain the cause of }
other exception. catch(ArithmeticException ex) {
System.out.println( "caught : " +ex);
For example - When we perform division operation a/b
System.out.println("actual cause: "+ex.getCause());
and if value of b is 0 then we get divide by zero }
execution. This execution is normally thrown as }
“ArithmeticException”. But actual cause of this }
exception is wrong input value to variable b. That means Output
the cause is actually IOException. caught : java.lang.ArithmeticException: This is arithmetic
exception
The chained exception is used to handle this kind of
actual cause: java.io.IOException: is cause
situation.
There are two important constructors used to support 4.11 Creating Own Exception Subclasses
MSBTE : Summer 15,16, 17, Winter 15, 16, 17, Marks 8
chained exception
1) Throwable(Throwable cause) We can throw our own exceptions using the keyword
throw.
2) Throwable(String str, Throwable cause)
The syntax for throwing out own exception is -
The cause specifies the actual cause of exception. The str
throw new Throwable’s subclass
is a exception description string.
Here the Throwable’s subclass is actually a subclass
There are two important methods used in chained
derived from the Exception class.
exception -
getCause(): this method returns actual cause associated For example -
throw new ArithmeticException();
with current exception.
initCause() this method sets underlying cause (exception)
with invoking exception. Throwable’s subclass
Let us see a simple Java program which illustrates this
Example Program
import java.io.IOException;
concept.
public class ChainedException
Java Program[MyExceptDemo.java]
{
import java.lang.Exception;
public static void divide(int a, int b)
class MyOwnException extends Exception
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-8 Exception Handling and Multithreading
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-9 Exception Handling and Multithreading
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 10 Exception Handling and Multithreading
getName() The name of the thread can be obtained using Implementing Runnable Interface
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 12 Exception Handling and Multithreading
Output }
}
class B extends Thread
{
public void run()
{
System.out.println("Odd Numbers Thread!!!");
try{
for(int i=1;i<=20;i++)
{
if(i%2!=0)
System.out.println(i);
Thread.sleep(500);
}
Program Explanation : }catch(InterruptedException e){}
In above program, we have used interface Runnable. }
}
While using the interface, it is necessary to use
class TwoThreads
implements keyword. {
Inside the main method public static void main(String args[])
{
1. Create the instance of class MyClass.
A t1=new A();
2. This instance is passed as a parameter to Thread t1.start();
class. try {
t1.join();// This is for execution of second thread
3. Using the instance of class Thread invoke the
//only after execution of first thread completely
start method. }catch(InterruptedException e){}
4. The start method in-turn calls the run method B t2=new B();
written in MyClass. t2.start();
}
The run method executes and display the message for }
thread creation.
Output
Example 4.13.1 : Write a program to create two thread one to Even Numbers Thread!!!
print odd number only and other to print even numbers. 2
MSBTE : Winter 17,Marks 4
4
Solution : 6
class A extends Thread 8
{ 10
public void run() 12
{ 14
int n,m=0,flag=0; 16
System.out.println("Even Numbers Thread!!!"); 18
try { 20
for(int i=1;i<=20;i++) Odd Numbers Thread!!!
{ 1
if(i%2==0) 3
System.out.println(i); 5
Thread.sleep(500); 7
} 9
}catch(InterruptedException e){} 11
13
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 13 Exception Handling and Multithreading
}
}
class B extends Thread
{
public void run()
{
System.out.println("\nReverse OrderThread!!!");
try{
for(int i=10;i>=1;i--)// for 100 number change
// 10 by 100 Fig. 4.14.1 Life cycle of thread
{
New state
System.out.print(" "+i);
Thread.sleep(500); When a thread starts its life cycle it enters in the new
} state or a create state.
}catch(InterruptedException e){}
} Runnable state
}
This is a state in which a thread starts executing.
class TwoThreads
{ Waiting state
public static void main(String args[]) Sometimes one thread has to undergo in waiting state
{
because another thread starts executing.
A t1=new A();
t1.start();
try {
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 14 Exception Handling and Multithreading
thread execution can be denoted by sample try…catch Preemption is a situation in which when the currently
block executed thread is suspended temporarily by the highest
priority thread.
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 15 Exception Handling and Multithreading
B: 1
The highest priority thread always preempts the lowest
B: 2 Thread 2 preempts the
priority thread. B: 3 execution of thread 1
Let us see the illustration of thread prioritizing with the B: 4
help of following example - B: 5
-----End of Thread#2-------
Java program[Thread_PR_Prog.java] A: 1
class A extends Thread A: 2
Then Thread 1 continues
{ A: 3
A: 4 its execution
public void run()
{ A: 5
System.out.println("Thread #1");
for(int i=1;i<=5;i++) -----End of Thread#1-------
{
System.out.println("\tA: "+i); Program explanation
} In above program
System.out.println("\n-----End of Thread#1-------");
1) We have created two threads - the Thread#1 and
}
}
Thread#2.
class B extends Thread 2) We assign highest priority to Thread#2.
{
3) In the main function both the threads are started but as
public void run()
{
the Thread#2 has higher priority than the thread#1, the
System.out.println("Thread #2"); Thread#2 preempts the execution of Thread#1. Thus
for(int k=1;k<=5;k++) Thread#2 completes its execution and then Thread#1
{ completes.
System.out.println("\tB: "+k);
} Board Questions
System.out.println("\n-----End of Thread#2-------");
1. Explain thread priority and method to get and set
}
priority values.
}
MSBTE : Summer 15, Marks 4
class Thread_PR_Prog
{ 2. What is thread priority ? How thread priority are
public static void main(String[] args) set and changed ? Explain with example.
{ MSBTE : Summer 16, Marks 8
A obj1=new A(); 3. What is thread priority ? Write default priority
B obj2=new B(); values and methods to change them.
obj1.setPriority(1); MSBTE : Summer 17, Marks 4
obj2.setPriority(10);//highest priority
System.out.println("Strating Thread#1"); 4.17 Synchronization
obj1.start(); MSBTE : Winter 16, Marks 4
System.out.println("Strating Thread#2");
When two or more threads need to access shared
obj2.start();
}
memory, then there is some way to ensure that the
} access to the resource will be by only one thread at a
time. The process of ensuring one access at a time by
Output
Strating Thread#1 one thread is called synchronization. The
Strating Thread#2 Thread 1 and synchronization is the concept which is based on
Thread #1 Thread 2 starts monitor. Monitor is used as mutually exclusive lock or
Thread #2
mutex. When a thread owns this monitor at a time then
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 16 Exception Handling and Multithreading
produces and the consumer thread consumes whatever public static Object obj1 = new Object();
public static Object obj2 = new Object();
is produced.
Both must work in co-ordination to avoid wastage of private static class A extends Thread
CPU cycles. {
public void run()
But there are situations in which the producer has to
{
wait for the consumer to finish consuming of data. synchronized (obj1)
Similarly the consumer may need to wait for the {
producer to produce the data. System.out.println("Thread 1: Holding object1...");
try
In Polling system either consumer will waste many {
CPU cycles when waiting for producer to produce or Thread.sleep(10);
the producer will waste CPU cycles when waiting for }
the consumer to consume the data. catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for
In order to avoid polling there are three in-built object2...");
methods that take part in inter-thread communication -
synchronized (obj2)
notify() If a particular thread is in the sleep mode then
{
that thread can be resumed using the notify System.out.println("Thread 1: Holding
call. object1 and object2...");
}
notifyall() This method resumes all the threads that are in }
suspended state. }
}
wait() The calling thread can be send into a sleep
private static class B extends Thread
mode. {
public void run()
4.19 Deadlock {
Deadlock is a situation in which two or more threads are synchronized (obj2)
{
waiting for object lock which is hold by some another
System.out.println("Thread 2: Holding object2...");
thread. try
For example - Consider thread A is waiting for object {
obj2 which is locked by thread B and thread B is waiting Thread.sleep(10);
}
for object obj1 which is locked by thread A. This situation
catch (InterruptedException e) {}
is described as deadlock. System.out.println("Thread 2: Waiting for
object1...");
synchronized (obj1)
{
System.out.println("Thread 2: Holding object1
and object2...");
Fig. 4.19.1 : Deadlock }
}
Following Java program shows the deadlock situation }
}
Java Program[DeadLockDemo.java]
public static void main(String args[])
public class DeadLockDemo
{
{
A T1 = new A();
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 19 Exception Handling and Multithreading
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 20 Exception Handling and Multithreading
Notes
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-1 Java Applets and Graphics Programming
UNIT - V
TM
Technical Publications (5 --An
1) up thrust for knowledge
Java Programming 5-2 Java Applets and Graphics Programming
3. Display state
Applet enters in the display state when it wants to display
some output. This may happen when applet enters in the
running state. The paint( ) method is for displaying or
drawing the contents on the screen. The syntax is
public void paint(Graphics g)
{
…
}
Fig. 5.2.1 Applet’s life cycle An instance of Graphics class has to be passed to this
When applet begins, the AWT calls following methods function as an argument. In this method various
in sequence - operations such as display of text, circle, line are invoked.
a) init() b) start() c) paint() 4. Idle state
When applet is terminated following method are invoked This is an idle state in which applet becomes idle. The
in sequence. stop( ) method is invoked when we want to stop the
a) stop() b) destroy() applet. When an applet is running if we go to another
1. Initialization state page then this method is invoked. The syntax is
public void stop()
When applet gets loaded it enters in the initialization
{
state. For this purpose the init( ) method is used. In this …
method you can initialize the required variables. This }
method is called only once initially at the execution of the
program. The syntax can be 5. Dead state
public void init() When applet is said to be dead then it is removed from
{ memory. The method destroy( ) is invoked when we
//initialization of variables
want to terminate applet completely and want to remove it
}
from the memory.
In this method various tasks of initialization can be
public void destroy()
performed such as - {
1. Creation of objects needed by applet …
2. Setting up of initial values }
</applet>
</body>
</html>
For embedding the applet in the HTML document the <APPLET> tag is used. The <APPLET> tag supplies
the name of the applet to be loaded. Suppose we want to load the applet FirstAppletprogram in the web
page then the applet tag will be
<APPLET CODE= FirstAppletprogram.class
WIDTH = 500
HEIGHT = 300
</APPLET>
The HTML code tells the web browser to load the compiled code of applet FirstAppletprogram.class. Note
that this class file must be present in the same directory where the web page is stored.
Step 4 : Load html file with some web browser, This will cause to execute your html file. It will look like this -
Note this
URL
We can embed the applet code in Java using comment statements. It is as shown in following illustration.
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-6 Java Applets and Graphics Programming
{ Output
g.drawString("This is my First Applet",50,30);
}
}
In above code we have added applet code at the beginning
of the program.
<applet code="FirstApplet" width=300 height=100>
</applet>
This will help to understand Java that the source program
is an applet with the name FirstApplet.
Step 2 :By this edition you can run your applet program
5.6 Passing Parameter to Applet
merely by Appletviewer command.
MSBTE : Winter 15, 16,17, Summer 15, 17, 18, Marks 8
D:\test>javac FirstApplet.java
D:\test>Appletviewer FirstApplet.java Parameters are passed to applets in NAME=VALUE
pairs in <PARAM> tags between the opening and
And we will get
closing APPLET tags.
There can be any number of <PRAM> tags inside
APPLET tag.
Inside the applet, you read the values passed through
the PARAM tags with the getParameter( ) method of
the Applet class.
The program below demonstrates this idea -
Example 5.6.1 : How can parameters be passed to an applet
? Write an applet to accept user name in the form of parameter
Example 5.5.1 : Define applet. Write a program to create an and print ‘Hello < username >’.
applet to display message MSBTE : Winter 15, Marks 8
“Welcome to java applet”. Solution :
MSBTE : Winter 15, Marks 6, Summer 18, Marks 8
Solution : import java.applet.Applet;
import java.awt.Graphics;
FirstApplet.java /*
/* <applet code="WelcomeParam" width=200 height=200>
This is my First Applet program <param name="Username" value="Parth">
*/ </applet>
import java.awt.*; */
import java.applet.*; public class WelcomeParam extends Applet
/* {
<applet code="FirstApplet" width=300 height=100> String msg="";
</applet> public void init()
*/ {
public class FirstApplet extends Applet msg = getParameter("Username");
{ msg = "Welcome " + msg;
public void paint(Graphics g) }
{ public void paint(Graphics g)
g.drawString("Welcome to Java Applet",50,30); {
} g.drawString(msg,50,50);
} }
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-7 Java Applets and Graphics Programming
Output Output
Step 4 : Open the web browser and type the name of the
html file created in step 1. The output will be -
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-8 Java Applets and Graphics Programming
Board Questions
1. Explain <PARAM> Tag of applet with suitable
example. MSBTE : Summer 15, Marks 6
2. Explain following methods for applet with an
example :
1) Passing parameter to applet
2) Embedding <applet> tags in java code.
MSBTE : Summer 18, Marks 8
Output
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-9 Java Applets and Graphics Programming
Output
Example Program
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="RadioButtonDemo" width=350 height=200>
3) Adding Checkbox to the applet </applet>
*/
The Checkbox class is used to create check boxes. It is public class RadioButtonDemo extends Applet
used to turn an option true or false. Following program {
shows the use of checkbox CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("Male",cbg,false);
Example Program Checkbox cb2=new Checkbox("Female",cbg,true);
import java.awt.*; public void init()
import java.awt.event.*; {
import java.applet.*; add(cb1);
/* add(cb2);
<applet code="CheckBoxDemo" width=350 height=200> }
</applet> }
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 10 Java Applets and Graphics Programming
The AWT contains large number of classes which help o Frame : This is a top-level window with a border
to include various graphical components in the Java and menu bar. It supports the common window
program. These graphical components include text events such as window open, close, activate and
box, buttons, labels, radio buttons, list items and so on. deactivate.
We need to import java.awt package for using these o The co-ordinate system of Java can be represented
components.
by following Fig. 5.8.2.
These classes are arranged in hierarchical manner
which is recognised as AWT hierarchy. (Refer
Fig. 5.8.1)
5.8.2 Lines
Drawing the line is the simplest thing in Java. The syntax is,
void drawLine(int x1,int y1,int x2,int y2);
Where x1 and y1 represents the starting point of the line and x2 and y2 represents the ending point of the line.
Output
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 12 Java Applets and Graphics Programming
Output
5.8.3 Rectangles
In Java we can draw two types of rectangles : Normal
rectangle and the rectangle with round corners. The
syntax of these methods are -
void drawRect(int top,int left,int width,int height)
void drawRoundRect(int top,int left,int width,int height,int
xdimeter,int ydimeter)
For example
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 13 Java Applets and Graphics Programming
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 14 Java Applets and Graphics Programming
Output
5.8.5 Arcs
/*
/*<applet code=smiley.class height=300 <applet code="Polyg" width=310 height=200>
width=300></applet>*/ </applet>
public class smiley extends Applet */
{
public void paint(Graphics g) public class Polyg extends Applet
{ {
g.drawOval(20,40,250,250); public void paint(Graphics g)
g.drawOval(70,100,50,50); {
g.drawOval(180,100,50,50); int xpt[]={50,20,20,20,130};
g.drawArc(100,150,100,100,180,180); int ypt[]={80,30,200,200,30};
}
} int num=5;
g.drawPolygon(xpt,ypt,num);
Output
g.setColor(Color.magenta);
g.fillPolygon(xpt,ypt,num);
g.setColor(Color.black);
g.drawString("Its a polygon Demo",100,100);
}
}
Output
5.8.6 Polygons
Color.blue Color.magenta
Color.cyan Color.orange
Color.darkGray Color.pink
Color.gray Color.red
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 17 Java Applets and Graphics Programming
Output Output
Program Explanation :
In above program,
1) We see one more method related to color and that is
setColor. To set some specific color this method is Example 5.9.2 : Write a applet program to set background
with red colour and fore ground with blue colour.
used. The color name has to be passed as a parameter MSBTE : Winter 17,Marks 4
to this method. Solution :
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 18 Java Applets and Graphics Programming
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 19 Java Applets and Graphics Programming
Output
Output
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 20 Java Applets and Graphics Programming
Notes
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-1 Managing Input, Output Files in Java
UNIT - VI
Definition :
Stream is basically a channel on which the data flow from sender to receiver.
An input object that reads the stream of data from a file is called input stream.
The output object that writes the stream of data to a file is called output stream.
As shown in above Fig. 6.2.1, A file or Console containing some input is given to the Java Program. This
input is read by our Java program with the help of input stream classes.
The output generated by our Java program, is then moved on to Output Stream classes. Using theses
classes we can store the output either in some another file or display it on Console(i.e. on output screen)
There are basically two types of streams used in Java.
Board Question
1. Explain serialization with stream classes. MSBTE : Summer 16, Marks 4
TM
Technical Publications (6 --An
1) up thrust for knowledge
Java Programming 6-2 Managing Input, Output Files in Java
Board Question
1. Explain byte stream class in detail. MSBTE : Summer 18, Marks 4
Various Reader and Writer classes are – 6.5 Using File Class
Various classes that work on the Input/Output system
FileReader FileWriter
makes use of the Java package java.io, however the
PipeReader PipeWriter File class works on file and file system.
That means the File class does not contain methods for
FilterReader FilterWriter reading and writing the file contents, but it describes
the properties of file itself.
BufferedReader BufferedWriter
A File object is used to manipulate the information
DataReader DataWriter present in the disk file. Files are useful for storing the
persistent and shared information.
LineNumberReader LineNumberWriter
Various commonly used operations using File class are –
PushbackReader PushbackWriter 1) File creation.
2) Opening a file.
ByteArrayReader ByteArrayWriter
3) Closing a file.
SequenceReader SequenceWriter 4) Getting name of file.
5) Renaming a file.
StringBufferReader StringBufferWriter
6) Checking whether the file is writable.
7) Checking whether the file is readable.
2. Draw the hierarchy of writer stream classes and InterruptedIOException If I/O operation is interrupted ,
hierarchy of Readerstream classes. then this exception is used to
MSBTE : Winter 16, Marks 4 handle the situation.
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-4 Managing Input, Output Files in Java
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-6 Managing Input, Output Files in Java
while((i=fr.read())!=-1)
{
ch++;
}
System.out.println("Total number of characters: "+ch);
fr.close();
}
}
Output
Total number of characters: 14
Write Operations
For performing write operation using byte stream classes we use an important class i.e.
FileOutputStream.
Declaration Syntax : The FileOutputStream class can be declared as follows -
public class FileOutputStream extends OutputStream
Useful Methods : The most commonly used methods of FileOutputStream class are as shown by following
table -
Method Purpose
void write( byte[] array) The array.length bytes can be written to the file output stream.
void write(byte[] array, int The len bytes can be written from byte array at the location
offset, int len) denoted by offset to the file output stream.
void write(int b) It is used to write the specified bytes to file output stream.
Let us now discuss how to write Java program using byte stream classes for Write operation
Output
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-8 Managing Input, Output Files in Java
J Output
Following data is read from file...
Program Explanation : In above program,
Java Program is fun!!!
1 : Import java.io.FileInputStream; at the beginning of
Example 6.9.1 : Write a program to copy contents of one file
your Java program. to another. Using byte stream classes.
MSBTE : Winter 17, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-9 Managing Input, Output Files in Java
Output
Writing some data to the file ...
Reading some data from the file ...
301
A
true
123.45
2) Then first of all we have prepared filestream object 7) Finally filestream object and datastream objects are
and datastream objects for writing primitive data type closed.
values to the Primfile.txt.
Board Questions
3) Then using writeType() methods (like writeInt,
1. Write any two methods of file and file input stream
writeChar and so on) we can write data to the file. class each.
4) The stream objects are then closed. MSBTE : Summer 15, Winter 15, Marks 4
5) We initialize the filestream object and datastream 2. Write any four methods of file class with their use.
MSBTE : Summer 17, Marks 4
objects for reading primitive data type values from
3. Write any four methods of file input stream class
Primfile.txt
give their syntax.
6) Then using readType() methods(like readInt, readChar MSBTE : Winter 17, Marks 4
and so on) we can reads primitive data type data from
the file.
TM
Technical Publications - An up thrust for knowledge
Java Programming L-1 Java Programming Laboratory
Java Programming
LABORATORY
Solution :
Step 1 : For running Java we require JDK i.e. Java Development Kit. It can be downloaded from the website
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Step 2 : Click the Download button Under "Java Platform, Standard Edition" ⇒ "Java SE 10.0.{x}", where {x}
denotes update number.
Step 4 : Choose JDK for your operating system i.e. Windows 32 bit or 64 bit. And download installer. Run the
installer.
Step 5 : Accept the defaults and proceed by clicking the Next button.
This installer installs both the JDK and JRE.
By default :
JDK is installed in directory "C:\Program Files\Java\jdk-10.0.{x}", where {x} denotes the upgrade
number; and
JRE is installed in "C:\Program Files\Java\jre-10.0.{x}".
Step 5 : Thus now we have Java installed on our PC. The last important task which we have to do is: setting up of
environmental variables. This will help us to run our java programs. For setting the environmental variables
just go to the control panel. You find the System folder over there. Click over there to set the system
properties. Following screen may appear by this
TM
Technical Publications
(L- -An1)up thrust for knowledge
Java Programming L-2 Java Programming Laboratory
Click on Environment Variables tab in order to set the environment variables. Under the “System Variables”
(the bottom Pane), Scroll down to select “Path” => Click “Edit..” Thus we should have –
Variable name : PATH
Variable value : c:\Program Files\Java\jdk-10.0.{x}\bin;
We can set the path variable by mentioning the directory C:\Program Files\jdk10.0.X\bin. Note that in the
subdirectory bin of our jdk directory the executable file of java is downloaded. Hence the bin directory has to
be mentioned in the path. Click OK to save these settings. Do not delete any other entries if present under the
“path” variable. Separate our Java entry by semicolon.
Many applications require the environment variable JAVA_HOME to be set to the installed JDK directory.
To set the JAVA_HOME environment variable :
(1) First find where your JDK is installed. By default it is installed at “C:\Program Files\Java.
(2) Check if JAVA_HOME is already set. Start a Command Prompt and issue:
SET JAVA_HOME
If you get a message "Environment variable JAVA_HOME not defined", proceed to the next step.
(3) To set the environment variable JAVA_HOME in Windows 10/8/7: Launch "Control Panel" ⇒ (Optional)
System and Security ⇒ System ⇒ Advanced system settings ⇒ Switch to "Advanced" tab ⇒ Environment
Variables ⇒ System Variables (the bottom pane) ⇒ "New"
TM
Technical Publications - An up thrust for knowledge
Java Programming L-3 Java Programming Laboratory
Step 6 : We can verify the installation of Java using Command prompt. For that - Launch a Command Prompt
shell via one of the following means :
Click "Search" button ⇒ Enter "cmd" ⇒ Choose "Command Prompt", or
right-click "Start" button ⇒ run... ⇒ enter "cmd", or
The command prompt window will appear , go to the command-prompt and type javac over there.
Thus we have got the fully functioning java software ready to run our java programs.
Step 3 : Create a shortcut for eclipse.exe on your Desktop. Click on this eclipse.exe to launch Eclipse.
Step 4 : The workspace launcher will appear. Click OK and proceed. Eventually Welcome tab will appear. You
can terminate this table by clicking X on top right corner.
Step 5 : Click Window and click Preferences in its pull down menu. The following screenshot illustrates –
Step 6 : Disclose Java by clicking the + in front of Java or double-clicking Java (after the +); the + changes to a -
Disclose Installed JREs similarly. The Preferences pop-up window should appear as follows
TM
Technical Publications - An up thrust for knowledge
Java Programming L-5 Java Programming Laboratory
Solution : (a) Refer section 2.1 (1) (b) Refer section 3.4.
Example 11 : Develop a program for implementation of different functions of String. Part I
TM
Technical Publications - An up thrust for knowledge
Java Programming L-6 Java Programming Laboratory
Example 16 Develop a program for implementation of Wrapper Class to convert object into primitive.
Solution : Refer example 2.14.1
Example 17 Develop program which implements the concept of overriding.
Solution : Refer section 3.5
Example 18 Develop a program for implementation of Single and Multilevel inheritances.
Solution : Refer examples 3.2.1, and 3.2.4
Example 19 Develop a program for implementation of multiple inheritance.
Solution : Refer example 3.15.2
Example 20 Develop a program to import different classes in a package.
Solution :
import java.awt.*;
import java.applet.*;
/*<applet code="Shape.class" height=400 width=500>
</applet>
*/
public class Shape extends Applet
{
public void paint(Graphics g)
{
//drawing Cylinder
g.drawLine(20,20,20,100);
g.drawOval(20,0,90,50);
g.drawLine(110,20,110,100);
g.drawOval(20,80,90,50);
g.drawString("Cylinder",30,160);
//drawing cone
g.drawOval(150,90,90,50);
g.drawLine(195,10,150,110);
g.drawLine(195,10,240,110);
g.drawString("Cone",180,160);
//drawing Cube
g.drawRect(300,10,100,100);
g.drawRect(320,30,100,100);
g.drawLine(300,10,320,30);//slanting top left
g.drawLine(400,10,420,30);//slanting top right
g.drawLine(300,110,320,130);//slanting bottom left
g.drawLine(400,110,420,130);//slanting bottom right
g.drawString("Cube",340,160);
//Square Inside Circle
g.drawOval(100,200,100,100);
g.drawRect(115,215,70,70);
g.drawString("Square Inside Circle",90,320);
//Circle Inside Square
g.drawRect(300,200,100,100);
g.drawOval(300,200,100,100);
g.drawString("Circle Inside Square",290,320);
}
}
TM
Technical Publications - An up thrust for knowledge
Java Programming L-8 Java Programming Laboratory
TM
Technical Publications - An up thrust for knowledge
Java Programming M-1 Solved Model Question Paper
TM
Technical Publications - An up thrust for knowledge
Java Programming M-2 Solved Model Question Paper
(c) How to add applet to HTML file. Explain it with suitable example. (Refer section 5.5.1)
Q.6 Attempt any TWO of the Following : [Marks 12]
(M - 1)
(a) Explain the different methods of passing arguments to the function with supporting Java programs
(Refer section 2.4)
(b) Write a Java program to display following number pattern. (Refer example 1.8.10)
1
12
123
1234
12345
(c) Explain the concept of creating own exception subclass with suitable example. (Refer section 4.11)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-1 Solved Board Question Papers
Summer 2015
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (21415)
3 Hours/100 Marks
Instructions :
(1) All questions are compulsory.
(2) Answer each next main question on a new page.
(3) Illustrate your answers with neat sketches wherever necessary.
(4) Figures to the right indicate full marks.
(5) Assume suitable data, if necessary.
(6) Preferably, write the answers in sequential order.
1. A) Attempt any three of the following : (3×4=12)
a) What is JVM ? What is byte code ? (Refer section 1.2)
b) Write any two methods of file and file input stream class each. (Refer section 6.9)
c) ‘? :’ What this operator is called ? Explain with suitable example. (Refer section 1.7.5)
d) Define an exception. How it is handled ? (Refer section 4.4)
B) Attempt any one of the following : (1×6=6)
a) Define a class ‘employee’ with data members empid, name and salary. Accept data for five objects
using array of objects and print it. (Refer example 2.11.1)
b) Explain with example how to achieve multiple inheritance with interface. (Refer example 3.15.1)
2. Attempt any two of the following : (2×8=16)
a) Define wrapper class. Give the following wrapper class methods with syntax and use :
1) To convert integer number to string.
2) To convert numeric string to integer number.
3) To convert object numbers to primitive numbers using typevalue ( ) method. (Refer example 2.14.1)
b) Write syntax and example of
1) drawString ( ) 2) drawRect ( ) ;
3) drawOval ( ) 4) drawArc ( ) (Refer section 5.10)
c) What is package ? State any four system packages along with their use ? How to add class to a user
defined package ? (Refer sections 3.18, 3.19 and 3.24)
3. Attempt any four : 16
a) Differentiate vector and array with any 4 points. (Refer section 2.13)
b) Write a program to accept a number as command line argument and print the number is even or odd.
(Refer example 2.6.1)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-2 Solved Board Question Papers
c) Write a program to copy contents of one file to another file using character stream class.
(Refer example 6.8.1)
d) State the use of final keyword w.r.t. a method and the variable with suitable example.
(Refer section 3.7) (S - 1)
d) Write the effect of access specifiers public, private and protected in package. (Refer section 3.22)
e) What are stream classes ? List any two input stream classes from character stream. (Refer section 6.4)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-3 Solved Board Question Papers
Winter 2015
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (15116)
Summer 2016
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (15162)
b) Describe with example how to achieve multiple inheritance with suitable program. (Refer section 3.15)
c) Write a simple applet program which display three concentric circle. (Refer example 5.8.3)
3. Attempt any four of following : (4×4=16)
a) Define constructor. Explain parameterized constructor with example. (Refer section 2.2)
b) Write a program to check whether an entered number is prime or not. (Refer example 1.8.6)
c) Explain serialization with stream classes. (Refer section 6.2)
d) State syntax and explain it with parameters for :
i) drawRect ( ) ii) drawOral ( ) (Refer section 5.8.4)
e) Describe use of ‘super’ and ‘this’ with respect to inheritance. (Refer sections 2.5 and 3.8)
4. A) Attempt any three of following. (3×4=12)
a) Explain break and continue statements with example. (Refer section 1.8)
b) Describe use of ‘throws’ with suitable example. (Refer section 4.6)
c) State syntax and describe working of ‘for each’ version of for loop with one example.
(Refer section 1.8)
d) State syntax and describe any two methods of map class. (Not in new syllabus)
B) Attempt any one of following. (1×6=6)
a) Write method to set font of a text and describe its parameters. (Refer section 5.10)
b) Describe final method and final variable with respect to inheritance. (Refer section 3.7)
5. Attempt any two of following. (2×8=16)
a) What is thread priority ? How thread priority are set and changed ? Explain with example.
(Refer section 4.16)
b) Write a program to input name and age of person and throws user defined exception, if entered age is
negative. (Refer example 4.11.2)
c) Explain <applet> tag with its major attributes only. State purpose of get Available Font Family N ame
( ) method of graphics environment class. (Refer sections 5.2 and 5.10)
6. Attempt any four of the following. (4×4=16)
a) Define a class Item having datamember code and price. Accept data for one object and display it.
(Refer example 1.5.1)
b) What is use of Array list class ? State any two methods with their use from Array List.
(Not in new syllabus)
c) Design an Applet program which displays a rectangle filled with red color and message as “Hello
Third year Students” in blue color. (Refer example 5.9.1)
d) Design a package containing a class which defines a method to find area of rectangle. Import it in Java
application to calculate area of a rectangle. (Refer example 3.23.1)
e) Define a class having one 3-digit number as a data member. Initialize and display reverse of that
number. (Refer example 1.8.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-6 Solved Board Question Papers
Winter 2016
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (16117)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-8 Solved Board Question Papers
Summer 2017
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (16172)
(b) What is use of ArrayList class ? State any two methods with their use from ArrayList.
(Not in new syllabus)
(c) Design an applet which accepts username as a parameter for html page and display number of
characters from it. (Refer example 5.6.3)
(d) List any four built-in packages from Java API along with their use. (Refer section 3.19)
(e) Write a program to accept two numbers as command line arguments and print the addition of those
numbers. (Refer example 2.6.2)
Winter 2017
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (11718)
(b) What is the multiple inheritance ? Write a java program to implement multiple inheritance.
(Refer section 3.15)
2. Attempt any TWO of the following : 2 × 8 = 16
(a) Define a class person with data member as Aadharno, name, Panno implement concept of constructor
overloading. Accept data for 5 object and print it. (Refer example 3.4.1)
(b) What is package ? How do we create it ? Give the example to create and to access package.
(Refer section 3.21)
(c) Give the syntax of following methods of graphics class. Explain their use with suitable program :
(i) drawRoundReel() (ii) drawPolygon()
(iii) drawOval() (iv) drawString( ) (Refer section 5.8)
3. Attempt any FOUR of the following : 4 × 4 = 16
(a) Describe following string class method with example :
(i) compareTo( ) (ii) equalsIgnoreCase( ) (Refer section 2.12)
(b) Write a program to copy contents of one file to another. Using byte stream classes.
(Refer example 6.9.1)
(c) Explain method overriding with suitable example. (Refer section 3.5)
(d) Enlist any four built in packages in java API with atleast two class name from each package.
(Refer section 3.19.1)
(e) Write a program to check whether given number is prime or not. (Refer example 1.8.6)
4. (A) Attempt any THREE of the following : 3 × 4 = 12
(a) Write a program to print the following output : (Refer example 1.8.1)
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
(b) Illustrate with example the use of switch case statement. (Refer section 1.8.5)
(c) Write a program to create two thread one to print odd number only and other to print even numbers.
(Refer example 4.13.1)
(d) What is the use of try catch and finally statement give example. (Refer section 4.8)
(B) Attempt any ON E of the following : 1×6=6
(a) What is importance of super and this keyword in inheritance ? Illustrate with suitable example.
(b) Write a single program to implement inheritance and polymorphism in java. (Refer section 3.6)
5. Attempt any TWO of the following : 2 × 8 = 16
(a) What is exception ? Why the exception occurred in program ? Explain with suitable example.
(Refer section 4.4)
(b) Write a program to define two thread one to print from 1 to 100 and other to print from 100 to 1. First
thread transfer control to second thread after delay of 500 ms. (Refer example 4.13.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 11 Solved Board Question Papers
(c) How to pass parameter to an applet ? Write an applet to accept Account N o and balance in form of
parameter and print message “low balance” if the balance is less than 500. (Refer example 5.6.4)
6. Attempt any FOUR of the following : 4 × 4 = 16
(a) What is the use of wrapper classes in Java ? Explain float wrapper with its methods.
(Refer section 2.14)
(b) Write a program to accept number from command line and print square root of the number.
(Refer example 2.6.3)
(c) Write any four methods of File Input stream class give their syntax. (Refer section 6.9)
(d) Write a applet program to set background with red colour and fore ground with blue colour.
(Refer example 5.9.2)
(e) Describe access control specifiers with example. (Refer section 2.10)
Summer 2018
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (21718)
(b) Which are the ways to access package from another package ? Explain with example.
(Refer section 3.22)
(c) Define a class and object. Write syntax to create class and object with an example.
(Refer section 1.5)
(d) With proper syntax and example explain following thread methods :
(1) wait( ) (2) sleep( ) (3) resume( ) (4) notify( ) (Refer section 4.14)
(e) What is type casting ? Explain its types with proper syntax and example. (Refer section 1.6.6)
Q.4 (a) Attempt any THREE of the following : 12
(a) State & explain scope of variable with an example. (Refer section 1.6.5)
(b) With syntax and example explain try & catch statement. (Refer section 4.4)
(c) Explain applet life cycle with suitable diagram. (Refer section 5.2)
(d) Explain byte stream class in detail. (Refer section 6.3)
(B) Attempt any ON E of the following : 6
(a) Write a java program to implement following functions of string :
(1) Calculate length of string
(2) Compare between strings
(3) Concatenating strings (Refer section 2.12)
(b) Write a java program to extend interface assuming suitable data.(Refer section 3.15)
5. Attempt any TWO of the following : 16
(a) Write a java program to implement runnable interface with example. (Refer section 4.13)
(b) Write a java program to display all the odd numbers between 1 to 30 using for loop & if statement.
(Refer example 1.8.8)
(c) Explain following methods for applet with an example :
(1) Passing Parameter to applet (Refer section 5.6)
(2) Embedding <applet> tags in java code. (Refer section 5.3)
6. Attempt any FOUR of the following : 16
(a) Explain following bitwise operator with an example :
(1) left shift operator
(2) write shift operator (Refer section 1.7.6)
(b) State & explain types of errors in Java. (Refer section 4.2)
(c) Enlist types of constructor. Explain any two with example. (Refer section 2.2)
(d) How to add new class to a package ? Explain with an example. (Refer section 3.24)
(e) Explain Array list & Iterator methods of collections with an example. (Not in new syllabus)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 13 Solved Board Question Papers
Summer 2019
Solved Paper
Java Programming
S.Y. Diploma Semester - IV 21819
(Computer Engg. Group & Information Technology) (CO/CM/IF/CW)
3 Hours / 70 Marks
Instructions :
1) All questions are compulsory.
2) Answer each next main question on a new page.
3) Figures to the right indicate full marks.
4) Assume suitable data, if necessary.
5) Use of Non-programmable Electronic Pocket Calculator is permissible.
6) Mobile Phone, Pager and any other Electronic Communication devices are not permissible in
Examination Hall.
1. Attempt any FIVE of the following : [10]
a) List any eight features of Java . \(Refer section 1.1)
b) State use of finalize( ) method with its syntax. (Refer section 2.8)
c) N ame the wrapper class methods for the following : (Refer section 2.14)
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
d) List the types of inheritances in Java. (Refer section 3.2)
e) Write the syntax of try-catch-finally blocks. (Refer section 4.4)
f) Give the syntax of < param > tag to pass parameters to an applet. (Refer section 5.6)
g) Define stream class. List its types. (Refer section 6.2)
2. Attempt any THREE of the following : [12]
a) Explain the concept of platform independence and portability with respect to Java language.
(Refer section 1.1(3))
b) Explain the types of constructors in Java with suitable example. (Refer section 2.2)
c) Explain the two ways of creating threads in Java. (Refer section 4.13)
d) Distinguish between input stream class and output stream class. (Refer section 6.3)
3. Attempt any THREE of the following : [12]
a) Define a class student with int id and string name as data members and a method void SetData ( ).
Accept and display the data for five students.
Ans. :
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class Student
TM
Technical Publications(S -- An
13)up thrust for knowledge
Java Programming S - 14 Solved Board Question Papers
{
int id;
String name;
public void setData()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter id: ");
id=in.nextInt();
System.out.println("Enter name: ");
name=in.next();
}
public void display()
{
System.out.println(id+"\t\t"+name);
}
}
class MyClass
{
public static void main(String args[])
{
Student S[]=new Student[5];
int i;
for(i=0;i<5;i++)
{
S[i]=new Student();
S[i].setData();
}
System.out.println("Data For Five Students is...");
System.out.println("ID \t\t Name ");
for(i=0;i<5;i++)
S[i].display();
}
}
Output
Enter id:
10
Enter name:
AAA
Enter id:
20
Enter name:
BBB
Enter id:
30
Enter name:
CCC
Enter id:
40
Enter name:
DDD
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 15 Solved Board Question Papers
Enter id:
50
Enter name:
EEE
Data For Five Students is...
ID Name
10 AAA
20 BBB
30 CCC
40 DDD
50 EEE
b) Explain dynamic method dispatch in Java with suitable example. (Refer section 3.6)
c) Describe the use of following methods : (i) Drawoval( ) (ii) getFont( ) (iii) drawRect( )
(iv) getFamily ( )
Ans. :
Method Purpose
d) Write a program to count number of words from a text file using stream classes.
Ans. :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
3. The overloaded functions may have In the method overriding all the
different return types. methods will have same return type.
d) Differentiate between Java Applet and Java Application ( any four points) (Refer section 5.1)
e) Write a program to copy content of one file to another file. (Refer example 6.9.1)
5. Attempt any TWO of the following : [12]
a) Describe the use of any methods of vector class with their syntax. (Refer section 2.13)
b) Explain the concept of dynamic method dispatch with suitable example. (Refer section 3.6)
c) Write a program to create two threads. One thread will display the numbers from 1 to 50 (ascending
order) and other thread will display numbers from 50 to 1 (descending order). (Refer example 4.13.2)
6. Attempt any TWO of the following : [12]
a) Explain the command line arguments with suitable example. (Refer section 2.6)
b) Write a program to input name and salary of employee and throw user defined exception if entered
salary is negative.
Ans. :
import java.lang.Exception;
import java.util.Scanner;
class SalException extends Exception
{
SalException(String msg)
{
super(msg);
}
}
class SalaryExceptionDemo
{
public static void main (String args [])
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 17 Solved Board Question Papers
{
Scanner in=new Scanner(System.in);
System.out.print("Enter name: ");
String name=in.next();
System.out.print("Enter salary: ");
int salary=in.nextInt();
try
{
if(salary<0)
throw new SalException("Negative Salary!!!");
else
System.out.println("Correct Salary");
}
catch (SalException e)
{
System.out.println (e.getMessage());
}
}
}
Output
Enter name: aaa
Enter salary: -100
Negative Salary!!!
c) Describe the applet life cycle in detail. (Refer section 5.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 18 Solved Board Question Papers
N otes
TM
Technical Publications - An up thrust for knowledge
Books available @
MUMBAI NASHIK
Student Agencies Pvt. Ltd. Rahul Book Centre
Ph. - 022 - 40496161 / 31 Ph. - 0253 - 27424287
Vidyarthi Sales Agencies Maharashtra Pustak Bhandar
Ph. - 022 - 23829330 Ph. - 0253 - 2317506
022 - 23851416 / 23867279 New India Book House
Bharat Sales Ph. - 9623123458
Ph. - 022 - 23821307 / 7580 Anmol Pustakalaya
Ph. - 9822306289
AHMEDNAGAR Anmol Books
Ph. - 0253 - 2505501
Shripad Granth Bhandar
Ph. - 9922664979 Om Pustakalaya
Ph. - 9422246809
SANGAMNER Pragati Books & Stationers
Ph. - 7721014040
Amrut Book Stall
Ph. - 9850663354 New Om Stationers
& General Stores
NARAYANGAON Ph. - 0253 - 2378874
Shri Ganesh Book Depot
Sunil General Stores
Ph. - 9890335806
Ph. - 9850725770
Eakveera Books
KOPARGAON Ph. - 9422754746
KARAD JALGAON
Archana Bazar Parvati Traders
Ph. - 7588065287 Ph. - 9422277738
(i)
R
(ii)
R