Sunteți pe pagina 1din 18

Java is: Object Oriented, Platform independent, Simple, Secure, Architectural- neutral, Portable, Robust, When we consider a Java

program it can be defined as a collection of objects that communicate via invoking each others methods. Object-oriented Programming (OOP) is a Programming language model, organized around "objects" rather than "actions", and data rather than logic. Object Oriented Programming solves three main software engineering goals: Re-usability Flexibility Extensibility Object - Objects have states and behaviours. Example: A dog has states-colour, name, breed as well as behaviours -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describe the behaviours/states that object of its type support. A class is a template for multiple objects with similar features. Classes embody all the features of a Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instant Variables - Each object has its unique set of instant variables. An objects state is created by the values assigned to these instant variables. There are no Global Variables in java. We cant declare any variable outside the class... Oops concepts are... 1)Encapsulation- Wrapping up of data and method into single unit. Ex: Class 2)Inheritance- Inheriting the properties from super class to sub class 3)Abstraction- Making using of useful data and hiding unnecessary data 4)Polymorphism The ability of reference variable to change behaviour acc to what object instance it is holding. This allows multiple objects of different subclasses

4 April

How to write method --- Using Syntax Calss <class name>{ <instance variables> <method> }

Method----<return type> <m-name> ([parameter]){ <logic> }

5 April
Object creation: Student s = new Student(); s is the object reference new operator allocates memory to the static members of the class new Student()- creates an object this process is called instantiation s is the reference stored in stack memory the instance variables values are sotred in heap memory s stores the refernce address of instance variables instance variables dont have any garbage values when ever they are declared they are initialized with default values like for int 0 float- 0.0 boolean-false String-null Constuctor is a spl type of method it should have same name as that of class name there is no return type if there is no Constructor given by user java compiler creates a default constructor if user creates constructor he can give his default values the for each object Two types of Constructor 1.defult- it doesnt have any arguments 2.parameterised- have arguments Cretaion of Constructor //Default Constructor Student(){ sID = -1; sName = satya sub1 = -1; sub2 = -1; } Student s = new Student(); Constructor is used to initialize instance variables with default values with default constuctor //Parameterised Constructor Student(int id, String name, int s1, int s2, int s3){ sID = id;

sName = name; sub1 = s1; sub2 = s2; sub3 = s3; } Student s = new Student(11,satya,67,89,90);

Constuctor Overloding Writing more than one constructor in 1 class. We can write any no of constructors Compiler can differentiates them basing on the parameters If you write parameterised constructor and create object for default constructor then it shows an error java compiler does nt create default constructor. If u wrtie Parameterised Constructor we should create its object If any of the constructor is written and another constructor is nt written jvm do not create defult constructor it shows an error

We cant call constructors from methods we can call it using this keyword

this Keyword 1. it is used to differentiate local & instance variable wen they have same name 2. 'this' refers to instance variables(Current object) 3. to call constructor of class from other constructor 4. 'this' keyword should be used as 1st statement Usage of this These must be as 1st statement in a constructor this(); --->to call default constructor this(10); --> to call parameterised consturctor These must be as 1st statement in a method this.i; --> to call instance member this.diaplay(); --> to call method

8-April Data Types in Java: Data types are used for representing data values in the memory 1.Integer Data Type: a. Int (default value = 0 , size - 4) b.byte (default value = 0 , size - 1) c.short (default value = 0 ,size - 2) d.long (default value = 0 , size 8) 2.Character Data Type: char(default value = /) 3.Boolean Data Type: boolean (default value = False) 4.Float Data Tpye: a.float (default value = 0.0) b.double (default value = 0.0)

Variables in Java: A Variable is an identifier whose value changes during the execution of a program Two type of variables 1. Global variables a. Instance variables (non-static) b. Class variables (static) 2. Local variables Instance variables: The variables which are declared inside the class and Local Variable : The variable which are declared inside the method. They cant be used unless they are initialized.

