Core Java

Lectures 12-18

public static void main (String[] args) {

System.out.println(“Echo !!!”);

} }

import java.lang.*                 //or java.lang.Math; by default

import java.util.*;

Import java.util.Random

class Abc {

int ia;                                 // instance var./data members

double da;

final int fia = 100;

static int isa;                         // Class (Static) data members

Abc(){...};                        //set of constructors

Abc(int i) { ... }

Abc(Abc oa) { .... }

public void Abc(){ .... }         // instance Methods

public static void SAbc(){ ..}         // Static Methods

}

        

public class StaticExample {

static int ia;

public static void main(String[] args){

System.out.println("In main method");

method1();

method2();

}

public static void method1(){

System.out.println( "method 1");

method2();

}

public static void method2(){

System.out.println( "method 2");

}

}

System.out.println("The square root of " + i + " is " + r + ".");

$ The square root of 5 is 2.23606797749979

System.out.format("The square root of %d is %f.%n", i, d);

$ The square root of 5 is 2.236067

static private BufferedReader br = new BufferedReader(new InputStreamReader (System.in));

String s = br.readLine();

// Parsing to get the desired data type. Parsing in java is similar to tokenizing in C.

int i = Integer.parseInt(s);

byte b = (byte(i); short s = (short)i;

Long lg = Long.parseLong(s);

double db = Double.parseDouble(s);

BufferedReader inStream = new BufferedReader(new FileReader(“abcd.txt"));

BufferedWriter outStream = new BufferedWriter(new FileWriter(“abcd.txt"));

        

        class Abc {

int ia;                    // instance (non-static) var./data members

double da;

static int isa;        // Class (Static) data members

final int fia = 100;  // not necessary to assign a value; one time assignment

Abc(){};

Abc(int i) { ... }     // many types of constructors / initializers

public void Abc(){ .... } // Non-static Methods

public static void SAbc(){ ..} // Static Methods

}

                                        

For example:-void fun(int x,int y):-arity of this function is 3.

typedef struct animal { . . . .} Animal;

Animal arr[2][2];

Class Animal { . . . .}

Animal[][] arr = new Animal[2][2];

1. instance initializers (also called instance initialization blocks)

2. instance variable initializers, and

3. Constructors.

Class Abc {

static int sa = 10;

static boolean flag = true;

}

Class Abc {

static int [][] arr;

}

How to initialize arr ?

static {

arr = new [?][?];

}

Class Abc {

int a = 10;

boolean flag = true;

}

Class Abc {

int [][] arr;

}

How to initialize arr ?

{

arr = new [?][?];

}

Class Abc {

Abc(…){ . . . }

}

1. No-Argument Constructor

2. Constructor with arguments

3. Copy Constructor

4. Default Constructor and Default Copy Constructor

5. Constructors : Pseudo Variables - this (…) and super(. . .)

 

Class Point {

private int x, y;

private int color=0;

Point(){x = 0; y = 0;} }

                Thumb Rule: Always define constructor with no arguments that initialises the

variables as we want, otherwise Java defines a default constructor that initialises

all the variables to its default initial values. Anything initialised by default may

cause problems.

EX 1:        Class Point {

private int x,y;

private int color = 0;

Point(int a, int b){

this.x = a;                 // this is a pseudo-var for current object

this.y = b; } }

EX 2:        Class Point {

private int x, y;

private int color;

Point(int a, int b, int c){

this (a,b);

this.color = c; } }

Point () { }  // this is equivalent to default constructor

 

Class Point {

private int x,y;

private int color = 0;

Point(Point P){

this.x = P.x;

this.y = P.y;

this.color = P.color } }

Point P1 = new Point(…)

Point P2 = P1;

Reference of P1 is copied in Java, though in C++, it will call copy constructor and if not defined it will call default copy constructor. In Java copy constructor is used as follows:

P2 = new Point (P1);

 

ColorPoint() { ColorPoint(0,blue);}

is compiled without inserting call to super

        Note: Methods don’t consume data space but only consume code space.

 Point P1, P2;         // assume Point has some references too.

  . . .                 // Initialize & Operate P1

 P2 = P1;

An assignment operator does Shallow Copy in C, by default.

Point P2 = P1; // assignment opr

Reference is copied in P2; this is neither Shallow nor Deep Copy.

protected Object clone () throws cloneNotSupportedException

public class Person implements Clonable {

private String name; //if immutable, no need to clone

private Date dob;

public Person Clone (){

Person p;

p = (Person) super.clone(); //within try-catch block

p.dob = (Date) dob.clone();

return p;

}}

outside the package in which the class is defined cannot access this class.

rules for floating points.

Class cannot be private, otherwise it is of no use if no one can access it.

 

or types of their parameters

e.g. if we have foo(double,double) and foo(int) then call foo(5,4) will do closest match and call definition foo(double,double).

public void move (int x, int y) { ... }

public int move (int x, int y) { ... }

e.g.         myPrint(int),myPrint(double),...

myPrint(int i, double d) { myPrint(i); …. ; }

myPrint (int i, Device d=printer) { … } //Device as a Default argument

Method Call:

myPrint(5);

myPrint(5,console);

Modifier

Overloading

(diff signature)

Overriding

(same signature)

Private

Yes

No( because it is not accessible to an inheriting class)

 Static  

(any access)

Yes

No(Overriding is in the context of objects and A static method belongs to the whole class)

Non-Static (non private)

Yes

Yes

final

Yes

No (not allowed)

Shape s = new Circle();

Circle c = (Circle) s;

Complex a, b, c;

.. .

a = b + c; // a = b.complex_add(c);

b = b + c * a;

c = a * b + complex(1,2);

returnType operator*(parameters);

class complex {

double re, img;

complex(double r, double i) {}

complex operator+(complex, complex);

complex operator*(complex, complex);

complex& operator=(complex, complex);}  //a=b, b is assigned to a and

reference of a is returned.

int Err_code = obj.do_something ();

throw <exception object>;

catch (<exception type> e) {

//statements that handle the exception }

class MyException extends Exception { }

class MyClass {

void oops(){

if { (/* no error occurred */)

/* normal processing */ }

}

else {

/* error occurred */

throw new MyException();

}

     }

}

public int computeFileSize() throws IOException, ArithmeticException

throw new TheException();

TheException ex = new TheException();

throw ex;

Example:

/** Set a new radius */

public void setRadius(double newRadius)

throws IllegalArgumentException {

if (newRadius >= 0)

radius = newRadius;

else

throw new IllegalArgumentException(

"Radius cannot be negative");

}

try {

statements; // Statements that may throw exceptions

}

catch (Exception1 ex1) {

handler for exception1;

}

catch (Exception2 ex2) {

handler for exception2;

}

...

catch (ExceptionN ex3) {

handler for exceptionN;

}

try {

statements;

}

catch(TheException ex) {

perform operations before exits;

throw ex;

}

class exc0{

public static void main (String args[]) {

int d=0;

int a=4/d;

}

}

Output: java.lang.ArithmeticException: / by zero at exc0.main(exc0.java:4)

catch(ArithmeticException e) {

System.out.println(“Exception: “+e);

}

unreported exception java.io.IOException; must be caught or declared to be thrown

try {
 System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}

Could be replaced by:
if (refVar != null)
   System.out.println(refVar.toString());
else
     System.out.println("refVar is null");
        

        

        

                      assert sum > 10 && sum < 5 * 10 : "sum is " + sum;

public void setRadius(double newRadius) {
   assert newRadius >= 0;
   radius =  newRadius; }