JPR CH2 Classes Objects Methods
JPR CH2 Classes Objects Methods
output:
Vijay T. Patil
1
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
C
C++
VB
Java
10
Vijay T. Patil
2
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
JVM runs the garbage collector (gc) when it finds time. Garbage collector will be run
periodically but you cannot define when it should be called.
We cannot even predict when this method will be executed. It will get executed when the
garbage collector, which runs on its own, picks up the object.
Example:
public class A
{
int p, q;
A()
{
p = 10;
p = 20;
}
}
class Test
{
public static void main(String args[])
{
A a1= new A();
A a2= new A();
a1=a2; // it deallocates the memory of object a1
}
}
Public: Public Specifiers achieves the highest classes are in the same package or in another
level of accessibility. Classes, methods, and package.
fields declared as public can be accessed from Example: public int number;
any class in the Java program, whether these Public void sum() {-------------}
Vijay T. Patil
3
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Explain use of following methods: i) indexOf() ii) charAt() iii) substring() iv) replace()
Vijay T. Patil
4
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Describe following string class method with example: (i) length() (ii) equals() (iii) charAt() (iv)
compareTo()
Q. Explain substring(), concat(), replace(), trim() method of class string.
The [Link] class provides a lot of methods to work on string. By the help of these methods,
we can perform operations on string such as trimming, concatenating, converting, comparing,
replacing strings etc.
toLowerCase():Converts all of the characters in this String to lower case.
Syntax: [Link]()
Example: String s="Sachin";
[Link]([Link]());
Output: sachin
trim():Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: [Link]()
Example:
String s=" Sachin ";
[Link]([Link]());
Output:Sachin
replace():Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Syntax: [Link](‘x’,’y’)
Example:
String s1="Java is a programming language. Java is a platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences of "Java" to "Kava"
[Link](s2);
Output: Kava is a programming language. Kava is a platform.
equals():The String equals() method compares the original content of the string. It compares values
of string for equality.
Syntax: [Link](s2)
Example:
String s1="Sachin";
String s2="Sachin";
String s3="Saurav"
[Link]([Link](s2)); //true
Vijay T. Patil
5
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]([Link](s3)); //false
Output:
True
False
compareTo(): The String compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 : positive value
s1 < s2 : negative value
Syntax: [Link](s2)
Example:
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2)); //0
[Link]([Link](s3)); //1(because s1>s3)
[Link]([Link](s1)); //-1(because s3 < s1 )
concat(): string concatenation forms a new string that is the combination of multiple strings.
Syntax: [Link](s2)
Example:
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);
Output: Sachin Tendulkar
Substring(): A part of string is called substring. In other words, substring is a subset of another string.
Syntax: [Link](n)
Example:
String s="Sachin Tendulkar";
[Link]([Link](6));
Output: Tendulkar
Vijay T. Patil
6
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
indexOf():Gives the position of the first occurrence of ‘x’ in the string s1.
Syntax: [Link](‘x’)
Example:
String s1=”sachin”;
[Link](‘a’);
Output: 1
[Link](‘x’,n): Gives the position of ‘x’ that occurs after nth position in the string s1.
Example:
String s1=”sanjay”; [Link](‘a’,2);
Output: 4
valueOf():The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.
Syntax: [Link](p)
Example:
int a=10;
String s=[Link](a);
[Link](s+10);
Output: 1010
endsWith():This method tests if this string ends with the specified suffix.
Syntax: endsWith(String suffix)
Example:
String Str = new String("This is really not immutable!!");
boolean retVal;
retVal = [Link]( "immutable!!" );
[Link]("Returned Value = " + retVal );
retVal = [Link]( "immu" );
[Link]("Returned Value = " + retVal );
Output:
Returned Value = true
Returned Value = false
startsWith(): This method has two variants and tests if a string starts with the specified prefix
beginning a specified index or by default at the beginning.
Syntax: startsWith(String prefix) or startsWith(String prefix, int toffset)
Example:
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]("Welcome") );
[Link]("Return Value :" );
[Link]([Link]("Tutorials") );
Output:
Return Value : true
Return Value : false
Vijay T. Patil
7
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
StringBuffer Class Methods
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.
Append():The append() method concatenates the given argument with this string.
Syntax: [Link](s2)
Example:
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java"); //now original string is changed
[Link](sb); //output: Hello Java
Insert():The insert() method inserts the given string with this string at the given position.
Syntax: [Link](n,s2)
Example:
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java"); //now original string is changed
[Link](sb); //prints HJavaello
Replace():The replace() method replaces the given string from the specified beginIndex and
endIndex.
Syntax: replace(int start, int end, String str)
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb); //prints HJavalo
delete():The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
Syntax: delete(int start, int end)
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
reverse(): The reverse() method of StringBuilder class reverses the current string.
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);
Output: olleH
deleteCharAt():This is the deleteCharAt() function which is used to delete the specific character from
the buffered string by mentioning that's position in the string.
StringBuffer s1 = new StringBuffer("vijay");
[Link](2);
Output: viay
Vijay T. Patil
8
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
setLength(): This method sets the length of the character sequence. Sets the length of the string s1
to n. if n<[Link]() s1 is truncated. If n>[Link]() zeros are added to s1.
Syntax: [Link](n)
Example:
StringBuffer sb = new StringBuffer("Java Programming");
[Link](sb + "\nLength = " + [Link]()); // Java Programming Length = 16
[Link](4);
[Link](sb + "\nLength = " + [Link]()); // Java Length = 4
Array Vector
An array is a structure that holds multiple values The Vector is similar to array holds multiple
of the same type. objects and like an array; it contains components
that can be accessed using an integer index.
An array is a homogeneous data type where it Vectors are heterogeneous. You can have
can hold only objects of one data type. objects of different data types inside a Vector.
After creation, an array is a fixed-length The size of a Vector can grow or shrink as
structure. needed to accommodate adding and removing
items after the Vector has been created.
Array can store primitive type data element. Vector are store non-primitive type data
element.
Array is unsynchronized i.e. automatically Vector is synchronized i.e. when the size will be
increase the size when the initialized size will be exceeding at the time; vector size will increase
exceed. double of initial size.
Declaration of an array : Declaration of Vector:
int arr[] = new int [10]; Vector list = new Vector(3);
Array is the static memory allocation. Vector is the dynamic memory allocation.
Array allocates the memory for the fixed size ,in Vector allocates the memory dynamically means
array there is wastage of memory. according to the requirement no wastage of
memory.
No methods are provided for adding and Vector provides methods for adding and
removing elements. removing elements.
In array wrapper classes are not used. Wrapper classes are used in vector.
Array is not a class. Vector is a class.
Q. Write methods from wrapper class to: (i) convert a string to primitive integer (II) valueOf().
Q. What are the applications of wrapper classes? Explain integer wrapper class.
Q. List various wrapper classes. Give any four methods of Integer wrapper class.
Q. What are wrapper classes? Give the following wrapper class methods with syntax and use. (a)
To convert integer number to string (b) To convert numeric string to integer number.
Q. 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.
Vectors cannot handle primitive data types like int, float, long, char and double. Primitive data types
may be converted into object types by using the wrapper classes.
The wrapper classes for numeric primitives have the capability to convert any valid number in string
format into its corresponding primitive object. For example “10" can be converted into an Integer by
using: Integer intVal = new Integer("10");
Simple data types and their corresponding wrapper class types are as follows:
Simple type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Vijay T. Patil
10
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Converting primitive numbers to object numbers using constructor methods
Constructor calling Conversion action
Integer IntVal = new Integer(i); Primitive integer to Integer objects.
Float floatVal = new Float(f); Primitive float to Float object.
Double DoubleVal = new Double(d); Primitive double to Double object.
Long LongVal = new Long(l); Primitive long to Long object.
Note: i, f, d, and l are primitive data values denoting int, float, double and long data types. They may
be constants or variables.
Converting String objects to numeric objects using the static method ValueOf()
Method calling Conversion action
DoubleVal = [Link](str); Converts string to Double object.
FloatVal = [Link](str); Converts string to Float object.
IntVal = [Link](str); Converts string to Integer object.
LongVal = [Link](str); Converts string to Long object.
Vijay T. Patil
11
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Describe use of “super” and “this” and “final” keyword with respect to inheritance with
example.
When we create super class that keeps the details of its implementation to itself (making it private).
Sometime the variable and methods of super class are private, so they will be available to subclass
but subclass cannot access it. In such cases there would be no way for a subclass to directly access
these variables on its own. Whenever a subclass needs a reference to it immediate super class, it can
do so by use of the keyword super.
Super have two general forms:
The first calls the super class’s constructor.
The second is used to access a member (variable or method) of the super class that has been
declared as private
Example use of super() class
class A { int i; }
// Create a subclass by extending class A.
class B extends A
{ int i; // this i hides the i in A
B(int a, int b)
{ super.i = a; // i in A
i = b; // i in B
}
void show()
{
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
Vijay T. Patil
12
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
[Link]();
}
}
Vijay T. Patil
13
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Final variable: the value of a final variable cannot be changed. final variable behaves like class
variables and they do not take any space on individual objects of the class.
Example of declaring final variable: final int size = 100;
Vijay T. Patil
14
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Vijay T. Patil
16
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class B extends A
{
void show()
{
[Link]("in show of B");
}
}
class C extends B
{
void show()
{
[Link]("in show of C");
}
}
class DynaMethod
{
public static void main(String args[])
{
A a = new A(); // object of class A
B b = new B(); // object of class B
C c = new C(); // object of class C
A r; // obtain a reference of type A
r = a; //r refer to object of A
[Link](); // call show() of A
r = b; //r refer to object of B
[Link](); // call show() of B
r = c; //r refer to object of C
[Link](); // call show() of C
}
}
Output:
in show of A
in show of B
in show of C
Reference of class A stores the reference of class A, class B and class C alternatively. Every call to
show() method would result in execution of show() method of that class whose reference is
currently stored by a reference of class A.
Vijay T. Patil
17
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Program for static variables
class s
{
int a,b;
static int c;
}
class statictest
{
public static void main(String args[])
{
s ob1=new s();
s ob2=new s();
s ob3=new s();
}
}
In above program variable a and b are declared as int variable whereas the variable c is declared as
static variable. Static variable will be common between all the objects.
When we accessing variable as ‘a’ we cannot access it directly without the reference of the object
because ‘a’ exist in all three objects. So to access the value of ‘a’ we must link it with the name of the
object. But the ‘c’ is static variable and it is common between all the objects so we can access it
directly. But when we are accessing it outside the class in which it is declared, we must link it with
the name of the class i.e. with S as S.c=20;
Programs:
Q. Write a program to convert a decimal number to binary form and display the value
import [Link].*;
import [Link].*;
class dtob
{
public static void main(String args[]) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the decimal value=");
String hex=[Link]();
int i=[Link](hex);
String bi=[Link](i);
[Link]("Binary number="+bi);
}
}
Output:
Enter the decimal value=12
Binary number=1100
Vijay T. Patil
19
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Define a class item having data member code and price. Accept data for one object and display
it.
import [Link].*;
class Item_details
{
int code;
float price;
Item_details()
{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
[Link]("Code of item :"+code);
[Link]("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
Int co;
Float pr;
BufferedReaderbr=new BufferedReader (new InputStreamReader([Link]));
[Link]("enter code and price of item");
co=[Link]([Link]());
pr=[Link]([Link]());
Item_details obj=new Item_details(co,pr);
[Link]();
}
}
Q. Write a program to implement a vector class and its method for adding and removing elements.
After remove display remaining list.
import [Link].*;
import [Link].*;
import [Link].*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Character s5=new Character('a');
Vijay T. Patil
20
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s5);
[Link](s6);
[Link](s7);
[Link](s8);
[Link](v);
[Link](s2);
[Link](4);
[Link](v);
}
}
Q. Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20). Remove
element at 3rd and 4th position. Insert new element at 3 rd position. Display the original and current
size of vector.
import [Link].*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
[Link](new Integer(10));
[Link](new Integer(20));
[Link](new Integer(30));
[Link](new Integer(40));
[Link](new Integer(10));
[Link](new Integer(20));
[Link] println([Link]()); // display original size
[Link](2); // remove 3rd element
[Link](3); // remove 4th element
[Link](11,2) // new element inserted at 3rd position
[Link]("Size of vector after insert delete operations: " + [Link]());
}
}
Q. Write a program to accept a number as command line argument and print the number is even
or odd
public class oe
{
public static void main(String key[])
{
int x=[Link](key[0]);
if (x%2 ==0)
{
[Link]("Even Number");
Vijay T. Patil
21
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
}
else
{
[Link]("Odd Number");
}
}
}
Q. Define a class ‘employee’ with data members empid, name and salary. Accept data for five
objects using Array of objects and print it.
class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader([Link]));
[Link]("Enter Emp number : ");
empid=[Link]([Link]());
[Link]("Enter Emp Name : ");
name=[Link]();
[Link]("Enter Emp Salary : ");
salary=[Link]([Link]());
}
void show()
{
[Link]("Emp ID : " + empid);
[Link](“Name : " + name);
[Link](“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(inti=0; i<5; i++)
{
e[i] = new employee();
e[i].getdata();
}
[Link](" Employee Details are : ");
for(inti=0; i<5; i++)
e[i].show();
}
}
Q. Write a program to accept first name, middle name and surname in three different strings and
then concatenate the three strings to make full name.
Vijay T. Patil
22
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
class StringConcat
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String str1,str2,str3,namestr="";
[Link]("Enter first name:");
str1=[Link]();
[Link]("Enter middle name:");
str2=[Link]();
[Link]("Enter last name:");
str3=[Link]();
namestr = [Link](str1);
namestr = namestr + " ";
namestr = [Link](str2);
namestr = namestr + " ";
namestr = [Link](str3);
[Link]("Your FULL NAME is : " + namestr);
}}
Vijay T. Patil
23
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
import [Link].*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter String:");
String word=[Link]( );
int len=[Link]( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
if([Link](l)==[Link](r))
{
l++;
r--;
}
else
{
flag=0; break;
}
}
if(flag==1)
{
[Link]("palindrome");
}
else
{ [Link]("not palindrome"); }
}}
Q. Program to define a class student with four data members such as name, roll no, sub1 and
sub2. Define appropriate methods to initialize and display the values of data members also
calculate total marks and percentage scored by student
class stu
{
String name;
int rollno;
float sub1, sub2;
stu(String n, int r, float s1, float s2)
{
name=n;
rollno=r;
sub1=s1;
sub2=s2;
}
void display()
{
[Link]("Name="+name);
Vijay T. Patil
24
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Rollno="+rollno);
[Link]("Sub1 marks="+sub1);
[Link]("Sub2 marks="+sub2);
}
void calculate()
{
float total=sub1+sub2;
[Link]("total="+total);
float per=(total/200)*100;
[Link]("Percentage="+per);
}
}
class student
{
public static void main(String args[])
{
stu s=new stu("Vijay",11,90f,80f);
[Link]();
[Link]();
}
}
Q. Define a class circle having data members pi and radius. Initialize and display values of data
members also calculate area of circle and display it.
class abc
{
float pi,radius;
abc(float p, float r)
{
pi=p;
radius=r;
}
void area()
{
float ar=pi*radius*radius;
[Link]("Area="+ar);
}
void display()
{
[Link]("Pi="+pi);
[Link]("Radius="+radius);
}
}
class area
{
public static void main(String args[])
Vijay T. Patil
25
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
{
abc a=new abc(3.14f,5.0f);
[Link]();
[Link]();
}
}
import [Link].*;
class Square //super class
{
int length;
Square(int x)
{
length=x;
}
void area() //method to calculate area of square
{
int area=length*length;
[Link]("Area of Square="+area);
}
}
class Rectangle extends Square
//inherit class rectanglefrom class square
{
int breadth;
Rectangle(int x, int y)
{
super(x); //calling super class constructor
breadth=y;
}
void rectArea()
{
int area1=length*breadth;
[Link]("Area of Rectangle="+area1);
}
}
Vijay T. Patil
26
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
int height;
Box(int x, int y, int z)
//calling rectangle class constructor
{
super(x,y);
height=z; }
void volume()
//method to display volume of box
{
int volume=length*breadth*height;
[Link]("Volume of Box="+volume);
} }
class Shape
{
public static void main(String args[])
//main method
{
Box b=new Box(10,20,30);
//creating object of Box class
[Link]();
[Link]();
[Link]();
}
}
Output:
Volume of Box=6000
Area of Rectangle=200
Area of Square=100
Q. Program to define class student with roll no. and name. Derive class attendance with member
as present days. Write method to calculate and print average attendance assuming today days as
180.
import [Link].*;
import [Link].*;
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno=r;
name=n;
}
void display()
{
[Link]("Roll No="+rollno);
[Link]("Name="+name);
}
}
class stuatt
{
public static void main(String args[])
{
att s1=new att(11,"vijay",150);
[Link]();
}
}
Output:
Roll No=11
Name=vijay
Present days=150.0
Average Attendance=83.33333333333333
class person
{
String name;
int age;
void getdata(String n, int a)
{
name=n;
age=a;
}
void putdata()
{
[Link]("Employee Details: ");
Vijay T. Patil
28
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Employee Name: "+name);
[Link]("Employee Age: "+age);
}}
void putdata()
{
[Link]();
[Link]("Employee's Designation: "+emp_desig);
[Link]("Employee's Salary; Rs. "+emp_sal);
}}
class emp1
{
public static void main(String args[])
{
emp e1=new emp();
[Link]("vijay",30,"Manager",50000);
[Link]();
}}
Output:
Employee Details:
Employee Name: vijay
Employee Age: 30
Employee's Designation: Manager
Employee's Salary; Rs. 50000
Vijay T. Patil
29
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class account
{
String custname;
int accno;
void getdata(String n, int a)
{
custname=n;
accno=a;
}
void putdata()
{
[Link]("Customers Account Details\n");
[Link]("Customers Name: "+custname);
[Link]("Customers Account Number: "+accno);
}
}
Vijay T. Patil
30
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class accdetail extends savingacc
{
int deposits;
int withdrawal;
void getdata(String n, int a, int m, int s, int d, int w)
{
[Link](n,a,m,s);
deposits=d;
withdrawal=w;
}
void putdata()
{
[Link]();
[Link]("Deposit: "+deposits);
[Link]("Withdrawal Amount: "+withdrawal);
}
}
class acc
{
public static void main(String args[])
{
accdetail a1=new accdetail();
[Link]("Vijay",123,500,10000,5000,2500);
[Link]();
}
}
Output:
Customers Account Details
Customers Name: Vijay
Customers Account Number: 123
Minimum Balance: 500
Saving Balance: 10000
Deposit: 5000
Withdrawal Amount: 2500
import [Link].*;
class sphere
{
int r;
float pi;
Vijay T. Patil
31
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class volume
{
public static void main(String args[]) //main method
{
hemisphere h=new hemisphere(12, 3.14f, 2);
[Link]();
}
}
Output:
Volume of Sphere=602.88
Volume of Hemisphere=3617.28
Vijay T. Patil
32
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
abstract class shape
{
float dim1,dim2;
void getdata()
{
DataInputStream d=new DataInputStream([Link]);
try
{
[Link]("Enter the value of Dimension1: ");
dim1=[Link]([Link]());
[Link]("Enter the value of Dimension2: ");
dim2=[Link]([Link]());
}
catch(Exception e)
{
[Link]("General Error"+e);
}
}
void disp()
{
[Link]("Dimension1= "+dim1);
[Link]("Dimension2= "+dim2);
}
abstract void area();
}
Vijay T. Patil
33
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
void area()
{
area1=(0.5*dim1*dim2);
[Link]("The Area of Triangle is: "+area1);
}
}
class methodover1
{
public static void main(String args[])
{
rectangle r=new rectangle();
[Link]("For Rectangle");
[Link]();
[Link]();
[Link]();
Output:
For Rectangle
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 5.0
Dimension2= 6.0
The Area of Rectangle is: 30.0
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 6.0
Dimension2= 7.0
The Area of Triangle is: 21.0
Q. Write a program to accept a password from the user and authenticate the user if password is
correct.
import [Link].*;
class test
{
public static void main(String a[]) throws Exception
{
String S1="Admin";
String S2="12345";
String username, userpwd;
try
{
BufferedReader b = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the user name");
username=[Link]();
Vijay T. Patil
34
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Enter the password");
userpwd= [Link]();
if([Link](username) && [Link](userpwd))
{
[Link]("Welcome!! You are authenticated");
}
else
{
[Link]("You have entered wrong information!!");
}
}
catch(Exception e)
{
[Link]("I/O Error");
}
}
}
Output:
Enter the user name
Admin
Enter the password
12345
Welcome!! You are authenticated
Enter the user name
Admin
Enter the password
123
You have entered wrong information!!
Vijay T. Patil
35