Sunteți pe pagina 1din 41

CHAPTER 2 (18 MARKS)

Constructors
● In Java, a constructor is a block of codes ​similar
to the method.
● It is called when an ​instance of the object is
created(new), and memory is allocated for the
object.
● It is called constructor ​because it constructs
the values at the time of object creation.
● It is not necessary to write a constructor for a
class. It is because java compiler creates a
default constructor if your class doesn't have
any.

When is a constructor called


Every time an object is created using new()
keyword, at least one constructor is called. It calls a
default constructor.
Rules for creating Java constructor
There are two rules defined for the constructor.
1.Constructor name must be the same as its class
name
2.A Constructor must have no explicit return type
3.A Java constructor cannot be abstract, static,
final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
1.Default constructor (no-argument constructor)
2.Parameterized constructor

​ efault Constructor
D
A constructor is called "Default Constructor" when
it doesn't have any parameter.
class Rectangle
{
Rectangle()
{
System.out.println("reclangle is created");
}

public static void main(String args[])


{
//calling a default constructor
Rectangle r=​new​ Rectangle();
}
}

Parameterized Constructor
A constructor which has a specific number of
parameters is called a parameterized constructor.
class Rectangle
{
int length;
int width;

//creating a parameterized constructor


Rectangle(int l,int w)
{
length = l;
width = w;
}
void calculate()
{
int area=length*width;
System.out.println("area of rectangle="+area);
}
}

class paraconstruct
{
public static void main(String args[])
{
//creating objects and passing values
Rectangle r = new Rectangle(111,78);

r.calculate();

}
}

class Nesting
{
int length;
int width;
int area;

//creating a parameterized constructor


Nesting(int l,int w)
{
length = l;
width = w;
}
void calculate()
{
area=length*width;
}

void display()
{
calculate();
System.out.println("area of rectangle="+area);
}

public static void main(String args[])


{
Nesting n = new Nesting(10,20);
n.display();
}
}
output:
area of rectangle=200

Command line argument in Java​.


● The ​command line argument is the ​argument
passed to a program at the time when you run it.
● arguments are stored as string in String array
passed to the ​args parameter of main(​String
args[])​ method.
● for example
class commandline1
{
public static void main(String args[])
{
int count=args.length;

for(int i=0;i<count;i++)
System.out.println(args[i]);

}
}

javac commandline.java
java commandline 10 20 30
10
20
30
example2-
class commandline
{
public static void main(String args[])
{
int a,b,sum;
a=Integer.parseInt(args[1]); //"10" convert to 10
and it will store in a
b=Integer.parseInt(args[0]); //"20" convert to 20
and it will store in b
sum=a+b;
System.out.println(“sum=”sum);

}
}

javac commandline.java
java commandline 10 20
sum=30

Vrags-variable arguments
● Let’s suppose you are creating a ​Java method​.
However, you are not sure how many arguments
your method is going to accept. To address this
problem, Java introduced varargs.
● Varargs is a short name for variable
arguments. In Java, an argument of a method
can accept arbitrary number of values. This
argument that can accept variable number of
values is called varargs.
● The syntax for implementing varargs is as
follows:
accessModifier methodName(datatype… arg)
{
// method body
}
In order to define vararg, ... (three dots) is used in
the formal parameter of a method.
for eg.
class Varg
{
void display(int ... arr)
{
for(int x: arr)
{

System.out.println(x);
}

public static void main( String[] args )


{
Varg v = new Varg();

v.display(2, 4);
System.out.println("---------------------------------");

v.display(1, 3, 5);

}
}

this keyword
There can be a lot of usage of ​java this keyword​. In
java, this is a ​reference variable​ that refers to the
current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1.this can be used to refer current class instance
variable.
2.this can be used to invoke current class method
(implicitly)
3.this() can be used to invoke current class
constructor.
4.this can be passed as an argument in the method
call.
5.this can be passed as argument in the constructor
call.
6.this can be used to return the current class
instance from the method.
for eg.
class Rectangle
{
int l;
int w;

//creating a parameterized constructor


Rectangle(int l,int w)
{
this.l = l;
this.w = w;
}

void calculate()
{
int area=l*w;
System.out.println("area of rectangle="+area);
}
}

class thisprogram
{
public static void main(String args[])
{
Rectangle r = new Rectangle(10,20);
r.calculate();
}
}
Access Modifiers/specifiers/visibility control in
java
Access Modifiers the name suggests access
modifiers in Java helps to restrict the scope of a
class, constructor , variable , method or data
member. There are four types of access modifiers
available in java:
1.Default(friendly) – No keyword required
2.Private
3.Protected
4.Public
​ ublic​: The public access modifier is specified
p
using the keyword ​public​.

● The public access modifier has the ​widest scope


among all other access modifiers.
● Classes, methods or data members which are
declared as public are ​accessible from every
where​ in the program. There is no restriction on
the scope of a public data members.
● for eg.
public int a;
public void sum();
Private​: The private access modifier is specified
using the keyword ​private​.
● The methods or data members declared as
private are accessible only ​within the class​ in
which they are declared.
● Any other ​class of same package will not be
able to access​ these members.
● for eg.
private int a;
private void sum();

protected​: The protected access modifier is


specified using the keyword ​protected​.
● The methods or data members declared as
protected are ​accessible within same package
or sub classes in different package.
● for eg.
protected int a;
protected void sum();
Default​: When no access modifier is specified for a
class , method or data member – It is said to be
having the ​default​ access modifier by default.
o The data members, class or methods which
are not declared using any access modifiers
i.e. having default access modifier are
accessible ​only within the same package​.
for eg.
int a;
void sum();
1.Default​: When no access modifier is specified
for a class , method or data member – It is said
to be having the ​default​ access modifier by
default.
o The data members, class or methods which

are not declared using any access modifiers


i.e. having default access modifier are
accessible ​only within the same package​.

Java Array
Normally, an array is a collection of similar type of
elements that have a contiguous memory location.
Java array​ is an object which contains elements of
a similar data type.
It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java
array.
Array in java is index-based, the first element of the
array is stored at the 0 index.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];
//declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};
//declaration, instantiation and initialization

