Unit-2 Java
Unit-2 Java
Unit-2 Java
Constructors
❑ Constructors are used to assign initial values to instance variables of the class.
❑ A default constructor with no arguments will be called automatically by the
Java Virtual Machine (JVM).
❑ Constructor is always called by new operator.
❑ Constructors are declared just like as we declare methods
❑ The constructors don’t have any return type, not even void because they return
the instance of the class itself.
❑ Constructors have the same name as the class itself.
Constructors
Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Types of Constructor
Constructor
❑ When no constructor has been explicitly defined then java creates a default
constructor.
❑ Default constructor automatically initializes all instance variables to zero.
Syntax:
class classname
{
classname()
{
}
}
❑ Class name will be the same name of class in which constructor is declared.
Example of Default Constructor
class sample
{
int num;
sample()
{
num=10;
System.out.println(“Constructor OUTPUT
class Rectangle
{ int length;
int breadth;
Rectangle(int l, int b)
{ length = l;
breadth= b;
}
int area()
{ return (length * breadth); }
}
class ParameterizedConstructor
{
public static void main(String[] args)
{ Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect = new Rectangle(7,8);
System.out.println("Area of First Rectangle : " +firstRect.area());
System.out.println("Area of Second Rectangle : "+secondRect.area());
}
Copy Constructor
❑ A copy constructor is a special type of constructor that creates an object using another object of the
same Java class.
❑ It returns a duplicate copy of an existing object of the class.
public class Fruit fprice = fruit.fprice;
{ fname = fruit.fname;
private double fprice; }
private String fname; double showPrice()
//constructor to initialize roll number and name of the student {
Fruit(double fPrice, String fName) return fprice;
{ }
fprice = fPrice; String showName()
fname = fName; {
} return fname;
//creating a copy constructor }
Fruit(Fruit fruit) public static void main(String args[])
{ {
System.out.println("\nAfter invoking the Copy Constructor:\n"); Fruit f1 = new Fruit(399, "Ruby Roman Grapes");
System.out.println("Name of the first fruit: "+ f1.showName());
System.out.println("Price of the first fruit: "+ f1.showPrice());
Fruit f2 = new Fruit(f1);
System.out.println("Name of the second fruit: "+ f2.showName());
System.out.println("Price of the second fruit: "+ f2.showPrice()); }}
Difference between Constructor and Method
❑ Constructor overloading in java allows having more than one constructor inside
one Class.
❑ Constructor with same name and different arguments then it’s called constructor
overloading.
❑ Overload constructors - define multiple constructors which differ in number
and/or types of parameters.
Example of Constructor Overloading
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,“Vihan");
Student s2 = new Student(222,“Rudra",25);
s1.display();
s2.display(); } }
Nesting of Methods
❑ A method of a class can be called only be an object of that class using the dot operator.
❑ Exception to this is a method can be called by using only its name by another method of the same class.
❑ This is known as nesting of methods.
class Nesting
{ int m, n; constructor
Nesting (int x, int y)
{ m=x; n=y; }
int largest()
{ if (m >= n)
return (m);
Nesting of
else return(n); }
Methods
void display ()
{ int large = largest();
System.out.println(“Largest value = “ + large); } }
public void static main(String args[ ])
{ Nesting nest = new Nesting (50, 40);
nest.display();
}
This Keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Note: 1.We are using this keyword to distinguish local variable and instance variable.
2. If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
Command Line Argument
❑ When we provided the input at the time of execution, it is known as command line arguments.
❑ Command line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.
❑ Args is declared as an array of strings. Any arguments provided in the command line are passed
to the array args as its elements.
❑ Example
class testarg
{ public static void main(String args[])
{ for(int i=0;i<args.length;i++)
{ System.out.println("Args[" + i + "] is " + args[i] );
}
}
Steps to run program Javac testarg
Java testarg C C++ Java
Output
Args[0] is C
Args[1] is C++
Args[2] is Java
Var args: Variable length arguments
❑ Variable argument in Java allows you to write more flexible methods which can accept as many
argument as you need.
❑ If we don't know how many argument we will have to pass in the method, var args is the better
approach.
❑ Var args is a helper syntax and it enables use of variable number of arguments in a method call.
❑ Syntax: type … variable Name.
class Example
{
void display(String... values)
{ System.out.println("display method invoked ");
for(String s:values)
{ System.out.println(s); } }
public static void main(String args[])
{ display(); //zero argument
display("hello"); //one argument
display("One","Two","Three","Four"); //four arguments } }
Garbage Collector
1. The memory to the object are dynamically allocated by using “new” operator.
2. Objects are destroyed and there memory release for later reallocation
3. In some language such as c++,dynamically allocated object must be manually
release by use of “delete” operator.
Java takes different approaches it handles the allocation of object automatically.
When no reference exits ,that object is assume to no longer needed and the memory
occupied by the object can be released.
There is no need to destroy the object explicitly.
Garbage Collector only occurs at irregular interval during the execution of program.
Garbage Collector
❑ When the object is not needed any more, the space occupied by such objects can be collected
and use for later reallocation.
❑ Java performs release of memory occupied by unused objects automatically, it is called garbage
collection.
❑ JVM runs the garbage collector (gc) when it finds time. Garbage collector will be run
periodically but you can not define when it should be called. We can not 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.
class X
{ int a; X() { a=0; } }
class Y
{ public static void main(String args[])
{ X ob1 = new X();
X ob2 = new X(); Ob1 = ob2; } }
Two objects are created which are referenced by ob1 and ob2
Garbage Collector
❑ The finalize() method of Object class is a method that the Garbage Collector always calls just
before the deletion/destroying the object which is eligible for Garbage Collection, so as to perform
clean-up activity.
❑ Since Object class contains the finalize method hence finalize method is available for every java
class
❑ Object is the superclass of all java classes. Since it is available for every java class hence Garbage
Collector can call the finalize method on any java object
Visibility Control in Java
Visibility Control
Private
Public Private Protected friendly
Protected
Java provides a number of access modifiers to set access levels classes, variables , methods and
constructors.
class A
{
private int data = 40;
private void msg()
{ System.out.println(“Hello Java”);} }
class Test
{
public static void main(String args[])
{
A obj=new A();
system.out.println(“Data is :”+obj.data); //Compile Time Error
Obj.msg(); //Compile Time Error
}
}
Friendly access specifier
❑ When no access modifier is specified
❑ The member defaults to a limited version of public accessibility known as “friendly” level of access.
❑ The difference between the public access and friendly access is that the public modifier makes
fields visible in all classes, regardless of their packages while the friendly access makes fields
visible only in the same package, but not in other packages.
class BaseClass
{ void display()
{ System.out.println("BaseClass::Display with 'dafault' scope"); } }
class Main
{ public static void main(String args[]) { //access class with default scope BaseClass obj = new
BaseClass();
obj.display();
}
}
Protected & Private Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
It provides more accessibility than the default modifer.
Private Protected Access
► The visibility level lies between private and protected access.
► This modifier makes fields visible in all subclasses regardless of what package they are in.
► These fields are not accessible by other classes in the same package.
Array in Java
► A list of items can be given one variable name using only one subscript and such a variable is
► After declaring the variable for the array, the array needs to be created in the memory.
► This can be done by using the new operator in the following way:
Arrayname = new type[size];
numbers = new int [10];
► This statement assigns ten contiguous memory locations of the type int to the variable numbers.
The array can store ten elements.
int number [] = new int[10];
Initialization of array
In java all array store the allocated size in a variable named length.
❑ We can access the length of the array using a.length
❑ int asize = a.length;
Program
class arraytest
{ public static void main(String args[])
{ int [] a1;
a1=new int[3];
a1[0]=11;
a1[1]=22;
a1[2]=33;
System.out.println("first element= "+a1[0]);
System.out.println("first element= "+a1[1]);
System.out.println("first element= "+a1[2]);
}
}
Two Dimensional Arrays
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first.
If the string already exists in the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
By new keyword
String s=new String("Welcome");
► String Concatenation
► String Comparison
► Substring
► Length of string and etc.
String Concatenation
There are two methods to concatenate two or more strings.
Concatenate two or more strings
1. Using concate() method
2. Using + Operator
String Concatenation Example
The java string length() method find the length of the string.
It returns the count of total number of characters.
Example:
public class lengthexample
{ public static void main(String args[])
{ String s1 = “Hello World”;
System.out.println(“String length is:” + s1.length());
}
}
More Methods on String
1)charAt()
2)contains()
3)getChars()
4)indexOf()
5)replace()
6)toLowerCase()
7)toUpperCase
charAt() and contains()
► toLowerCase(): it converts all the characters of the string into lowercase letter.
► toUpperCase(): it converts all the characters of the string into uppercase letter.
Example:
class methods
{ public static void main(String args[])
{ String s1 = “Hello World”;
String lowercase = s1.toLowerCase();
System.out.println(lowercase);
String uppercase = s1.toUpperCase();
System.out.println(uppercase);
}
}
Immutable String in Java
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
StringBuffer Class
In java strings are class objects and implemented using two classes namely, String and StringBuffer.
append()
Example:
Class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Welcome");
StringBuffer s2 = new StringBuffer(“ GHRIET");
s1.append(s2);
System.out.println(s1);
}
}
Insert()
Example:
Class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Welcome");
StringBuffer s2 = new StringBuffer(“ World");
S1.insert(3,s2);
System.out.println(s1);
}
}
delete()
This is the delete() function is used to delete multiple character at once from n
position to m position (n and m are will be fixed by you.) in the buffered string.
Example:
Class a
{ public static void main(String args[])
{
StringBuffer s1 = new StringBuffer(“College");
s1.delete(1,3);
System.out.println(s1);
}
}
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.
Example:
class a
{ public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“Morning");
s1.deleteCharAt(2);
System.out.println(s1);
}
}
reverse()
This is the reverse() function used to reverse the string present in string buffer.
Example:
Class a
{
public static void main(String args[])
{ StringBuffer s1 = new StringBuffer(“GHRIET");
s1.reverse();
System.out.println(s1);
}
}
setCharAt()
Example:
Class a
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer(“College");
s1.setCharAt(3,’e’);
System.out.println(s1);
}
}
Vector
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
byte Byte
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short
Autoboxing
❑ The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing
❑ Example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
❑ The Enum in Java is a data type which contains a fixed set of constants.
❑ It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW,
BLUE, GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we
should have all constants in capital letters. So, we have enum constants in capital letters.
❑ Enums are used to create our own data type like classes.
❑ The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java.
❑ Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either inside the
class or outside the class.
Simple Example of Java Enum
class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
values(), valueOf(), and ordinal() methods of Java enum.
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}
}