You are on page 1of 57

Unit –II

Derived Syntactical Constructs In Java

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{

class Student1 { public static void main(String[] args) {


String name ;
int roll,marks; Student1 s =new Student1 ();
Scanner sc=new Scanner (System.in); s.getData();
s.display();
void getData( ){
}
System. out.println("Eneter Roll no");
}
roll=sc.nextInt();
System. out.println("Eneter Name");
name=sc.next();
System. out.println("Eneter Marks");
marks=sc.nextInt();
}
void display() {
System. out.println(" Roll no="+roll);
System. out.println("Name="+name);
System. out.println("Marks="+marks);
}
}
• Constructor

– Its name is same as the name of the class .


– It doesn’t return the value
– It is automatically called when the object is created.
– Constructor without parameter is called default
constructor .
– It can be overloaded.
– It can have arguments.
– If the programmer don’t write constructor then compiler
provides the default constructor.
– If the programmer writes the any parameterized
constructor the compiler will not provide the default
constructor.
Default constructor
class ExCon{
int n1,n2, sum;
ExCon(){
n1=10; n2=5;
}
void cal () {
sum=n1+n2;
System.out.println("Sum ="+ sum);
}
}
public class ExCons1 {
public static void main(String[] args) {
ExCon obj=new ExCon(); //default Constructor is called
obj.cal();
}
}
class ExCon{
int n1,n2, sum;
ExCon(int a ,int b){
n1=a; n2=b;
}
void cal () {
sum=n1+n2;
System.out.println("Sum ="+ sum);
}
}
public class ExCons1 {
public static void main(String[] args) {
ExCon obj=new ExCon(10,20); //Parameterized Constructor called
obj.cal();
}
}
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

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;

ConstructorOver (int a ,int b){ Out put


n1=a; n2=b; Sum= 30
} Sum= 55
ConstructorOver (int a ){
n1=a;
n2=5;
}

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

• When you will want to pass information into a Run :


program when you run it. java CommandLine this is a
test 100 -1
• This is accomplished by passing command-line
arguments to main( )

class CommandLine { output:


args: this
public static void main(String args[]) { args: is
for(int i=0; i<args.length; i++) args: a
System.out.println(“args:" +args[i]); args: test
args: 100
} args: -1
}
Variable length argument
• Beginning with JDK 5, Java has included a feature that need to take a variable
number of arguments.

• This feature is called varargs and it is short for variable-length arguments .

• A method that takes a variable number of arguments is called a variable-arity


method , or simply a varargs method.

• A variable-length argument is specified by three periods(…)

• Syntax of varargs :

For Example,

public static void fun(int ... a) {


// method body

}
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 ?

• In some languages, such as C++, dynamically allocated objects must be manually


released by use of a delete operator.

• Java takes a different approach; it handles deallocation for you automatically.


• The technique that accomplishes this is called garbage collection

• 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.

• System.gc() method – it requests the JVM to run Garbage Collection


• Syntax
protected void finalize( )
{
// finalization code here
}
• The Object Class

• All other classes are subclasses of Object class .

• That is, Object is a superclass of all other classes.

• 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");

boolean b= str1.equals(str2); // true


System.out.println ( b ); //true

System.out.println(str1==str2 );//False

int i=10,j=10;
System.out.println ( i==j ); //true

}
}

Output:
true
false
public class TOSTRING {

public static void main(String[] args) {

Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
}
}

• OUTPUT- 5
12
• public class ToGetClass{

public static void main(String[] args) {

Integer i= new Integer(10);


Class obj= i.getClass();
System.out.println("class name ="+obj.getName());
}
}
OUTPUT –
class name = java.lang.Integer
• Difference between == and equals method
== equals ()

== is a operator equals() is a method or function

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[];

• Two Dimensional array


• Syntax - type var-name[ ][],
• E.g. int arr[][];

• Three Dimensional array


