0% found this document useful (0 votes)
12 views15 pages

Java Leave

Java basics

Uploaded by

kulasmart100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views15 pages

Java Leave

Java basics

Uploaded by

kulasmart100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Program 4.

2
class Student

private String name, city;


private int age;
public void getDatal()

name=Anana
city-Vellore":
age=23;

public void getData2()

name="Joseph"
city"Chennai "
age-22;
Output 4.2
public void printData() Student name = Anand
Student city = Vellore
System. out.println("Student nane ="+name ) Student age -23
System. out.println("Student city +city) Student name = Joseph
System. out.println("student age "tage) Student city = Chennai
Student age =22

Class Cs

publiC static void main(String args 1)

Student s1new Student()


Student s2-new Student ();
S1.getData1
)
S1.print Data()i
s2.getData2()
s2. printData()7

Student and Cs. Cs refers to the main () class. The stul


The program has two classes, namely,
toinitl
name, city and age as variables. The method. getDatal () and getData2 () are used
class has
usedto
dis

city and age. Then the printData() method


the values to the data members name, is
s!
class
members. In the main Class Cs two objects are created for student
the values of the data
Program 4.3

public class ModifierEx {


private String name-"Joseph";
private int age=20;
public void display)

System. Qut.println("Name : +name)


System.out.println("Age "+age)

private void show)

Systen.out.println("Name :"+name), Output 4.3


System.out.println ("Age "+age)
Name :Joseph
Age :20
class MoifierEx1

puhli statiC void main(String args[])

ModifierEx m1=new Modifier Ex():


n1.isplay ()
1Ia1.show () ;
The name of the class is ModifierEx and it has two variables and two methods. The data membe

name and age are declared and initialized with thè values Joseph and 20 respectively. The two
age
ods display() and show() print the values of the data members, The data members name and
ispub
declared as private. All theinstance variables are private by default. The display method. )
and hence itcan be accessed fromthe main() method to display the data members; show() Imethodis
netho

display the data members but is defined as private, hence it can't be accessedfrom themain)

The program has commented the invoking line m1. show () otherwisethe compiler will give
Program 4.4
class minimum