9-April Things covered : Getting started with java oops basics Identifiers, keywords, data types control flows class design Array Access Specifier

Things to be covered: advance class features Array: collection of similar data types int n1,n2,n3,......n10 int num[] = new num[10]; uses creating arrays- they are stored in continous memory by this ur program exectuion gets faster how to create static array in java syntax: int num[] = new num[10]; Or

int[] num = new int[10]

whenever new is used- compiler allocates memory in the Heap Array is Object in java Memory allocation Stack Memory Heap Memory num index---- 0 1 2 3 4 5 6 7 8 9 initial values -----0 0 0 0 0 0 0 0 0 0

local variable should be initialized before it is used int iValue[] ---------> creating array reference in Stack iValue = new int[10] ------> creating new array object in Heap int[] iValue; int iValue[]; int []iValue[]; []int iValue[];

How to initialize array: iValue = new int[10]; iValue = {1,2,3,4,5,6,7,8,9}; ----- U r creating array of 9 elements with values These are all arrays of primitive data types can we create array user defined data types? Yes Ex: class emp(){ int eno; String enum; } p s dispaly(){

sop(eno, ename); } emp emplist[] = new emp[10]; emplist[0].dispaly(); if we ru this project we will get NullPointerException ' emp emplist[] = new emp[10]; ---- this is collection of ten employee references Inorder to run this program U need to initialise all references of employee emplist[0] = new emp(); emplist[0].eno = 10; emplist[1].ename = satya Memory emp emplist[] = new emp[10]; Stack Heap emplist index--emplist[0],emplist[1],emplist[2],emplist[3],emplist[4],emplist[5] value-----null null null null

null

null

Syntax for creating non-rectangular array or multi-dimensional array ilist[][] 1st[] --- Represents no of columns 2nd[] --- Represents no of rows int iList[][] = new int[5][]; Create this using non-retangular array 1 0 0 2 3 4 5 6 5 6 8 9 11 12 12 23 23