• Syntax - type var-name[ ][][],
• E.g. int arr[][][];
• Two dimensional Array
class TwoDArray {
public static void main(String args[]) {
output
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++) 0 1 2 3 4
for(j=0; j<5; j++) { 5 6 7 8 9
twoD[i][j] = k; 10 11 12 13 14
k++; 15 16 17 18 19
}

for(i=0; i<4; i++) {


for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
• String Class In java
• Java String length(): The Java String length() method tells the length of the
string. It returns count of total number of characters present in the String.

public class Example{


public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
Java String compareTo(): The Java String compareTo() method compares the given
string with current string.

public class StrCompareToExample {

public static void main(String args[]){


String s1="hello";
String s2="hello";
String s3="hemlo";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because
}
}
Java String concat() :
The Java String concat() method combines a specific string at the end of another
string and ultimately returns a combined string. It is like appending another string.

public class ConcatExample{


public static void main(String args[]){
String s1="hello";
s1=s1.concat("how are you");
System.out.println(s1);
}
}

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.

• public class StrIsEmpty {

public static void main(String args[]){


String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // 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 {

public static void main(String args[]){


String s1=" hello ";
System.out.println(s1+"how are you"); // without trim()
System.out.println(s1.trim()+"how are you"); // with trim()
}
}
Out Put :
hello how are you
hellohow are you
• Java String toLowerCase() : The java string toLowerCase() method converts all
the characters of the String to lower case.

• public class StringLowerExample{


public static void main(String args[]){
String s1="HELLO HOW Are You? ”;
String low=s1.toLowerCase();
System.out.println( low);
}
}
• Java String toUpper() : The Java String
toUpperCase() method converts all the
characters of the String to upper case.
• StringBuffer

• The java.lang.StringBuffer class is a thread-safe, mutable sequence of


characters.

• A string buffer is like a String, but can be modified.

• It contains some particular sequence of characters, but the length and content
of the sequence can be changed through certain method calls.

• They are safe for use by multiple threads.


• Every string buffer has a capacity.
• Pages saved in d drive of string folder .

• StringBuffer class methods (Read from Download Files )


class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
charAt( ) and setCharAt( )

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);
}
}

The output of this example is shown here:


I like Java!
reverse( )
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
delete() & deleteCharAt() method

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 Object is immutable StringBuffer Object is mutable

It is slower in the process of It is faster in the process of concatenation


concatenation

Requires more memory Requires less memory

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.

• Need of Wrapper Classes


• They convert primitive data types into objects.
• The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
• Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
• An object is needed to support synchronization in multithreading.
• Examples to use wrapper class

• Integer i1 = new Integer(42);


• Integer i2 = new Integer("42");
• Character c1 = new Character('c');

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

System.out.println("Values of Wrapper objects (printing as objects)");


System.out.println("Byte object byteobj: " + byteobj);
System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);
System.out.println("Character object charobj: " + charobj);
}
}
• Autoboxing

• 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

public class WrapperExample1{


public static void main(String args[]){
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a;

//autoboxing, now compiler will write Integer.valueOf(a) internally


System.out.println(a+" "+i+" "+j);
}
}
• Unboxing
• The automatic conversion of wrapper type into its
corresponding primitive type is known as unboxing. It is the
reverse process of autoboxing.

//Unboxing example of Integer to int


public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int explicitly
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
Vectors
• Vector class implements a growable array of objects .

• Vector implements a dynamic array that means it can grow.

• They are similar to ArrayList but Vector is synchronized.

• It extends AbstractList and implements List interfaces .


import java.util.*;
public class VectorDemo {

public static void main(String[] arg){

Vector v = new Vector();

v.add(1);
v.add(2);
v.add("geeks");
v.add("forGeeks");
v.add(3);

System.out.println("Vector is " + v);


}
}
Output
Vector is [1, 2, geeks, forGeeks, 3]
enumerated type
• an enumeration is used to define collection of constants.

• Enum improves type safety.

• Java enum is a special kind of java class .

• Enum can be traversed.

• Enum can have fields, constructors and methods.

• 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

• Java ArrayList class uses a dynamic array for storing the


elements.
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at
the index basis.
• In Java ArrayList class, manipulation is slow because a lot of
shifting needs to occur if any element is removed from the
array list.
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();

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.

2) ArrayList increments 50% of current Vector increments 100% means doubles


array size if the number of elements exceeds the array size if the total number of
from its capacity. elements exceeds than its capacity.

3) ArrayList is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized,


synchronized.
i.e., in a multithreading environment, it
holds the other threads in runnable or non-
runnable state until current thread releases
the lock of the object.

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

You might also like