publ ic static void main (String[1 args)

int num1 12 10;


num2
Systen. out.println( wThe minimum of + numl
and + num2 +is + min (numl, nun2 )): Output. 4.4
The minimum of 12

a
public static int min (int x, int Y) 10.
int nini
if (x Y)

else

return (min);
88 Java Programming

Program 4.5
public class CallByValue

public void display (int y)

y 20:

public static void main (String args (]) Output 4.5


10
CallByValue cbv = new CallByValue();
int x = 10;
cbv.display (x);
System. out.println (x);

In Program 4.5 the class name is callByValue two methods, display


and ithas and main(j.
0

display()method is defined as publ ic,return type is void, display is the name of the method and
a parameter. The value 20 is assigned to the parameter y. In the main )
method the object cbyfr
defined class is created and the value 10is passed as argument to the display ( ) method. As a cop

x is passed changing y does not change the value of x in main () method. Hence the value of xdoes
change sothe output is 10. Program 4.6 also brieflyexplains the call by value technique.

Program 4.6
class byvalue

int data-50;
void change (int data)

ata-data+i00;
11changes will be in the local variable only Output 4.6

public static void main (Stríng args[l) before change 50


after change 50
byyalue op=new byvalue ()

System, out.println ("before change "+op.data) ;op.change (500)


Systen,out println("after change "+op.data)
Classes and Objects 89

In call by reference, however, the reference or in other words address of an argument is passed to
method.Any changes made inside the method will affect the argument's value. It manipulates objects by
reference and hence all object variables are referenced. When the reference is passed to a method, the
parameter thatreceives will refer to the same object. Hence changes to the object insidethe method will

afiect the object used as an argument. Program 4.7 demonstrates the objects being passed by reference

Progran 4.7
class byreference

int data-50;
void change(byreference op)

op.data-op. data+100
changes will be in the instance variable
Output 4.7
public static void main(String args[1) before change 50
after change 150
byreference op=new byreference(),
System.out.println( "before change +op.data) ;
op.change (op) l/passing object
System.out.println("after change "+op data)
Classes and Objects 91

Program 4.8

class Display

int a=4; 7/initiali zer expression


int b; /assigned default value
Display ()

a=5; 1/override default and initializer expression

void show
()
System.out.println ("Value of a ta); Output 4.8
System.out.println ("Value of b +b) ; Value of a : 5
Value of b : 0

class DefaultConstructor

public static void ma in (String Il args)

Display data=new Display()


data.show();

In Program 4.8 the class name is Display, the variables are a,bas integer type. The variable a is initial
izedwith value 4 and the other variable b is not initialized. There is a constructor namely Display(0 with
value 5. The method
nopararmeters and inside the constructor definition the variable a is assigned with the

show() is of return type void and it prints the values of a, b. The DefaultConstructor is the name ofthe

main class. Then an object data is created for the defined lass. During the data object creation, no values
are passed as arguments to the constructor Display ().On the execution of the statement, Display data =

new Display ()the ; constructor overrides the default value 4 andassigns the value 5to a. When the show ()

method iscalled it prints the value of the a as 5and b does not have any value so the constructor itself assigns

0 value byassessing the datatype to be integer. Hence the value of a is 5 and b 0 is is obtained as output.

4.4.2 Parameterized Constructor


While default constructors do not have any parameters, it
is however possible to have one or more

pararmeters in a Thistype of constructorwhich has parameters is known as a parameterzed


constructor.,
different sets of
Constructor, Using a parameterized constructor, it is possible to initialize objects with
values at the time of their creation. These different sets of initialization values must be passed as argu

invoked. The parameter can be specified in parentheses in the Same


ments when the constructoris list

way astheparameter list is specified in the method.


The generalform of the parameterized constructoris

PConstructor (datatypel argl, datatype2 arg2.)

1 give inítial values to data members


Program 4.9

class Rectangle

int length:
int breadth:
7iconstructor to initialize length and breadth of rectangle
Rectangle (int l,int b)

length = l;
breadth+ b;

1method to calculate area of rectangle


int area()

Output 4.9
return (length * breadth);
Area of First Rectangle 5
Area of Second Rectangl:
1/ciass to create rectangle objects and calculate 56
area
class ParaneterizedConstructor

public static void main (Stringl]args)

Rectangle firstRect = new Rectangle(5,6):


Rectangle secondRect = new Rectangle(7,8):
Systern.out.println ("Area of First Rectangle
+firstRect.area());
Systen.out.println("Area of Second Rectangle :"
+seconóRectarea();

InProgram 4.9 the class name is Rectangle


and the variables are length, breadth
s
There is need for a constructor to
and it contains
initialize the variables. Hence the
constructor Rectangle
)
two parameters 1, b The method area() is declaredto calculate the
as integer.
at

rectanglewhere itreturns themultiplied


value of length and breadth.The
is the name of the
main class, The objects Parameter1zee
firstRect, secondRect are createdRectangle
for the
During the firstRectobject
methods named
In Program name is Calculation and it has two
4.13 the class
overloaded
a, b of integer type and the
second
where both have two parameters. The first sum ()method holds
Then
the object for the class is created as obj.
method holds a, b as double. In main()method holds double
two double values have been assigned and it executes the method which
Sum() method
which ho
integer values are assigned and the method
as parameters. Similarly in the next line two value 21.0 =
is executed. Hence the output for the first sum method is double
integers as parameters
overloading with return
illustrates the concept of method
second sum method is40. Program 4.14

Program 4.14
Class overloading

int cal,
float val,
int add( int x, int y)

return (cal}

int add int z)

cal= z+i0;
return (cal)i
Output 4.14
1loat add (float x floatt y)
10+10=20
15+10=25
val =X + yi 1.5+1.5=3.0
return (val)

class MathS

public static void main String args I)

Overloading m=new overloading ()


Systen.out println ("10+10=" +m. add(10,10)
);
System. out.println ("15+10="+m. add (15)):
$ystem. out.println (1.5+1.5="+m.add (1.5f,
1.5E));

In Program 4.14 the class nameis overl oading and it has two variables cal as integer, va
Progranm 4.12

class Total{
void sum(int a, int b)

System. out.println (a + b)}


void sum (int a, int b, int c)
Output 4.12
System.out.println(a + b + c);
30
public static void main(String args{l){ 40
Total obj=new Totàl () :
ob.sum(10,10, 10);
obj.sum(20,20);

In Program 4.12 the class name is Total and it has two methods named sum(). Since both m

have the samename they are called overloaded methods. The first sum ()method has two argumens
integertypeand the second sum ()method consistsof three arguments a,b, c as integertypes. Ihe
method performs addition of two numbers and the second sum method performs addition of tre

bers. In main ()method an object for the class Total is created as obj. Then with thehelp of objcate

arguments are passed tothe sum ) method. The first call passes three integer values to the sunt

with three argument. The second two integer values to the sum () method with two
call passes g
The execution in an overloaded method depends on the nümber of argument and the data type o
ments passed to the methods. Thus the first passing generates output 30 and the second time tne
40.Program 4.13explicitly describes method overloading by changing the data type of the g
Program 4.13
Class Calculation

yoid sum(int a, int b)

SYstem,out.println(a + b)

Void un(ouble a, double b)

System. out,println (a b); Output 4.13


public static void nain(String args (]) 21.0
40
Calculation objunew Calculat ion()
obj,sun(10,5,10.5)
obj,sun(20,20);
:
Program 4.15
class Box

int height, depth, length;


Box()

height-depth=length=10;
3
Box(int x, int y)

height-x;
depth=y:
}
Box (int x, int y 1nt z)
Output 4.15
height=x;
depth=Yi Depth of a: 10
length=zi Depth of b: 15
Depth of c: 15

Class BoxClass

public static void main (String árgs (1)

Box a new Boxi


System. out.println("Depth of a: "+a.depth);
Box b= new BOx{10, 15) ;
Systen. outprintln ("Depth of b: +b. depth);
BOx C= new BOx(12,15, 20)
System. out println("Depth of c:+C.depth):

andlengt
In Program 4.15 the class Box containsthree variables height, depth
different co
a default
Box () is
is a dela
gers. It also has three constructors named Box().The first constructor and dep
since it does not have any parameters but initializes the variables length, height
it
assigt
and
Progranm 4.16

class Rectangle {
int length;
int breadth:
Rectangle (int l,int b) {
length = l;
breadth = b;

Rectangle getRectangleobject () {
Rectangle rect = new Rectangle (10,20)
zeturn rect; Output 4.16
obl.length: 40
obl.breadth: 50
Class RetOb ob2.length: 10
public static void main (String args[]) { ob2.breadth: 20
Rectangle ob1 = new Rectangle (40, 50);
Rectargle ob2;
ob2 = ob1.getRectangleObject ();
Systen, out println("obl,length: " + obl.length)
Systero. out.príntln(ob1, breadth:"+
ob1.breadth);
System, out.println("ob2.length: " + ob2,length)
System, out.println ("ob2.breadth;"+ ob2, breadth)
;

the method creates


In Program 4.16 the programmer called a method get:RectangleObject() and
dynamically allocated
object rect of class Rectangle from which it has been called. All objects are
the method in whic
using new; one doesn't need to worry about an object going out-of-scope because
it was created terminates, The object willcontinue toexist as long as there is a reference to it somewhere
in theprogram, When there are no references to it, the object will be reclaimed the next time garbag
collection takes place.
Program 4.17
class Student
int rollno;
String name;
String city;
Student (int rollno, String nane String city)(
this.rollno=rollno;
thìs. name=name;
this.city=city;
Output 4.I7
public static void main(String argstl){ Student@c17164
Student sl=new Student (101,"Joseph","Tirupattur"); Student@1fb8ee3
Student s2=new Student (102,"Joe,"Vellore")
System. out.println (s1)//compiler writes here
sl.toString ()
System. out.println (s2) //compiler wIites here
s2.toString ()

In Program 4.17 the class student has variable rollnoas integer, name and city as type s
constructor student ()receives three parameters rollno, name and city and assigns them
variables. In main(0 the objects s1, s2 are createdforthe defined class and one integer, two Su
Printing
s
are passed as arguments. The next statements print the content of the objects s1, s2.
a
s2 displaysthe hashcode values of the objects but when one want to print the values ofthese
becomes a complex task. Since the Java compiler internally calls toString 0 method overmu
ll
method will return tostring
thespecified values. The problem can be solved withthe help of

Program 4.18 demonstrates the use of tostring () method.

Program 4.18
Class Student
int rolino:
String name;
String cityi
Student(int rollno, String name, String city)
this.rollno=rollno;
this. panesame;
thís,cítyscityi
Output 4.18
public String tostring (07/overriding the
toString() nethod 101 Joseph Tirupattur
return rollno+ +nane "+city; l02 Joe Vellore

public static void nain(8tring args [])


Student sl=new Student (101,"Joseph", "Tirupattur")i
Program 4.19

public class EqualsExample(


public static void main (String args{]){
String si="java";
String s2="java";
String s3="Visualbasic"; Output 4.19
String s4="python":
true
System.out.println(s1.equals(s2)); false
System.out.println (s1,equals(s3)); false
System,out.println (s1.equals(s4)):
Department MSC
Shift :2
:
Regno Name Dept Shift
504 Prabu MSC
506 John MSC 2

4. Program to print the odd or even numbers using objects


import java. util.Scanner
public class Even_0r_Odd

int a;
public void get ()

Scanner s=new Scanner (System. in);


");
System. out.println ("Enter any Number:
a=s.nextInt ();
is : ") ;
System. out.println ("Given Number "+a+"

public void display ()


{
if (a%2==0)

System. out.println ("Even");

else

System. out.println( "Odd"):

(String[] args)
public static void main
{
Even_0r_0dd ();
Even_Or_Odd e=new
e.get (0;
e.display ()
;

Output

11 Por Even
Enter any Number : 2
Given Number 2 is :Even
11 For 0dd
Enter any Number: 125: Odd
is
Given Number 125

print the biggest


among the numbers
to
5. Program
Scanner i
import java. util,
class Bigger Among_Nos

int a,b,ci in);


Scanner(System.
Scanner s=new
void getA ()
Value: ")
("Enter First
System, out.println
}

class nesteddemo

public static void main(String arg[J)

outer outobj=new duter(0;


outer. inner inobj=outobj .new inner () :
inobj. display():

Output

10
n20
7. Programto implement array of objects.
import java.lang. *;
public class EmployeeTest

public static void main (String [] args)

Employee [] staff =
new Employee [3]:
3500);
staff [O] = new Employee ("Harry Hacker",
Cracker", 7500);
staff [1] = new Employee ("Carl
3800);
staff [2] = new Employee ("Tony Tester",
for (int i = 0; i < 3; i++)
staff [i].print();

class Employee

private String name;


private double salary;
double s)
public Employee (String n,

name= n;
salary = S;

public void print )

System,out.println (name + + salary);

Output

Harry Hacker 3500,0


Carl Cracker 7500,0
Tony Tester 3800.0

You might also like