//printing array
for(int i=0;i<a.length;i++)
//length is the property of array
System.out.println(a[i]);
} }
What is String in java
Generally, String is a sequence of characters. But in
Java, string is an object that represents a sequence of
characters.
How to create a string object?
There are two ways to create String object:
1.By string literal
2.By new keyword

1) String Literal
Java String literal is created by using double quotes.
For Example:
1.String s="welcome";
) By new keyword

1.String s=new String("Welcome");


Example

public class StringExample


{
public static void main(String args[])
{
String s1="java";
//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
//converting char array to string
String s3=new String("example");
//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
output:
java
strings
example

String functions

1)charAt()-
The ​java string charAt()​ method returns ​a char
value at the given index number.​
public class CharAtExample
{
public static void main(String args[]){
String name="javatpoint";

char ch=name.charAt(9);//returns the char value at th


e 9th index
System.out.println(ch);
}}
output- t

2)length()
It returns count of total number of characters.
public class LengthExample
{
public static void main(String args[])
{
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());//
10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());//
6 is the length of python string
}}
output:
string length is: 10
string length is: 6

3)substring()
substring()​ method returns a part of the string.
public class SubstringExample{
public static void main(String args[]){
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint

}}

output:
vat
vatpoint

4)​concat
concat()​ method ​combines specified string at the
end of this string.​ It returns combined string. It is
like appending another string.

public class ConcatExample{


public static void main(String args[]){
String s1="java string";

s1=s1.concat(" is immutable so assign it explicitly");

System.out.println(s1);
}}

output:
java string is immutable so assign it explicitly
5)replace()

replace()​ method returns a string replacing all the


old char or CharSequence to new char or
CharSequence

public class ReplaceExample2


{
public static void main(String args[])
{
String s1="my name is abc";
String replaceString=s1.replace("is","was");
//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}

output:
my name was abc.

6)indexOf()
indexOf()​ method returns index of given character
value or substring. If it is not found, it returns -1.
The index counter starts from zero.
public class IndexOfExample2
{
public static void main(String[] args)
{
String s1 = "This is indexOf method";
// Passing Substring
int index = s1.indexOf("method"); //Returns the in
dex of this substring

System.out.println("index of substring "+index);


}
}

output:
index of substring 16

7)toLowerCase()
toLowerCase()​ method returns the string in
lowercase letter. In other words, it converts all
characters of the string into lower case letter.

public class StringLowerExample


{
public static void main(String args[])
{
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}
Output:
javatpoint hello string

8)toUpperCase()

toUpperCase()​ method returns the string in


uppercase letter. In other words, it converts all
characters of the string into upper case letter

public class StringUpperExample{


public static void main(String args[]){
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}
Output:
HELLO STRING
9)valueOf()
valueOf() method converts different types of values
into string. By the help of string valueOf() method,
you can convert int to string, long to string, boolean
to string, character to string, float to string, double to
string, object to string and char array to string.
public class StringValueOfExample
{
public static void main(String args[])
{
int value=30;
String s1=String.valueOf(value);
System.out.println(s1);//concatenating string with 10

}}
Output:
30
Wrapper class
Wrapper class in java​ provides the mechanism​ t​ o
convert primitive data type into object and object
into primitive data type​.
The automatic conversion of primitive into object is
known as autoboxing and vice-versa unboxing.
The eight classes of ​java.lang​ package are known as
wrapper classes in java. The list of eight wrapper
classes are given below:
Inheritance
● Inheritance is a mechanism in which one class
acquires the property of another class. For
example, a child inherits the traits of his/her
parents.
● With inheritance, we can reuse the fields and
methods of the existing class.
● The parent class is termed super class and the
inherited class is the sub class
● The keyword "extend" is used by the sub class
to inherit the features of super class
Types of Inheritance
There are Various types of inheritance in Java:

1.Single Inheritance:
In Single Inheritance one class extends another
class (one class only).
In above diagram, Class B extends only Class A.
Class A is a super class and Class B is a
Sub-class.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.sala
ry);
System.out.println("Bonus of Programmer is:"+p.b
onus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000

2.Multiple Inheritance:
In Multiple Inheritance, one class extending
more than one class. Java does not support
multiple inheritance.
As per above diagram, Class C extends Class A
and Class B both.
3.Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit
from a derived class. Hence, the derived class
becomes the base class for the new class.
As per shown in diagram Class C is subclass of
B and B is a of subclass Class A.

4.Hierarchical Inheritance:
In Hierarchical Inheritance, one class is
inherited by many sub classes.
As per above example, Class B, C, and D inherit
the same class A.
5.Hybrid Inheritance:
Hybrid inheritance is a combination of Single
and Multiple inheritance.

As per above example, all the public and


protected members of Class A are inherited into
Class D, first via Class B and secondly via Class
C.

S-ar putea să vă placă și