JAVA Training

Following are the notes of JAVA Training at IBM by Prof. Sandeep

Index :

 


What is a Software? ->Set of instructions which turns imaginary things into realty.
What are the types of software’s?

3 types of Software’s

  1. System software – Link between hardware’s Eg: Operating System
  2. Application software – 1.StandAlone App – Cannot share the data/Only for one machine/No link with server 2.Distributed App – Data can b shared through network. We use JAVA,DOT NetInternet software
  3. Internet Software’s

History of JAVA

  • Java was introduced in the year 1991 with the name of oak.
  • After 4 to 5 years of modifications it named of java in 1995.
  • James gosling is known as Father of java
  • Started with respect to sun microsystems and in 2007 it was handled to oracle corporation.

Versions in JAVA –

  • Java has 3 api’s j2se,j2ee,j2me. 2 stands for version. when java 2nd version is released it is named as j2se.java 8 version is used now.since now we are using java8 again 2 is removed from the notations

JSE->Core java. JEE->Advanced. jvm ->platform independent dotnet->recently dotnEt supports it recently platform independence.

CORE JAVA

Importance of core java:: Celinium testing. Informatica related to database technologies Features of java::

  1. SIMPLE:->no address concept here.ex:photograph.
  2. SECURE:->i.username and password,hackers ii.biometrics
  3. Dynamic:->run-time calculation.
  4. Platform independence:with different os.
  5. Robust:because of exception handling.
  6. Architecture neutral: client server architecture :: :in case of 2 tier we have only client and server.Ex:www.google.com. :in case of 3 tier server maintains relationship with database.ex:facebook,flipkart,authentication etc :in case of n tier architecture we have firewalls. All the 3 tier must be n tier?true or false? Ans:sometimes yes and sometimes no; ex:youtube,flipkart.Web services have 2 architectures: 1.soap 2.restaful
  7. High performance:because of pointers performance is high compared to c and c++..
  8. Multi threading:in case of java for each an every program JVM provide 2 threads internally .1.foreground thread  :::it is used to execute the business logic what we have written. .2.background thread :::it is used to monitor the status of foreground thread.
  9. Networked:.
  10. Interpreted:in case of memory allocation it is differnt from compiler but not line by line since both of them execute line by line WORA->write once run anywhere and anytime
  11. Distributed:
  12. Portable. transfer files .class files to another machine we will get output. In 2 different machines with same OS.combination of a.n and platform independence.
  13. OOPS/OOPL::java is object oriented language which supports all the features of object oriented programming structure

In case of object oriented it supports all the concepts. object based only some concepts. ex:c++ PRINCIPLES OF OOPS::

  1. Object::instance of a class.                                                                                                  ]ex:car,tree whenever an object is created for a particular class memory space will be created at that time called an instance..  ]
  2. Class::collection of objects which share common state and behavior Class is a collection of data members,objects,constructers,methods.A
  3. Abstraction: door.
  4. Encapuslation:::combinng data and code together ex:atm:based on requirement we will be using the program.we have 15 functionalities in ATM.and we are combining everything together called encapsulation which is nothing but cobing data unit together
  5. Inheritance:methods and variables are inherited. i.single (one parent and one child class). ii.multiple(two parents one child). iii.multilevel(intermediate sub classes) iv.hierarchical(one parent many child). v.hybrid(combination of more than one).
  6. Dynamic binding:::the process of binding APPROPRIATE VERSIONS of derived classes which are inherited from base class with respect to base class object.
  7. Polymorphism:;one entity showing multiple behaviours.the process of representing one form in multiple forms.here one form represents ORIGINAL methods.multiple forms represent OVERRRIDEN methods.state of existance of a method is called form.method is group of statements to perform a task;each and every line we write is called a statement;
  8. MESSAGE PASSING:

