Unit 2
Unit 2
Unit 2
S G Mundhe
Lecturer In IT
Government Polytechnic Nanded
• Declaring class
Syntax
class Student
{
data members;
member methods;
}
• Creating Object & accessing class members
class Test {
double width, height, depth;
}
class Test1{
public static void main(String [] arg ){
double volume;
Test obj =new Test();
obj. width=10.0;
obj. height=20.0;
obj. depth=15.0;
volume= obj. width* obj. height* obj. depth;
System.out.println(“Volume= ”+volume );
}
}
Output: Volume= 3000.0
Note- Members of the class are accessed in another class using object name and .
Operatoer
class Test{
double width, height, depth;
void cal ( ) {
width=10.0;
height=20.0;
depth=15.0;
double vol = width*height*depth;//inside same class so accessed directly
}
void display(){
System.out.println(“volume =”+ vol);
}
}
Public class Test1{
public static void main(Strring arg[]){
Test obj=new Test();
obj.cal();
obj.display();
}
}
import java.util.*; public class Student{
void volume() {
System.out.println( “volume=”+(width * height * depth));
}
}
class BoxDemo {
public static void main(String args[]) {
Box b1= new Box(10.1, 20.1, 15.1);
b1.volume();
}
}
• Parameterized Constructor
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
Box b1= new Box(10.1, 20.1, 15.1);
double vol;
vol = b1.volume();
System.out.println("Volume is " + vol);
}
}
• Constructor Overloading
class ConstructorOver {
int n1,n2, sum;
void cal () {
sum=n1+n2;
System.out.println("Sum ="+ sum);
}
}
public class ExCons1 {
public static void main(String[] args) {
ConstructorOver obj1=new ConstructorOver (10,20);
ConstructorOver obj2 =new ConstructorOver (50);
obj1.cal();
obj2 .call();
}
}
• this keyword
• Sometimes a method will need to refer to the object that invoked it.
• This can be used inside any method to refer to the current object.
• That is, this is always a reference to the object on which he method was
invoked.
class Test {
int a,b;
Test( int p, int q ){
this.a=p;
this.b=q;
}
void disp(){
System.out.println(“a=” +this.a+ ”b=” +this.b );
}
}
class CurrentObj{
public static void main(String []arg){
Test obj=new Test( 10,20 );
obj.disp();
}
}
• Command Line Arguments
• Syntax of varargs :
For Example,
}
class VarArgs {
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}
• Garbage Collection
• Since objects are dynamically allocated by using the new operator but how to
delete that object ?
• It works like this: when no references to an object exist, that object is assumed to
be no longer needed and memory will be made free .
• Java uses the void finalize() method for garbage collection. i.e once the execution
of finalize method completes then Garbage collector deletes the objects.
• This means that a reference variable of type Object can refer to an object of
any other class.
• Also, since arrays are implemented as classes, a variable of type Object can
also refer to any array.
• Visibility Modes /visibility control/ Access specifiers
• There are four access modifiers, private , public , protected and default.
• public-
• allows classes, methods and data variables accessed from any class.
• public specifies achieves the highest level of accessibility .
• private- It achieves the lowest level of accessibility.
• protected – can only be accessed by the subclass in the package & outside the
package.
• Default- within package only & behaves private out side the package
• Equals method
• public class Equal {
public static void main(String[] args) {
String str1 =new String( "abc");
String str2 =new String( "abc");
System.out.println(str1==str2 );//False
int i=10,j=10;
System.out.println ( i==j ); //true
}
}
Output:
true
false
public class TOSTRING {
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
}
}
• OUTPUT- 5
12
• public class ToGetClass{
We use == operator for reference equals method checks the content for
comparison comparison or equal method checks
the values for comparison
• Arrays
Array is a group of similar elements .
Types
• Single dimensional array-
• Syntax - type var-name[ ],
• E.g. int month_days[];
Out Put:
hello how are you
• Java String IsEmpty() : This method checks whether the String contains
anything or not. If the java String is Empty, it returns true else false.
}
• Java String Trim() : The java string trim() method removes the leading and
trailing spaces.
• It checks the unicode value of space character (‘\u0020’) before and after the
string. If it exists, then removes the spaces and return the omitted string.
• public class StrTream {
• It contains some particular sequence of characters, but the length and content
of the sequence can be changed through certain method calls.
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
Output:
• buffer before = Hello
• charAt(1) before = e
• buffer after = Hi
• charAt(1) after = i
insert()
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Out put
• After delete: This a test.
• After deleteCharAt: his a test.
String StringBuffer
The length of the string object is fixed The length of the StringBuffer object can be
increased.
String class overrides the equals() StringBuffer class doesn't override the
method of Object class. equals() method of Object class.
Wrapper Class
• A Wrapper class is a class whose object wraps or contains a primitive data
types.
• When we create an object to a wrapper class, it contains a field and in this
field, we can store a primitive data types.
• In other words, we can wrap a primitive value into a wrapper class object.
class Wrap {
public static void main(String args[]) {
Integer obj= new Integer(100);
int i = obj.intValue();
System.out.println(i + " " + obj);
}
}
Output :
100 100
class WrappingUnwrapping
{
public static void main(String args[])
{
byte a = 1; // byte data type
Byte byteobj = new Byte(a); // wrapping around Byte object
int b = 10; // int data type
Integer intobj = new Integer(b); //wrapping around Integer object
float c = 18.6f; // float data type
Float floatobj = new Float(c); // wrapping around Float object
double d = 250.5; // double data type
Double doubleobj = new Double(d); // Wrapping around Double object
char e='a'; // char data type
Character charobj=e; // wrapping around Character object
• The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int to
Integer, etc
v.add(1);
v.add(2);
v.add("geeks");
v.add("forGeeks");
v.add(3);
• Enum may implement many interfaces but can not extends enum class.
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }
class EnumDemo {
public static void main(String args[]) {
Apple ap;
ap = Apple.RedDel; // Output an enum value.
System.out.println("Value of ap: " + ap);
ap = Apple.GoldenDel;
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n");
}
}
Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.
• enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }
class EnumDemo2 {
public static void main(String args[]) {
Apple ap;
System.out.println("Here are all Apple constants:");
Apple al[] = Apple.values();
for(int m=0;m<5;m++)
System.out.println(al[m]);
Output
System.out.println(); Here are all Apple constants:
ap = Apple.valueOf("Winesap"); Jonathan
System.out.println("ap contains " + ap); GoldenDel
RedDel
} Winesap
} Cortland
ap contains Winesap
• ArrayList class
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
5) ArrayList uses the Iterator interface to A Vector can use the Iterator interface
traverse the elements. or Enumeration interface to traverse the
elements.
The End