Basics of Java


JAVA

JDK: Java development Kit for java development. This freeware can be downloaded from downloads.oracle.com.

Setup you PATH and CLASSPATH system variables. PATH should point to where java exits. It need to point to jdk\bin. So that java compiler and executable can be called from any directory.

CLASSPATH need to point to all those directories to search for classes. Multiple paths can be appended separating with semicolon. Once you set these two variables system need to restart to make them effective

 

“java -version” gives java version

JDK also comes with Jdev

Below are some basic concepts you should aware before coding in OAF

  • Coding/Naming standards
  • Classes
  • methods
  • datatypes
  • Access modifiers
  • Static and Final
  • looping and conditional statements
  • Basic seeded methods -like String methods  etc
  • Collection objects – arrays, hashmap etc
  • Packages
  • Type Casting
  • constructors
  • Exceptions
  • Extensions
  • JDBC

Naming conventions:

  • Package names in lowercase
  • Class names should be in CamelCase
  • Methods and variable names in mixed case starting with lowercase character
  • Constants will be in uppercase (EX: public final int MAX_COUNTER = 1) Note: final key word to define constants

Creating Java Classes and Methods

All Java coding will be structured as classes. Source code file name should be the same as class name and extension will be .java

On compiling source code, it creates executable having extension of .class

The structure of Java source code includes

import <packages>     //optional

<access modifier> class <classname>

{

<variables…>

<methods..>

}

HelloWorld.java Example:

public class HelloWorld

{

public static void main (String args[])

{

System.out.println(“HelloWorld”);

}

}

To compile… java HelloWorld.java

To execute… javac HelloWorld

Note: Classes having “main” method can only be executable. “main” in class should always be public static void and argument to this method will be always String array

Data Types:

int/long : for integer numbers

float/double : for decimals numbers

boolean : true/false

char : 1 character

String : Strings

Reference data types:

Arrays

Objects

Data type conversion:

String to numbers: Integer.parseInt(str)

String to double: Double.parseDouble(str)

String to Date: Date dv = new SimpleDateFormat(“dd-mon-yyyy”).parse(str);

Date d = new Date();

New SimpleDateFormat(“yyyy/MM/dd”).format(d);

int To String: Integer.toString(str)

Access modifiers:

JAVA_Basics_wk2

Creating and Accessing Methods

A class is set of variables and methods. A method is set of instructions that can perform a specific function. A class having “main” method will always be executable otherwise the methods of non-executable class can only be access from other classes based on their access modifiers

Note: non-static methods cannot be called directly from a static method even though they are in same class. Need to define object for that call and call the method

Math.java Example: 

public class Math

{

public int add(int i , int j)

{

return i+j;

}

public static void main (String args[])

{

Math math = new Math();

System.out.println(“addition = “+math.add(Integer.parseInt(args[0]),Integer.parseInt(args[1])));

}

}

Compile it… javac Math.java

Execute it… java Math 3 5

Static:

Static methods or variables are not instantiable. Static variables will be used to define common properties of a class that cannot be vary for object to object

A static method should be called with class name instead of object

A static method/variable cannot be referred from a non-static method

Looping and conditional statements

  1. For loop

Syntax: for (<initialization>;<condition>;<increment/decrement>) {}

  1. While loop

Syntax: while(Boolean){….}

  1. Do while loop

do {…. } while(Boolean)

Un-conditional control statements

break: terminate looping statement

continue: skips execution of remaining statements in loop and transfers control to beginning of loop

Conditional statement

if ( <Boolean>)

{…}

else if ( <Boolean>)

{…}

else

{…}

Packages: Packages are those used to group the classes. They refer to physical folders

EmpDet.java Example:

package wk1.emp;

public class EmpDet

{

private final int BONUS_PER = 10;

private int sal;

public void setSal(int psal)

{

sal = psal;

}

public double getBonus()

{

return (sal*BONUS_PER)/100;

}

}

Note: the package structure in above example wk1.emp should be physical folder structure that exists in current working directory and current working directory should be part of CLASSPATH

Make sure EmpDet.class file moved to folder wk1/emp/  (source file EmpDet.java should not be in current working directory so move it also to wk1/emp/ eventhough it is not required to execute or remove it)

You can use above class EmpDet and its methods from any other classes. Below is the example calling method of EmpDet class

CallEmpDet.java Example:

import wk1.emp.*;                           //this is the statement  to use methods of other classes

public class CallEmpDet

{

public static void main(String args[])

{

int sal = Integer.parseInt(args[0]);         //array index starts from zero

EmpDet empDet = new EmpDet();

empDet.setSal(sal);

System.out.println(“Bonus=”+empDet.getBonus());

}

}

Exceptions and Exception handling:

Exceptions can be system defined and user defined. They are the runtime errors. Any method or class can throw an exception. These exceptions can be handled using try{} catch{} blocks

SystemException.java Example: 

public class SystemException

{

public static void main(String args[])

{

int sal = Integer.parseInt(args[0]);

System.out.println(“Salary=”+sal);

}

}

Compile it.. javac SystemException.java

Execute it.. java SystemException           //this throws error because in above code we used args[0] and we are not passing parameter

Correct the code as below in SystemException.java to catch any system exception