Sample Structure class <classname> { variables; methods() { business logic; } public static void main(String args[]){ object creation// calling tthe methods } } DATA TYPES How many data types we have??? we have three types of data types we have.A 1.primitive 2.derived 3.user defined data types which is used to allocate sufficient memory  for the variables in main memory. primitive:: Path – Copy link –> Open MyComputer –> Properties –> System Path –> PATh Through CMD  –

Method declaration Method Types:

  • Instance Method : returnType methodName(Parameters);
  • Static Method : static returnType methodName(Parameters);

Method Declarations:

  1. No return type – No parameters  : void <MethodName> () Ex: void example ( );
  2. Return type – Parameters : <ReturnType> <MethodName> (<parameters>) Ex: int example( int arg1,int arg2);
  3. No return Type – parameters : void <MethodName> (<Parameters>) Ex: void example(int arg1,int arg2);
  4. Return Type – No Parameters : <ReturnType> <MethodName> ()

Program :

class test
{
void display()
{
int a=10;
System.out.println(“The value of ‘a’ is ” +a);
}
public static void main(String[]args)
{
test t = new test();
t.display();
}
}
Compile: javac test.java java test OUTPUT – The value of ‘a’ is 10

“”Display is the method called with respect to T . where T is the object of test class, control goes to test class looking for the existance of the display method and execute statements in display method””

Passing a method with parameter

class test
{
void display(int a)
{
System.out.println(“The value of ‘a’ is” +a);
}
public static void main(String[]args)
{
test t = new test();
t.display(10);
}
} javac test.java java test OUTPUT – The value of ‘a’ is 10

METHOD OVERRIDING

  • Method declaration should be same 
  • Signature must be different
class Sugar
{
void display()
{
System.out.println(“I am from sugar class”);
}
}
class child extends Sugar
{
void display()
{
System.out.println(“I am from child class”);
}
public static void main(String[]args)
{
child c= new child();
c.display();
}
}

Compile : javac Sugar.java java child Output :I am from child class NOTE – CHILD coz main is in child class

With super

class Sugar
{
void display()
{
System.out.println(“I am from sugar class”);
}
}
class child extends Sugar
{
void display()
{
super.display();
System.out.println(“I am from child class”);
}
public static void main(String[]args)
{
child c= new child();
c.display();
}
}

javac Sugar.java java child Output : I am from Sugar class I am from child class

METHOD OVERLOADING

class loading
{
void load(int a,int b)
{
int c=a+b;
System.out.println(c);
}
void load(int a,int b,int c)
{
int d= a+b+c;
System.out.println(d);
}
void load(float a,float b)
{
float c = a+b;
System.out.println(c);
}
public static void main(String[]args)
{
loading l = new loading();
l.load(10,20);
l.load(10,20,40);
l.load(10.10f,20.20f);
}
}
Compile: javac loading.java java loading Output 30 70 30.300001

CONSTRUCTORS
  • Above, In Loading is class name load is method name, both different but if class name and method name Is Same then it is constructor.
  • No return type

2 Types :

  1. Default
  2. Parametrized
Default constructor Example: class Sum

{ Sum()//constructor { System.out.println(“I am from default Constructor”); } public static void main(String[] args) { Sum S= new Sum(); } }

Compile : javac Sum.java java Sum Output – I am from default Constructor

Ex 2: Next Program we use void method

class Sum
{
Sum()//constructor
{
System.out.println(“I am from default Constructor”);
}
public static void main(String[]args)
{
Sum S= new Sum();
S.method();
}

void method()
{
System.out.println(“Hi”);
}
}

Output: I am from default Constructor Hi Default constructors

  • Used to place null values into our constructors
class Test1

{ int a; void value() { System.out.print(a); } public static void main(String[]args) { Test1 t=new Test1(); t.value(); } }

Output = 0

Parametrized Constructor

class Test1
{
Test1()
{
System.out.println(“I am from default contructor”);
}
Test1(int a)
{
System.out.println(“I am from parametarized contructor”);
System.out.println(“The value of a”+10);
}

public static void main(String[]args) { Test1 t=new Test1(10); } }

Output = I am from parametarized contructor the value of a 10

Next prog

class Test1
{
Test1()
{
System.out.println(“I am from default contructor”);
}
Test1(int a)
{
System.out.println(“I am from parametarized contructor”);
System.out.println(“The value of a”+10);
}
public static void main(String[]args)

{ Test1 t=new Test1(10); Test1 t1 = new Test1(); } }

I am from parametarized contructor The value of a 10 I am from default contructor

New EX – Using global values and checking output for Default and Para Constuctors , how they differ

class Test1
{
int a;
int b;
Test1()
{
System.out.println(“I am from default contructor”);
}
Test1(int x,int y)
{
a=x;
b=y;
int c=a+b;
System.out.println(c);
}
public static void main(String[]args)
{
Test1 t=new Test1();
System.out.println(t.a);
System.out.println(t.b);
Test1 k=new Test1(10,20);

System.out.println(k.a); System.out.println(k.b);

}}

OUTPUT : I am 0 0 30 10 20

Therefore we see that default values are place for Default constructor but in Parametrized constructor own values are placed

In default C in will place default null values in para C we can place our own values.

Abstract Class

  • Are the combination of defined methods and then undefined methods(Abstract Methods)
  • To make Abstract we use Abstract keyword
  • Syntax – Abstract Returntype methodName (parameters)
  • Is defined inside the method but we have to make he class also Abstract

creating POEL Plain old execution logic

Directly it is not possible to create object of Abstract class but we can create indirectly using references, that we call it as “Dynamic Binding” In case of Dynamic Binding we have to consider 2 things 1:Type – used for checking that existence of method 2:Reference – Used for executing the method AGAIN “”Display is the method called with respect to T . where T is the object of test class, control goes to test class looking for the existence of the display method and execute statements in display method””

Abstract class and concrete class
abstract class Abst { abstract void display();
}
class Ab extends Abst {]void display()
{
System.out.println(“Abstract class”);
}
public static void main(String[]args)
{
Ab a = new Ab();
a.display();
Abst b = new Ab();
b.display();
}
}

Output: Abstract class Abstract class

Because both the classes are calling same class AB

  • 1st – “”Display is the method called with respect to A . where A is the object of abst class, control goes to abst class looking for the existance of the display method and execute statements in display method””
  • 2nd – “”Display is the method called with respect to B . where B is the object of Abst class, control goes to Abst class but reference is given to Ab class therefore looking for the existence of the display method in Ab class and execute statements in display method””

An obj on Abst class is equal to obj of that class which extends that abstract class.

Use of This

class same
{
int a;
int b;
void th(int a,int b)
{
this.a=a;
this.b=b;
int c= this.a+this.b;
System.out.println(c);
}
public static void main(String[]args)
{
same t = new same();
t.th(10,20);
}
}
Output – 30

Interfaces

Code Example
interface i1
{
void sum();
}
interface i2 extends i1
{
void sub();
}
class c1 implements i2
{
int a=10;
int b=20;
int c;
public void sum()
{
c=a+b;
System.out.println(c);
}
public void sub()
{
c=a-b;
System.out.println(c);
}
public static void main(String[] args)
{
c1 a= new c1();

a.sum();
a.sub();
i1 b= new c1();
b.sum();
i2 c=new c1();
c.sum();
c.sub();
}
}

Compile
Javac i1
java c1

Output:
30
-10
30
30
-10

Packages

Compiling of Packages

javac -d . filename.java
java packagename.classname

 

Threads

  • Flow of control of a program is Thread.
  • In thread based application context switching is less.
  • In order to make internet applications c,c++ are not suitable as they are process based.

==========================================================================
Whenever u are creating object of thread class (is also known as creating a thread) that will be NEW state and it is about to enter main memory.

In READY state memory space will be allocated to the thread and it is waiting for the CPU call for the 1st time.

RUNNING–> Now the thread is under the control of CPU

java.lang.thread
java.lang.runnableinterface
==========================================================================

3 APIs =====> public static final int MAX-PRIORITY –> 10
MIN-PRIORITY  –> 1
NORM-PRIORITY  –> 5

NORM-PRIORITY is default.

==========================================================================

Constructors is Thread
———————–

1. Thread()
2. Thread(String)
3. Thread(Runnable)
4. Thread(RunnableString)

In case of 2nd one we can give a name to the thread but we cant do that for the 1st one.
For 3rd Converts runnable objects into thread objects.
For 4th 3rd + we can give a name to the thread.

==========================================================================

Instance Methods
—————-

setName(), getName(), setPriority(), getPriority(), suspend(), resume(), wait(), start(), run(), join(), isAlive()

only run() method is NOT final. As we have to write the business logic inside the run() method.

Static Methods
————–

sleep(long milisec)
currentThread()

==========================================================================

Some Examples on Thread:
Ex1 :

import java.lang.Thread;

class ThDemo extends java.lang.Thread
{
public static void main(String[] args)
{
Thread t = new Thread();
System.out.println(t);
t.setName(“ABC”);
System.out.println(t);
System.out.println(“Is it Alive ?\n ” + t.isAlive()); //false
Thread t1 = new Thread();
System.out.println(“Is it Alive ?\n ” + t.isAlive()); //false
System.out.println(“Default name of Thread= ” +t1.getName());
}

}

Compilation and Output
C:\Users\IBM_ADMIN\Desktop\Core  Java>javac Thread.java
C:\Users\IBM_ADMIN\Desktop\Core  Java>java ThDemo
Thread[Thread-0,5,main]
Thread[ABC,5,main]
Is it Alive ?
 false
Is it Alive ?
 false
Default name of Thread= Thread-1

1. Java program starts execution.

2. Class will be loaded by loader sub-system into main memory.

3. JVM creates one background thread.

4. Background thread creates n no. of foreground threads.

5. Background thread dispathes  each and every foreground thread on order to the respective run() methods.

6. Foreground will execute the business logic written in run() method and gives the result to background thread.

7. Foreground thread are collected by garbage collector since they are unreferenced.

8. Background thread displays the output to the console(or programmer or client).

9. Garbage collector collects background thread since it is unreferenced.

10. Java program termination.

==========================================================================

==========================================================================

Synchronization

The process of allowing one thread among multiple threads into the sharable area in order to perform write operations.

In order to make any method as synchronized we have to mention the keyword. Synchronization is applicable for both static and instance methods wrt to synchronized keyword.

For instance methods object will be locked.
For static methods class will be locked.

==========================================================================

 

Exception-Handling

EXECEPTION HANDLING

  • Errors which will come at compile time and exceptions occur at run time.
  • Errors and exceptions must be handled by the programmer .

Types of errors

I. Compile time (syntactical errors).

ii. logical.

Iii.run time.

Without exception handling system defined error messages .

Arithmetic exception

with exception handling user friendly exception

dividing by zero does not give correct value

There are two types of exceptions.

1.user-defined

2.pre-defined

Synchronus

Asynchronus(error)

Synchronus

1.checked 2.unchecked

  • class not found Arithmetic exceptions
  • File not found number format
  • interrupt exceptions parse only interger values

stack overflow

  • super class is java.lang.exception
  • Asynchronous are the system generated exceptions
  • EX:Force shut down,windows not responding,file already exists etc.

Blocks of exception handling

1.try:

  • It must contain those statements which causes problem at run time
  • If any exceptions raised in try block then control will execute appropriate catch block.
  • If any exceptions raised in try block remaining statements will not be executed

2.catch:

  • This block generally used to generate user friendly messages
  • IT is highly recommended to write n number of catch blocks.
  • At a particular instance of time JVM will execute only 1 number of catch block in number of catch blocks
  • After executing appropriate catch block even if we use return statement control never goes to try block

3.finally:

  • It is used to relinquish the resources. Whatever we write in this block it will execute irrespective of try and catch blocks. It is optional block.
  • We should not write any statements between try,catch and finally blocks. Otherwise error will come.

4.throws:

5.throw

  • Gives indication developer to write 1method declaration with throw and another method with TRY-CATCH blocks.

 

 JDBC

TomCat server – Provide implementation as JAR files.
IBMs server – WebSphear
class filename(“)

Steps to establish JDBC connection

  1. Load the Driver
  2. Connection
  3. Statement
  4. Query
  5. Close

Let us see all the steps in detail:

Step 1 –

Step2 – Connection
Create class DriverManager getConnection , return type is Connection.
Parameters URL, UserName ,  Password
URL = JDBC:

Step 3 – Statements – 2 Types

  1. PreparedStatement
  2. CallableStatement

CrateStatement is used

Step 4 –

  1. Execute –  (Return type – Boolean)
  2. Execute update – For updation , (Return type – INT)
  3. Select – for * execute query (Return type – resultset)

Executiion
javac
select * from student
drop
select * from student
table does not exeist

Wednesdays Lec Notes

IMG_20150909_172859410 IMG_20150909_172907051 IMG_20150909_172912232 IMG_20150909_172926089 IMG_20150909_172931540 IMG_20150909_172842317 IMG_20150909_172851663

 

Servlets

Steps

  1. Install oracle DB, apache tomcat
  2. Set Path
  3. Right click on My Computer –> Properties –> Advanced System Settings –> Environment variables and change the following
    path
  4. Create a folder and their sub-folders in the following manner
    C: ProjectName

    1. WEB.INF
      •            lib – save .jar files here
      •            src – save .java files here
      •            classes  – save .class files here
      • web.xml
    2. html
    3. jsp
  5. Type the following code in your notepad and save the .java file in src folderimport java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class welcome extends HttpServlet
    {
    public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
    PrintWriter pw=res.getWriter();
    //res.getcontentType();
    pw.println(“hi welcome to servlet”);
    }
    }
  6. Compile it, it will generate a .class file(in the src folder).Cut and Paste this .class file into the ‘classes’ folder
  7. Goto Apache Tomcat –>lib –> servlet-api.jar, Copy this file into the ‘lib’ folder
  8. Write the following code in web.xml
    <web-app>
    <servlet>
    <servlet-name>ss</servlet-name>
    <servlet-class>welcome</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ss</servlet-name>
    <url-pattern>/wc</url-pattern>
    </servlet-mapping>
    </web-app>
  9. Copy the entire folder(ProjectName) and paste it into Apache tomcat –>WebApps
  10. Goto Apache Tomcat –>Bin –> Startup.batCheck for the msg INFO: Deploying web application directory ProjectNameGoto Mozilla and enter the following URL http://localhost:8000/ProjectName/<URLpattern in XML file>
  11. Hurray!!! There it is, Your output
  12. OutPut : hi welcome to servlet

Leave a Reply

Your email address will not be published. Required fields are marked *