package com.satya.data; import java.util.Scanner; public class TwoDimensionalArray { public static void main(String[] args){ int[][] twoDim = new int[5][];

//declaring two arrays twoDim[0] = new int[2]; twoDim[1] = new int[3]; twoDim[2] = new int[3]; twoDim[3] = new int[4]; twoDim[4] = new int[5]; //intializing the array Scanner sc = new Scanner(System.in); int k = 1; for(int i = 0 ; i < twoDim.length; i++){ for(int j = 0;j<twoDim[i].length; j++){ System.out.println("Enter numbers" + k + ":"); k++; twoDim[i][j] = sc.nextInt(); } } //reading arrays for(int i = 0 ; i < twoDim.length; i++){ for(int j = 0;j<twoDim[i].length; j++){ System.out.print(twoDim[i][j]); } } } } You cannot resize an array. You can use the same reference variable to refer to an entirely new array, such as: int[] myArray = new int[6]; myArray[0] = 2,myArray[1] = 2,myArray[2] = 2,myArray[3] = 2,myArray[5] = 2 myArray = new int[10]; myArray[6] = 2,myArray[7] = 2,myArray[8] = 2,myArray[9] = 2,myArray[10] = 2 for(int i : myArray) sop(i) O/p 0000022222 Enhanced for loop: int[] i = {1,2,3,4,5}';

Syntax: for( int element: i) i ---- dynamic or static array that we want to read two dimensional int[][] evalues = new int[4][]; for(int i[] : evalues) for(int j : i) sop(j) }

10-April Access Specifier 1.Private ---> Private members are nt inherited. Scope of this member is inside the class it cant be accesed outside the class 2.Public ---> Universal scope, it can be accessed anywhere. If ur class is public u must save the file with same class name If in a file there are 3 clasess then we should save the file with class name that has public. and if u compile that file, compiler will create 3 .class files but, the class with public has the scope to access outside the package, for the remaining two classes we cant create an object outside the package as they are not declared as public. Note: Never write two or more class in a single file 3.Protected ---> it is avaible within in the sub class in all packages 4.Default ---> it is availble within the smae package. Diff bte public and default public is available in all package default is available in the same package if u dnt specify any access specifier then the default specifier is default Pass by Value Pass by Reference Note: java always uses pass by value as an argument Casting: Implicit

Explicit Implicit EX: int i = 4; flaot f = i; Explicit Ex: float f = 5.34; //int i = f; int i = (int)f

11-April
Polymorphism: One thing many forms Super class reference variable can refer any of its subclass object is called as Polymorphism but it can access only member functions and variables that are present in the super class virtual method invocation late binding Note: Super class reference variable cant refer to the member functions and vairables of the sub class functions and variables which are not part of super class. For the method in super class we are not creating any object and making use of the method in it but i should make use of in order to perform polymorphism, but still there is a chance to create an object for the super class and call the method, so inorder to avoid that i make that method as ABSTRACT. Abstract method says that, it doesnt have any body or implementation Now we cant make use of this method and so we should not be able to create an object for that class so keep that class as ABSTRACT CLASS

12-April
Any class in java is sub class of object class The methods in Object class are toString() getClass() equal() hashCode() notify() notifyall(); wait()

for any class we must override toString() and equals() method.

Finalize Method: Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. protected void finalize() throws Throwable {} every class inherits the finalize() method from java.lang.Object the method is called by the garbage collector when it determines no more references to the object exist the Object finalize method performs no actions but it may be overridden by any class normally it should be overridden to clean-up non-Java resources ie closing a file if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize(). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class protected void finalize() throws Throwable { try { close(); // close open files } finally { super.finalize(); } } any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored finalize() is never run more than once on any object Forcing JVM for Garbage Collection is never possible we can just request it even then if it is free it will call GC. Design Pattern:(Search in google)

Wrapper Classes In java we have 8 primitive data types in order to represent these 8 data types in object we uses classes called wrapper class Primitive Wrapper Class Int Integer byte Byte short Short long Long

float double boolean char Ex:

Float Double Boolean Character

Integer iObj = new Integer(10); Integer iObj1 = new Integer(10); If we want to add these two objects, then iObj.intValue() ---- > returns 10 ---> this is nothing but taking the value of primitive type Boxing, Unboxing, Autoboxing , AutoUnboxing Boxing: Converting primitive into its relevant object is called boxing ex: Integer i = new Integer // boxing Converting object into its relevant primitive is called Unboxing ex: int ivalue = i.intValue(); //unboxing In JDK 1.5 autoboxing,autounboxing are introduced If compiler takes care of converting primitives into object or objects into primitives it used autoboxing or autounboxing Ex: Boolean ans = new Boolean(true); if(ans){ //ans ----> should take only boolean primitive // do something; } actually we passing 'ans' as object but it should take only primitive type so we need to convert it. This code will give u an error i.e compile time error{Required Primitive Data Type] if u run using versions before JDK 1.5 but if u run on JDK 1.5 it will work because it converts into relevant object or primitive type This is example of AutoBoxing ---->Converting Primitive into relevant Object Ex1: int i = 40; float f = 4.5f; ArrayList list = new ArrayList(); list.add(i); //list can add only objects but we are passing primitive type as ar argument. Here compiler converts this primitive into object list.add(f); This is example of AutoUnboxing --->Converting Object into its relevant primitive

13 April
Interface: there are some uncommon objects like bird,aeroplane,superman and one common behaviour indirect relationship is there between each of these objects to provide common platform for uncommon objects is called interface. Bird is an animal which can fly Aeroplane is an vehicle which can fly Superman is an human who can fly Bird is a flyable animal Aeroplane is a flyable vehicle Superman is a flyable human flyable ----> adjective In ur reruirement specification u have to create adjective as interface. Interface is a class like strcuture with keyword interface ex: public interface <interface main>{ // public static final variables; // abstract methods } why only abstract methods? Just to give presentation and implementation of the method can be done in their sub classes. What are the methods there in interface should be overriden by the class which uses that interface. U cant create object for interface but it's can be used same as class reference. U can extend interface also. Static Initializer: Before constructor we can create to other blocks like static Initializer and non-static initalizer So, we can say class is a collection of variables,methods,constructor,static initializer,non-static initializer Class{ //class structure static Initializer non-static Initializer constructor methods variables

} static initializer is used to initialize all static variables non static vice-versa it will be invoked once no matter how many objects we create non-static will be invoked how many times the object is created. Static{ y = 20 ------> Static Initializer syntax //static intializer } { x = 20 //non-static initializer } ------> Non-Static Initializer syntax

Static Import:

16April
Exception Handling: When an exception is generated, it is said to be thrown Errors: compile time error / syntax error logical error run time error whenever exception occurs in ur program, the application will terminat abnormally. It will also gives an abnoraml error msg. That is y we should handle that exception and should provide a reasonable error msg. What is happening: if exception is raised in ur heap area one object gets created. When jvm finds unhandled object in heap ur application will terminate. Throwable it has 2 sub classes 1. Error 2. Exception Error: ex--> if ur jvm gets sppiled u can't handle then ur application gets terminated When an exception is thrown, an exception object is created and passed to the catch block much like an parameter to a method occurrence of an exception generates an object (an instance of a class in the exception hierarchy) containing information about the exception the exception object is passed to the code designated to catch the exception, which may then use methods of the exception object to help handle the situation

There is an API class called Exception All exception classes inherit from Exception, which inherits from Throwable another class, Error, also inherits from Throwable Your code must handle most exceptions, but generally should not attempt to handle Error subtypes (likeOutOfMemoryError or StackOverflowError) RuntimeException is a subclass of Exception that is a base class for all the exception classes that you are not obligated to handle, but still might want to anyway (examples are ArithmeticException, from dividing by zero, NullPointerException, and ArrayIndexOutOfBoundsException) Exception: 1.try 2.catch 3.throw 4.throws 5.final in Java we can handle exception using only 1 mechanism i.e trycatch

Ex: num1 = 10; num2 = 0; it throws a Arithmetic exception in heap.

Now we need to handle this exception. Using throw u can raise explicit exception but u cant handle the exception, it can be handled by using try and catch only. Throw : declare exception at class level we can declare exception by using ----> throw we will handle exception using ----> try and catch we have handle exception at application level we have to declare exception at class level never handle exception in class level, do it in application level 1.Checked Exception 2.Unchecked Exception

exception handling process 1.create the exception 2.throw the exception 3.declare the exception 4.handle the exception

Collection: Limitations of Arrays: Array is fixed in size. Suppose if u create array of 100 elements and ur want to use only 10 elements the remaining memory space is wasted Arrays are by default homogenous Requirement of dynamic arrays in java is done by using COLLECTIONS it is part of java.util package not all the classes of this package represent collection only some classes, intefaces, are grouped as collections Collection Interface By default Dynamic Array is hetrogenous. Dynamic Arrays means Objects ---> u can store any kind object they cant work with primitives we will accept value as primitive but we convert them into primitive object and store

17April

whenever a dynamic array is created Stack mylist Heap ArrayList 12 Date() Satya 11.9

when any of the element is removed t Comparable and comparator

18April Collection framework:


diff btwn arraylist and vector. Vector is synchronized Assume u have one resourse. U can add or remove or Synchronized Three thread can access one resourse at a time but there is a chnace of

Generics:

19April
Multi-Threading: U can produce how to design java app which can perform multi tasking Process: some task. Thread: some task. Two constructors of thread are Thread() Thread(Runnable r , String name) One class with 2 functions generateNumber() generateAlphabets() Whenever u create a Java Apllication every main method is a thread which is called as MAIN THREAD

Never create Thread which extend Thread class use implements runnable Thread based search engine

26April JDBC Three tier Architecture Database Drivers

S-ar putea să vă placă și