public class SystemException

{

public static void main(String args[])

{

try{

int sal = Integer.parseInt(args[0]);

System.out.println(“Salary=”+sal);

}catch(Exception e){System.out.println(“Exception = “+e.getMessage());}

}

}

UserDefinedException.java Example: In below class setComm method is defined to throw an exception when sales is <10000

public class UserDefinedException

{

private int comm;

//when method throwing exception it should be declared to be thrown or exception should be caught

public void setComm(int sales) throws Exception

{

if (sales<10000)

throw new Exception(“Commission can not be given for sales less than 10000”);

else if (sales<20000)

comm=2000;

else

comm=5000;

}

public int getComm()

{

return comm;

}

}

CallUserDefinedException.java Example to call above method:

public class CallUserDefinedException

{

public static void main(String args[])

{

UserDefinedException ude = new UserDefinedException();

int sales;

for (int i=0; i<args.length; i++)

{

sales = Integer.parseInt(args[i]);

try {

ude.setComm(sales);

System.out.println(“Comm=”+ude.getComm());

}catch(Exception e)

{System.out.println(“Error=”+e.getMessage());}

}

}

}

OR you can code CallUserDefinedException.java as below

public class CallUserDefinedException

{

//this will throw exception message along with details from where the exception raised

public static void main(String args[]) throws Exception

{

UserDefinedException ude = new UserDefinedException();

int sales;

for (int i=0; i<args.length; i++)

{

sales = Integer.parseInt(args[i]);

ude.setComm(sales);

System.out.println(“Comm=”+ude.getComm());

}

}

}

Note: When we are using any method that throws an exception, we should either catch it throw it explicitly

Constructor:

Constructor is the method which will be executed at the time of object initiation.

Constructor will be on the same name of class.

They are used to initialize the object

Class can have multiple constructors but of different signature

Constructor methods will not have return type or void even though they will not return any value

Constructors.java Example:

public class Constructors

{

private int empno;

private int sal;

private String empname;

public Constructors()

{

empno = 0;

sal = 0;

empname = ” “;

}

public Constructors(int empno, int sal, String empname)

{

this.empno = empno;

this.sal = sal;

this.empname = empname;

}

public int getEmpno()

{

return empno;

}

public int getSal()

{

return sal;

}

public String getEmpname()

{

return empname;

}

}

UseConstructors.java Example:

public class UseConstructors

{

public static void main(String args[])

{

Constructors cons1 = new Constructors();

Constructors cons2 = new Constructors(1,10000,”Raju”);

System.out.println(“Values from 1st constructor = “+cons1.getEmpno()+”-“+cons1.getSal()+”-“+cons1.getEmpname());

System.out.println(“Values from 2nd constructor = “+cons2.getEmpno()+”-“+cons2.getSal()+”-“+cons2.getEmpname());

}

}

Extending Classes:

Extensions are inheritance of a class to another class. All public methods and variables of base class can be used in extended class. Also protected variables and methods can also use in extended class if it is in same package

This is most common while doing customizations in OAF. Seeded classes need to extend and add custom functionality

MarksBase.java Example

package wk1.students;

public class MarksBase

{

protected int min_marks = 35;

private final int MAX_MARKS = 100;   //final is the key word used to define constant

private int sub1;

private int sub2;

public MarksBase()

{

sub1 = 0;

sub2 = 0;

}

public MarksBase(int sub1, int sub2)

{

if (sub1>MAX_MARKS)

sub1 = 100;

if (sub2>MAX_MARKS)

sub2 = 100;

this.sub1 = sub1;

this.sub2 = sub2;

}

public int getTotal()

{

return sub1+sub2;

}

public String getGrade()

{

if ( (sub1<min_marks) || (sub2<min_marks) )

return “FAILED”;

else

return “PASS”;

}

}

MarksExtend.java Example

package wk1.students;

import wk1.students.*;                      //need to import base class

public class MarksExtend extends MarksBase  //extends is key work to do extensions

{

private int sub3;

public MarksExtend(int sub1, int sub2, int sub3)

{

super(sub1,sub2);       //super refers parent class. This will call constructor of parent class

this.sub3 = sub3;

}

public int getTotal()

{

//if any variable or method name is same for both child and parent, parent method will be referred with super.

return super.getTotal() + sub3;

}

public String getGrade()

{

//min_marks is protected in base class and can user here being extended class also in same pacakge

min_marks = 45;

if (super.getGrade().equals(“FAILED”) || sub3<min_marks)

return “FAILED”;

else

return “PASS”;

}

}

CallMarksExtention.java Example:

import wk1.students.*;

public class CallMarksExtention

{

public static void main(String args[])

{

int sub1 = Integer.parseInt(args[0]);

int sub2 = Integer.parseInt(args[1]);

int sub3 = Integer.parseInt(args[2]);

MarksExtend marksExtend = new MarksExtend(sub1,sub2,sub3);

System.out.println(“Total = ” + marksExtend.getTotal());

System.out.println(“Gradel = ” + marksExtend.getGrade());

MarksBase marksBase = new MarksBase(sub1,sub2);

System.out.println(“Total from base= ” + marksBase.getTotal());

System.out.println(“Gradel from base= ” + marksBase.getGrade());

}

}