Sunteți pe pagina 1din 84

JAVA A Program can support c, c++ applications for developing any software, only simple instructions are used.

Complex instruction a=b=c=d; We should not write complex operations and use comments. Object takes memory but not class. Object does not exist without class. Class can be created with out Object (The Object may be created later).

C features missing from java:1. 2. 3. 4. 5. 6. 7. 8. 9. No Bit Fields No Enumerated Data Types No free() No goto statement No global variables No pointers No pre processors No typedef No Structures 10. No Unions

C++ features missing from Java:1.No 2.No 3.No 4.No 5.No 6.No 7.No 8.No 9.No 10. 11. For C, C++: C Program | Compiler / \ Machine Machine Code for Code for Platform 1 Platform 2 | | Runs on only Runs on only Platform 1 platform 2 Operator Overloading. Function Overloading. Templates Pointers to Members Const Destructors Virtual Functions Friend Functions Multiple Inheritance No Reference Concept No Implicit Memory Management.

Ex:

abc.c | Compiler | abc.exe | abc.exe runs on specific platform which are using

For JAVA: Java Program | Compiler | Byte code for JVM | Runs on multiple Platform Ex: abc.java | Compiler | abc.class For JVM | Runs on many Platforms Note:

1.

C and C++ are platform dependant, but JAVA is platform independent. applications can write once and run on any platform.

Hence JAVA

2. abc.exe is an executable file. Executable file uses Binary Code. 3. 4. 5.


abc.class is a Byte Code. Byte Code uses set of alphabets and ASCII Characters. C (1000 Lines) C++ (500 Lines). The lines reduce because of Code Reusability. C (1000 Lines) C++ (500 Lines) Java (250 Lines). In JAVA, the line reduces because of Predefined Packages.

Institute have divided JAVA into three types: Core JAVA + Advanced JAVA + J2EE According to JAVA SOFT, there is no Advanced JAVA. According to JAVA SOFT: J2SE Classes, interfaces, AWT, Applets, Swings, RMI, Networking, JNDI . . .

JAVA

J2EE Servlets, EJB, XML, JTA, Java mail. . . J2ME Mobile Computing Technology. J2SE JAVA 2 Standard Edition. J2EE JAVA 2 Platform Enterprise Edition. J2ME JAVA 2 Micro Edition

Different areas in which we can find Jobs:-

Classes, interfaces, JDBC, JNDI + Swings Classes, interfaces, JDBC, JNDI + Servlets Classes, interfaces, JDBC, JNDI + EJB Classes, interfaces, JDBC, JNDI + J2ME Note: Servlets and Swings are extended versions of Core Java API. .Net .NET Vs JAVA Classes Servlet s JAVA

ASP.NET ADO.NET
C++ J# VB.Net

EJB Java Virtual Machine

JSP

Common Language run time WINDOW S

Any OS

TCP/IP & HTTP

TCP/IP & HTTP

Note: .NET is Language Independent. It supports 22 Languages.

Difference Between .NET and JAVA: .NET 1. 2. It supports multi languages. It supports single OS i.e. Wina. b. JAVA It supports single language. It supports multi OS.

3. 4.

dows. .NET applications are tightly coupled. It is developed by Microsoft.

c. d.

J2EE applications are loosely coupled i.e. they can run on any platform. It is developed by Sun Micro Systems.

C. C. M = J2EE + .NET CORBA (Common Object Request Broker Architecture) Supports Multilanguages & Multi Operating Systems.

Difference between Microsoft and Sun Micro Systems: Microsoft They are developing Client side applications. Ex: MS Office These applications can be used in office applications. Let a Microsoft application cost = 5 million $. Sun Micro Systems They are developing Server side applications. Ex: Sun Salaries These applications can be used in air crafts, railways, banking etc. These application cost = 20 times greater than Microsoft applications (100 million $).

1. 2.

a. b.

3.

c.

Any thing exit in the real world is called an Object. Ex: chair, student, mango, etc. Can Object exist physically? Yes. Can an Object is distinguishable from its environment? Yes. What is not an Object? Ex: LOVE (LOVE is an attribute but not an Object). Soul, Sand in wall, water in milk (here water is an Object & milk is an Object but combination is not an Object).

Does an Object exist without Class? No, hence Object is an instance of Class. Can Object is runtime instance of a class? Yes.

Object will have two things: 1. Properties 2. Actions Properties: Attributes=Variables

Ex: Assume that student is an Object then name, id, color, height and weight are Properties.

Actions: Methods Ex: Talking, Sleeping, walking etc. are some actions (because, to do these things we need some energy). Objects: Active Objects:These are Autonomous. Acted as implicit Objects. It serves as a Root Controller in the System. It exhibits some behavior without being operated on some other Objects. Passive Objects:o It is acted explicitly. Object is: 1. 2. 3. 4. o It depends on some other Object for state changing.

Tangible (real/clear) Visible Concrete Uniquely Identifiable

Is there any intangible Object? Yes. Ex: Goodwill, Chemical Processing, Rate of Interest.

Can Object do things? Yes, hence we can ask them to perform what they do by passing messages. What an Object does do? 1. 2. 3. 4. 5. 6. Objects can pass messages to other objects. Every Object plays some role in execution. Every Object may not work every time. Object may be destroyed after sometime. Object will wait till some other Object invokes method on it. Object can invoke methods by itself.

What an Object has? 1. 2. 3. 4. 5. Object Object Object Object Object can can can can can have one or more attributes. have one or more methods. have unique identity in the system. play specific role in the system. play specific role in the application.

Finally Object has 4 things: 1. 2. 3. 4. State: Attribute. State. Behavior. Identification.

It is a condition in which an Object may exist. State represents what is the value of an attribute of the Object at the given time. State changes normally based on the given time.

Behavior: Behavior tells how an Object is acting/reacting in terms of changes and message passing. Message passing- defines the behavior of an Object. State of an Object is affected by behavior. Is Object Oriented Modes is JAVA? No, Here Object Oriented Programming Model is a Concept. What is Object Oriented Technology? It is Software technology which makes use of OOPS. Hence the Software constructed has Objects in it. What OOPS have? Objects, Classes, Polymorphism, Inheritance, Encapsulation, Abstraction, Dynamic Binding, Message Passing. Advantage of OOPS: 1. 2. 3. 4. 5. 6. 7. 8. Data Hiding. Code Redundancy. Classes. Reduce the developed time. Reduce the Complexity. Easy to debug. Easy to divide the work. Increase the productivity.

Applications of OOPS: 1. 2. 3. 4. 5. Real time system. Artificial intelligence & Explore system. Object Oriented Database. CAS/CAM Systems. In Compiler design.

Types of Programming Language:

1.

Monolithic Programming Languages: Disadvantages: No Loops. No Parameter Passing. No Procedures.

No Functions. It has only instructions. Statements are less meaning full. It supports less statement.

2.

Procedure Programming Language: Advantage:

It supports Procedures. Reduce the Code. It supports sub programming concept. It supports global variables. Disadvantages: No parameter passing. No Local Variables. No Return type.

3.

Structured Programming Language: Advantage: It supports functions, structures, return Values, parameter Passing, local & global variables.

It supports Comments. Disadvantages:

We cannot handle bigger applications. Debugging is difficult. Understanding is difficult. Programmer may loose control on his program.

4. Object Oriented Programming:


Advantages: It handles bigger applications. Debugging is easy. Understanding is easy. It studies the overall behavior of the System.

Classification of Popular Programming Languages:First Generation: FORTRAN I It handles mathematical expressions. ALGOL 58 It handles mathematical expressions. Flowmatic It handles mathematical expressions. Second Generation:

FORTRAN II ALGOL 60 COBOL LISP Third Generation:

Subroutines. Block Structures, Data types. Data Description, File handling. List Processing, Pointers, Garbage Collector.

PASCAL Procedures. SIMULA Data Abstraction, Classes. Fourth Generation: Features: 1. Structured Programming. 2. Object Oriented Programming. 3. Parameter Passing etc. Note: The First Object Oriented Programming is SIMULA.

CHARACTARISTICS BINDING POLYMARPHISM DATA HIDING CONCURRENCY INHERITANCE GARBAGE COLLECTION MULTIPLE INHERITANCE GENERICITY (TEMPLATES)

SIMULA Both (Late/Ea rly) Yes Yes Yes Yes Yes No No

SMALL TALK Late

C++ Both (Late/Ear ly) Yes Yes Poor Yes Yes Yes Yes

ADA Early

EIFFEL Early

JAVA Both (Late /Early) Yes Yes Yes

Yes Yes Poor Yes Yes Yes No

Yes Yes Difficult No No No Yes

Yes Yes

Yes Yes Yes Yes

Yes Yes Yes No

o o o

From the above table:

Pure Object Oriented Programming Languages: Simula, Small Talk, Eiffel and JAVA. Object Oriented Programming Languages: C++. Object based Programming Languages: ADA, because it doesnt support inheritance. Note: VB is Object based Programming Language because, it doesnt

support Inheritance. VB.NET is Object Oriented Programming Language because, it supports Inheritance. CLASS o A class is a set of Objects, that share Common Structure and Common Behavior. Common Structure = Attributes. Common Behavior = Operations/Methods/Actions. Attributes that are not Objects. Ex: Love, time, beauty. . . A Class represents a Similar Characteristics of a group of Objects. Ex: Fruits, Sweets (Here Sweets is Class and Laddu is bject). A class is a Abstract Idea only, hence Class doesnt exist physically. Class doesnt take memory. Can Class exist with out an Object? Yes, because Class is an Abstract Idea. A Class encapsulates attributes and behavior of Objects. Can Class gives complete solution of the given problem? Yes.

o o o

o o o

What are the relationships among Classes? Association Inheritance. Using. Meta Classes.

Aggregation.

Association:

Produc t Class

If Products class object is given we can locate object for Sales. If Sales class object is given, then we can locate all the Products that sold during the transaction.

Sale s Clas s

Aggregation: Aggregation assets a direct to whole/part of relationship. Meta Classes: Class of a Class is Meta Class. A Meta Class allows us to treat Class as an Object. Meta Class is a Class whose instances are themselves Classes. Small talk, clos supports Meta class concept.

In C++: Static member functions=Meta Class Operations in Small Talk. To implement Abstraction and Encapsulation we require classes. In other words the implementation of class is done with abstraction and encapsulation.

Abstraction: Defines exactly what we need. Creating a new data type. Ex: Student properties are Id, name, color, height, DOB, DoJ, and Course.

To implement a particular project we require only few properties from above. Ex: Student in G.I.P.S requires Id, Course, Name, marks. Simplified specification or description of the system is called abstraction. Types of Abstraction: Entity Abstraction - Identifying useful properties. Action Abstraction Identifying useful methods. 3. Coincidental Abstraction Whatever we get from above (1 & 2). Abstraction focus on outside view of the objects. In other words abstraction gives how object is visible for other object.

Abstraction hides the data. Ex: In car we dont know so many things (like connections) that means they are hidden from the user. Encapsulation:

1.

2. 3. 4. 5. 6.

Combining data and member functions at a particular place is called encapsulation. Merits: i. Data and Member functions are stored at same location. ii. Execution is faster. iii. No wastage of time. iv. Modification is easy. v. It helps to isolate the class member functions from other member functions. Encapsulation focus on implementation of behavior. Do Abstraction first, Do decision making and finish before encapsulation. Abstraction tells what to do and Encapsulation tells how to do. Abstraction and Encapsulation are complementary things. Encapsulation at class level:Create the classes. Keeping definition on it. Say the order of definitions. Allow to add new Operations. C++:-

C++ was developed with the help of c and Small talk. (I.e. Syntax is taken from C and OOPS concept is taken from Simula). What are the class libraries merged for this technology? a.M.F.C (Microsoft Foundation Classes). b.J.F.C (Java Foundation Classes). c. .Net frame work class library (2000, Microsoft). JAVA(1991): Java started at 1991. It is the product of Sun Micro Systems. Java is developed by James Gastine and team. Initially java was OAK. OAK was all ready trademarks so, Brain Stromng let to Java. To write java programs we require JDK (Java Development Kit). J.D.K can be downloadable at http:\\ www. Javasoft.com.

We have J.D.K 1.3 version. The current version is J.D.K 1.5. JDK JDK JDK JDK 1.0.2 (1996) 200 classes, 2000 methods. 1.1 (1997) 500 classes, 5000 methods. 1.2 (1998) 2000 classes, 20,000 methods. 1.3 - Approximately 8000 classes.

The Mother of Java is c language.

What are the tools in JDK? Javac Java Applet Viewer JAR Java doc Javap Javac: Compiler It is an executable file. Ex: javac.exe. Purpose of Javac is converts .java file into .classes Java: Interpreter It is also an executable file like java.exe. Java.exe=JVM It is an interpreter for executing compiler. Java filer or application. Note: Java uses both interpreter and compiler.

Applet Viewer: We can run applets in two ways. 1. Through Browser. 2. Through Applet Viewer. Javap:

It displays the help. Ex: Javap java.lang.Object (It gives help of Object Class). How you organize a project/file? Let application director is Satya Project. In BIN directory place all executable files. In BUILD directory place all .class files. In DOCS directory place all documentation files. In LIB directory place all JAR files. In temp directory, place all temporary files. In SRC directory place all source code files. NOTE: It is not recommended to place all .java files in SRC directory because we may have more than one file in the same name. In this case we need to create sub directories in SRC directory. How do you will deliver your project to customers? In the project we will have several classes so it is better to pack them as a single or more JAR files. Now give this JAR file to customers.

Advantage with JAR files: o o Takes less memory. Maintenance is easy. rt.jar = Runtime. jar It is provided by JAVA Soft. It is having classes approximately 8000. JDK is providing a tool called JAR. Though JAR tool we can create or extract or display the content of JAR files.

o o NOTE:

How to create a JAR file? J:\jdk1.3\bin\satya\ let I have 20 files. J:\jdk1.3\bin\satya\JAR cf a. jar . Cf: create file a. jar: Name of JAR file. . : Current directory file. Note: To open JAR files we can use WinZip (manually).

How to see the content of JAR files? J:\jdk1.3\bin\satya\jar tf a.jar t= table of content f=file How to extract JAR file? J:\jdk1.3\bin\satya\JAR xf a.jar X= Extract. F=File. Where we are using java? To develop network applications. To develop distributed applications.

To To To To

develop develop develop develop

internet applications. platform independent applications. secure applications. machine critical applications.

Java is a? (Or) Explain Buzz words (features) of java? 1. Java is a architectural neutral (write once and run any where, any time, forever). 2. Distributed. 3. Dynamic. 4. High performance. 5. Multi threaded (Running more than one time working simultaneously). 6. Robust (Supports exception handling, avoids deallocation) 7. Portable (write once run any where). 8. Object Oriented. 9. Simple (Because mother of java is c & some features are taken by c++). 10. Secured (Because java provides firewalls between network application and client computer). Java is both compiler and interpreter. If we compare performance of java with c or c++, java will have less performance. JDK does not support any editor for writing java programs, thats why we can write where ever we want (like notepad, ms word, etc.). Java Program Compiler Byte Code JVM [Interpreted by java] Ex: Abc.java Compiler [javac] Abc.class JVM [java] JVM understands byte code. To execute java program by the understand we require JVM. JVM comes with as and automatically maintain. JVM does not exist physically JVM works like a security manager because before executing any instruction it is validated and verified by JVM then it is given for CPU for execution. Byte Code: A. After compilation we will get byte code for JVM. B. Byte Code is executed by java runtime system called JVM. C. Byte Code runs through interpreter on particular hardware (platform) JIT: JIT=Just In Time. It is part of JVM. It converts byte code into Native Code. JIT works as a compiler for byte code.

Some of the editors for JAVA:J Builder J Creator Kava Java is platform dependent.

Conditions for writing JAVA program:I. First statement is comment. We can write comments any where. Comments are for our purpose. These are non-executable statements (not compiled, not executed).

Types of comments: /* . . . . . . ...... ...... * // . . . . . . /** . . . . . ..... . . . . . */ Merits: Readability Understandability. II After comments write import package Package: o Package represents group of classes. In other words it represents a group of classes and place to store classes. o It is developed by java soft o Packages will have classes & interfaces. o It can allow subdirectories also. o We can create our own packages. Ex: import java.lang.*; import: statement java.lang.*: package. lang: language *: All the classes and interfaces are available in any program. Java.lang : default package In java.lang package there are classes like system, string . . . Multi line comments Single line comments Java documentation comment

#include stdio.h

import java.lang.*;

Let stdio.h has shaving 100 lines of code then this 100 lines of code is copied in to our program.

Let java.lang is having 100 lines of code then this 100 lines of code is not copied in to our program. That means a link is established from program to the package.

Note: We can write c++ program with out having classes but in java we cannot write programs with out class. That means to total code of java should be in at least one class (More than one class is also possible). Thats why c++ is an OOP language and java is pure object oriented programming language.

First. java // Program to display my name import java.lang.*; public class First { public static void main (String args[]) { System.out.println(Satya); } } public : access specifier class : keyword first : class name Every java program should have at least one method called main. We can write main only once.Main take arguments. String: It is a class It is available in java.lang package It is developed by javasoft String args[] : This is a command line argument Args is a variable name. Any method will perform some task. After performing task it should return some value so there should be return type. In above program there is no return value so we specified void. Why Static? Static methods can be invoked with out an object. In above program to invoke main there is no object. Who will invoke main? JVM will invoke main. Hence to invoke main we are note using any object (It is invoked by JVM automatically). Thats why keep static before main. Public: Main is invoked from outside to JVM that means my main method has to be available to outside. Thats why keep public.

System.Out.println(Satya):System=class Out=variable Can you create object for System class? No println is method in which Class? Print stream class System. out" returns object for print stream class thats why we can invoke println method with this object. Print(Satya); Output: Satya _ (cursor) Println(Satya); Output: Satya _ (cursor) How to compile above java program? H:\satya\javac First.java How to run java program? H:\satya\java First Note: Class name must be a program name and the extension is .java. Abc.java public class Abc { public static void main(String args[]) { System.out.println(Satya); } }

javac Abc.java After pressing enter it starts JVM. Now JVM search for Abc.class in the class. In that the Abc.class is found then java class loader is responsible to load Abc.class in the JVM Public class Abc { Static { System.out.println(Static block); } public static void main(String args[]) { System.out.println(Satya); } } will it compile? Yes will it run? Yes Output: Static block Satya

Public class Abc { public stativ void main(String args[]) { System.out.println(Satya); } Static { System.out.println(Static block); } } will it compile? Yes will it run? Yes Output: Static block Satya Note: In java static blocks are executed first, then main method is executed. public class Abc { Static { System.out.println(Static block); } } will it compile? Yes will it run? Yes, but error will come like main() not found. Output: Static block Public class Abc { public static void main(String args[]) { System.out.println(Satya); } } will it compile? Yes will it run? Yes Output : Satya

Note: While writing java program compiler checks is there at least one constructer in the class or not. In above example we didnt provide any constructor. Hence compiler is going to provide one constructor that is zero argument constructor. Public class Abc { public static void main(String args[]) {

System.out.println(Satya); } Abc(int x) { __ __ __ } } In above program we have provided an argumented constructor hence when we compile this program compiler is not going to provide any constructor. public class Abc { Static { System.out.println(Static block); } public void Abc() { System.out.println(Abc method); } } will it compile? yes will it run? yes, but error message will arise due to lack of main method. Public class Abc { public static void main(String args[]) { System.out.println(Satya); } public void Abc() { System.out.println(Abc method); } } will it compile? yes will it run? yes No errors will arise but warning will arise. How many methods? 2 How many constructors? 1 (provided by compiler) Output: Satya

Public class Abc { public void abc() { System.out.println(Satya); } public void xyz() { System.out.println(xyz method);

} } Will it compile yes Will it run? No, main method and no Static block hence run time error will arise like main not found. Class Abc { public static void main(String args[]) { System.out.println(Satya); } } Output: Satya Note: In above example the class access specifier will be treated as default.

Public class Abc { } Will it compile yes Will it run- No run time occurs. Class Abc { static void main(String args[]) { System.out.println(Satya); } } Will it compile? yes Will it run? yes Output: Satya In above example method access specifier is default.

Public class { public static void main(String args[]) { System.out.println(Satya); } } Java is pure object oriented language. In above program there arise an error when compiled because there is no name for class Public class Abc { public static void main(String args[]) {

System.out.println(Sat\nya); } } Output: Sat ya Note: Java will allow escape sequence characters i.e.,\n,\t

Public class Abc { public void main(String args[]) { System.out.println(Satya); } } In above program when we run leads to run time error. Public class Abc { static public void main(String args[]) { System.out.println(Satya); } } Output: Satya Note: public static void main = static public void main Public void static main wrong. Void public static main wrong.

Public class Abc { public Abc() { System.out.println(Abc); } Static { System.out.println( Static block); } public static void main(String args[]) { Abc a=new Abc(); // creating object System.out.println(Main); } } Output: Static block Abc Main() The execution order of methods : Static Constructor Main block Public class Abc {

public static void main(String []args) { System.out.println(Satya); } } Output: Satya Note: String [] args=String args[] Public class Abc { public static void main() { System.out.println(Satya); } } will it compile? Yes. will it run? No, it will get runtime error Note : command line arguments are compulsory. How to create an object in java? Public class Abc { public Abc { System.out.println(Constructor); } public void display() { System.out.println(Normal member function); } Static { System.out.println(Static block); } public static void main(String args[]) { Abc obj=new Abc(); // Creating an object. obj.display(); System.out.println(Main Block); } } What is the order of evaluation of methods? Static block Main function Constructor Member function Output: Static block Constructor Normal Member functions Main function

What new do? It allocates 4 bytes of memory for newly created objects. What is an anonymous object? If we have to use object once we use anonymous object. It takes memory for allocation but immediately after usage the memory allocation is destroyed. Public class Abc { int x=10; public static void main(String args[]) { Abc obj=new Abc(); System.out.println(obj.x); } } Real object: Abc obj=new Abc(); Anonymous Public class Abc { int x=10; public static void main(String args[]) { System.out.println(new Abc().x); } } object:new Abc();

When we want to use an object for single time ti is better to select anonymous object else select real objects. How to know Version, Vendor? Public class Abc { public static void main(String args[]) { System.out.println(System.getProperty(java.Vm.Version)); System.out.println(System.getPropety(java.Vm.Vendor)); } } Output: 1.3 Sun Micro Systems Program to display all System Properties of JAVA Public class Abc { public static void main(String args[]) { java.util.properties p=System.getProperties(); p.list(System.out); } } Types of variables:Instance Variables Class Variables Local Variables Ex: Public class Abc { int x; //Instance Variable static int y; // Class Variable public static void main(String []args) { int z; // Local Variable }

} Why we are calling Static Variables as Class Variables? Public class Abc { int z=1; static int x=10; public static void main(String args[]) { Abc y1=new Abc(); Abc y2=new Abc(); System.out.println(y1.x); System.out.println(y2.x); System.out.println(y1.z); System.out.println(y2.z); Y1.x=20; Y1.z=2; System.out.println(y1.x); System.out.println(y2.x); System.out.println(y1.z); System.out.println(y2.z); Y2.x=30; Y2.z=3; System.out.println(y1.x); System.out.println(y2.x); System.out.println(y1.z); System.out.println(y2.z); } } Output: 10 10 1 1 20 20 2 1 30 30 2 3 More than one object will share the common location for static variables. The example is given above. Do class variables or Static Variables have Encapsulation? No, because if we modify one object value, it is going to effect other object value. Can we declare local variables as static? No, because we cant write class variable inside the block(or) we cant use local variables out side though we declare then a static inside the block. Ex: Public class Abc { public static void main(String args[]) { Static int x; (wrong) } } Can we declare local variable as final?

Yes, but final keyword we not allow rechanging value. Can we reassign Values? No Ex: public class Abc { public static void main(String args[]) { final int x=10; x=20; (wrong, reassigning is not possible) } } Purpose of final variable: We can use final keyword in 3 ways For Variables For Methods For Classes Final classes will not support extended classes or inheritance Final methods cannot be over written Final variables cannot be reassigned. Can we declare final and static for instance variable? Yes, we can access but we cannot modify. Ex: Public class Abc { final Static x=10; public static void main(String args[]) { __ __ __ } } Note: We can access instance (or) class variables using this keyword public class Abc { int x=10; // Interface variable Static int y=20; // Class Variable Final int z=30; // Instance Variable Public void display() { int x=1; int y=2; // Local variables int z=3; System.out.println(x); System.out.println(y); System.out.println(z); System.out.println(this.x); System.out.println(this.y); System.out.println(this.z); } public static void main(String []args) { Abc obj=new Abc(); Obj.display(); System.out.println(obj.x);

System.out.println(obj.y); System.out.println(obj.z); } } Output: 1 2 3 10 20 30 10 20 30 How to use command line argument? Or how to get input at runtime? Public class Abc { public static void main(String args[]) { for(int i=0;i<args.length;i++) System.out.println(args[i]); } } c:\javac Abc.java c:\ java Abc one two three Output: One Two Three Program to find sum of 2 number? Public class Abc { public static void main(String []args) { int a,b; a=10; b=20; System.out.println(Sum is :+a+b); } } Output: 1020 In above program +a+b is acting as an concatenation operation. To get the sum of a and b we have to change as below: System.out.println(Sum is : +(a+b)); Output: Sum is : 30 Java is supporting + operator overloading or not? Yes, refer the sum of 2 numbers program. How can we get a and b value at runtime in above program? Public class Abc { public static void main(String args[]) { int a,b; a=Integer.parseInt(args[0]); b= Integer.parseInt(args[1]); System.out.println(Sum is : +(a+b)); } } c:\> javac Abc.java c:\> java Abc 20 30

Output: Sum is : 50 Note: sion. Command line argument values are always strings thats why we need some type of conver-

How to convert a string to integer? Int a=Integer.parseInt(args[0]); Public class Abc { public static void main(String args[]) { System.out.println(One); Our o1=new Our(); System.out.println(Two); Our o2=new Our(); System.out.println(Three); } } class Our { Static { System.out.println(Static block); } } c:\> javac Abc.java (here we will get two class files) c:\> java Abc Output: One Static block Two Three Note: In java program if there are more than one class then devlare only one class as Public. When ever class is required JVM checks whether that class is loaded or not if not loaded then JVM loads that class. In other words JVM loads the class when we are suing the class for the 1st time. How to load a class dynamically? Class.forName() checks whether class is loaded in JVM or not. If not loaded then that class will be loaded in JVM. In other words Class.forName() loads JVM for the 1st time. Our.java Public class Our { Static { System.out.println(Static block); } } javac Our.java Abc.java Public class Abc { public static void main(String args[])throws Exception { System.out.println(One); Class.forName(Our);

System.out.println(Two); Class.forName(Our); System.out.println(Three); } } javac Abc.java java Abc How to create an object dynamically? Class O=Class.forName(Our); O.newInstance(); (Or) Class.for(Our).newInstance(); Our.java Public class Our { Static { System.out.println(Static block); } } javac Our.java Abc.java Public class Abc { public static void main(String []args) { Class.forName(args[0]).new Instance(); } } javac Abc.java java Abc Our Data types Intiger type: Byte : 1 Byte Short : 2Bytes Int : 4 Bytes Long : 8 Bytes Int x=30; Long y=x; This is called implicit conversion. Conversion lower data type to higher data type is called winding. Reatl type: Float : 4 Bytes - + 3.4 e + 3.8 Double: : 8 Bytes - + 1.7 e + 3.8 Long double : 10 Bytes. Ex: float x=3.5; Here compiler recognizes 3.5 as double. To treat compiler 3.5 as float we have to declare as follows: Float x=3.5F; Float is having precision = 7 Double is having 15 precisions.

Character Data type:

Char 2Bytes

Why char takes 2 bytes? Java soft thought that in future we will get a key board in our own languages. In this case data type needs to support more characters (International characters) thats why 2 bytes. Ex: string x=Satya; String x=new String(Satya); Here x is an object for String class. Boolean Data type: It holds true or false values Ex: Boolean x=TRUE; Is Boolean data type incompatible? Yes. Ex: Boolean x=True; Int y=x; (Wrong) Int x=30; Boolean y=x; (Wrong) Note: Converting higher data type to lower data type is called narrowing or explicit conversation. Operators Arithmatic : + - / * % Unary Ex: : ++ -- new Public class Abc { public static void main(String args[]) { System.out.println(10%3); System.out.println(-0%3); System.out.println(10%-3); System.out.println(-10%-3); } }

Assignment : =, +=, -=, /+, *=, %= Relational : <, <=, >, >=, ++, !=.

logical : AND OR NOT Bitwise : ~, |, &, <<, >>, cap Conditional /Ternary : ?:

dot operator : . (in packages) We use . operator in java in 3 ways Packages. Ex: java.lang.*; In invoking methods Public class Abc { int x=10; public void display()

{ System.out.println(Display); } public static void main(String args[]) { Abc x1=new Abc(); X1.display(); X1.x; } } public class Abc { public static void main(String args[]) { int x=10,y=11; System.out.pritnln(~x); System.out.pritnln(~x); System.out.pritnln(~x); System.out.pritnln(~x); System.out.pritnln(~x); System.out.pritnln(~x); } } Output: -11, 10, 11, 1, 46, 2. Which are the keywords reserved for java but not implemented? Goto, Cosnt. Control Statements: If-else Switch For loop While loop Do-while loop Break Continue Return Write a java program to find given number is odd or even Public class Test { public static void main(String args[]) { int x=21; if(x%2==0) System.out.println(Given number is even); else System.out.println( Given number is odd); } } write a program to explain switch statement? Public class Switch { public static void main(String args[]) { char x=B;

Switch(x) { case R:System.out.println( Color is Red);break; case B: System.out.println( Color is Blue);break; default : System.out.println(No color); } } } Output: Color is Blue Goto statement: In java there is no goto statement, so we can use break statement as goto statement. Public class goto { public static void main(String args[]) { block1: { block2: { block3: { System.out.println(block3); break block2; } } System.out.println(block1); } System.out.println(Out side); } } Output: block3 Block1 Out side We can use break statements in 3 ways: To come out from the loop To come out from the block Break can be used as goto in java In java why goto statement is not there? Goto statement skip the statements with out checking any condition thats why goto is called unconditional statement. Disadvantages: May occur in infinite loop. Documentation is difficult Readabulity is required. For loop, continue statements example program Public class Abc { public static void main(String args[]) { for(int i=1;i>=10;i++) { if(i==2 || i==5) continue; else System.out.println(i);

} } } Output: 1 3 4 6 7 8 9 10. Return: Return can be used in 2 ways 1. To return some value to method. 2. To come out from block. Ex: Public class Abc { public static void main(String args[]) { System.out.println(Satya); Return; System.out.println(Hello); } } Output: Satya Note: To terminate the program System.exit(0); Here 0 means normal termination and if 1 then when error comes then it will be terminated. Program to calculate Area of a circle Public class Circle { public static void main(String args[]) { final float pi=(flaot)22/7; float r=10.2F; float area; area=pi*r*r; System.out.println(Area is +area); } } Output: 326.6858.

How to format the sequence 326.6858? Import java.util.*; Import java.test.*; Public class Circle { public static void main(String args[]) { final float pi=(flaot)22/7; float r=10.2F; float area; area=pi*r*r; System.out.println(Area is +area); NumberFormat nf=NumberFormat.getNujmberInstance(); Nf.setMaximumIntegerDigits(4);

String str=nf.format(area); System.out.println( Area is : +str); } } Output: 326.6859. Note: If we have to display the result according to country NumberFormat nf=NumberFormat.getNumberInstance(locale.us); NumberFormat nf=NumberFormat.getNumberInstance(locale.DE); What is factory method? If any method returns any object of the class to which it belong then that method is called factory method. Ex1: Public class Abc { public static Abc display() { Abc x=new Abc(); Return x; } } In above example display method is called factory method. Because it is returning an object of the same class. Ex2: getNumberInstance is factory method. Note: To declare constants in java use final keyword. getNumberInstance is a static method in number format class. Number format class is available in java.text.*.

ARRAYS An array is a group of elements of same type and all the elements will be stored in continuous locations. Types of Arrays: One dimensional array Two dimensional array Multi dimensional array How to declare and initialize one-dimensional array? a[0] 1. a[1] a[2] a[3]

10

20

30

40

Total require memory 4X4 =16. 2. float a[]={1.2F,1.3F,1.4F}; Here a is a one dimensional array of type float.

3. String a[]={Satya,abc}; Here a is a one dimensional array of type String Note: Command line arguments are one-dimensional array. How to declare 1-dimensional array? Int a[]=new int[10]; Here a is an array of type int and it can hold 10 integer elements. How to declare & initialize of 2-dimentional arrays? 1. int a[][]={ {1,2,3},{4,5,6},{7,8,9},{10,11,12}};

1 4 7 10

2 5 8 11

3 6 9 12

2. String a[][]={{Satya,abc},{xyz,xy}}; Here a is a 2-dimentional array of type string. System.out.println(a[0][1]); Output for the above statement is : abc How to declare of 2 dimensional arrays? Int a[][]=new int[4][3];

Write a java program to find big number using arrays? Public class Abc { public static void main(String args[]) { int a[]={9,11,23,6}; int large, I; large=a[0]; for(i=0;i<4;i++) { if(a[i]>large) large=a[i]; } System.out.println(Big number:+large); } } String Handling String class is available in java.lang.* String x=Satya; System.out.println(x); Output: Satya String x=new string(Satya); System.out.println(x);

Output: Satya Char a[]={S,a,t,y,a,\0}; String x=new String(a); // converting char into string System.out.println(x); Output: Satya String x=new String(a,0,3); System.out.println(x); Output: Sat Methods in String Classes: String concat (String Str); // prototype of concat method String s1=Hello; String s2=Satya; System.out.println(S1.concat(s2)); Output: Hello Satya Int length(); System.out.println(S1.length()); Output: 5 Char chatAt(int index); System.out.println(S1.chatAt(2)); Output: t Int compareTo(String str); String s1=Bat; String s2=Cat; System.out.println(S1.compare(s2)); Output: -ve.(negative value) Note: CompareTo returns ve value if second string is next to first string in dicronary order else it return +ve value.

Boolean equals(String str); String s1=Satya; String s2=satya; System.out.println(S1.equals(s2)); Output: false Boolean equalsIgnoreCase(String str); String s1=Satya; String s2=Satya; System.out.println(S1.equals(s2)); Output: true Int indexOf(String str) String s1=Satyabxyzabcd; System.out.println(s1.indexOf(ab)); Output: 5,6 System.out.println(s1.lastIndexOf(ab)); Output: 10,11 Boolean StartsWith(Stgring Str); String s1=Satyabxyzabcd; System.out.println(s1.startsWith(Sat)); Output: True

Boolean endsWith(String Str); String s1=Satyabxyzabcd; System.out.println(s1.endsWith(bc)); Output: True System.out.println(s1.endsWith(xy)); Output: False String replace(old class, new class); String s1=Hello; System.out.println(s1.replace(l,x)); Output: Hexxo String substring(int begin); String s1=Hello; System.out.println(s1.subString(2)); Output: llo String toUpperCase(); String s1=Satya; System.out.println(s1.toUpperCase()); Output: SATYA String toLowerCase(); String s1=SATYA; System.out.println(s1.toLowerCase()); Output: satya String trim(); String s1= Satya ; System.out.println(s1.trim()); Output: Satya Trim(): It removes all the spaces in the string. Program to perform string operations Import java.lang.String; Public class Strings { public static void main(String []args) { String s1= This is JAVA; String s2= I like that; Char s3[]={H,E,L,L,O,\0}; String s4=new String(s3); // converting char to string System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1.concat(s2)); int x=s1.length(); System.out.println(x); System.out.println(s1.toUpperCase()); System.out.println(s2.toLoweCase()); System.out.println(s1.startsWith(This)); System.out.println(s2.endsWith(Java); System.out.println(s1.subString(0,6)); } } How to take input from key board?

Using strings we can get input from keyboard. Streams: Stream is nothing but flow of data between any two objects. Ex: data flow can be: Program to memory Program to device Program to printer

Progra m

Stream

stream

stream

Device

Key Board

Memory

Why Streams? Stream can represent any device. Ex: separate stream for representing key board, separate stream for monitor, separate stream for printed and etc. Why we need separate streams for each device? Streams are independent to hardware. Predefined Streams: System.out: It returns print stream object. Generally it will be connected to monitor. This stream is all ready opened. It sends the data. System.in: It returns input stream object. Generally it will be connected to keyboard. It is already opened. It received data. System.err: It returns print stream object. It is already opened It send the data. System.out.println(Hello); System.err.println(Hello); Can you It will display message Hello. It will display message Hello create an Generally it is used to display norThis will be used to display error object for mal message. message hence above Hello result system is error message. class? No, generally system class will interact with operating system for program execution. Can we create an object for runtime class? No, generally run time class also interact with operating system for program execution. How to read a character from keyboard? import java.io.*; Public class Rchar { public static void main(String args[]) throws Exception { char ch;

System.out.printoln(Enter a charcter : ); InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); (or) BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Ch=(char)br.read(); System.out.println(Entered character is :: +ch); } } Note: All the streams are available in java.io package. o To improve efficiency use bufferreaderclass o InputStreamReader class and BufferedReader class are available in jav.io package o read method throws an io exception. How to read a String or line of text from Keyboard? Import java.io.*; Public class Rstring { public static void main(String args[]) throws Exception { String Str; System.out.printoln(Enter a String : ); BufferedReader br=new BufferedReader(new putStreamReader(System.in)); Str=br.readLine(); System.out.println(Entered String is :: +Str); } } How to read integer from keyboard? Import java.io.*; Public class Rnum { public static void main(String args[]) throws Exception { int n; System.out.printoln(Enter a number : ); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); System.out.println(Entered Number is :: +n); } } How to read float from keyboard? import java.io.*; Public class Rfloat { public static void main(String args[]) throws Exception { flaot f; System.out.printoln(Enter a real value : ); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); f=Float.parseFloat(br.readLine()); System.out.println(Entered real value is :: +f);

In-

} } How to read a double number from keyboard? import java.io.*; Public class Rdouble { public static void main(String args[]) throws Exception { double no; System.out.printoln(Enter a double number : ); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Double.parseDouble(br.readLine()); System.out.println(Entered Double Number is :: +no); } } Write a program to read file content and displaying on screen. import java.io.*; Public class File { public static void main(String args[]) { FileInputStream fis=new FileInputStream(a.txt); Int ch; While((ch=fis.read())>=0) { System.out.println((char) ch); } fis.close(); } } Output: hello java. Note: To handle files we need to use FileInputStream and FileOutputStream. In above program a.txt is text file with text hellojava. Write a program to copy the contents from one file to another file. Note: Copy contents from a.txt to b.txt Program should take a.txt and b.txt at run time. import java.io.*; Public class Copy { public static void main(String args[]) throws Exception { FileInputStream fis=new FileInputStream(abc[0]); FileOutputStream fos=new FileOutputStream(abc[1]); Int ch; While((ch=fis.read())>=0) { fos.write(char(ch)); } fis.close(); fos.close(); } }

Note: EOF is the end of the file which is having value -1. Exercise: Write a java program which reads file contents and convert the file content into upper case and display it on monitor. Write a java program which reads inputs from keyboard and place it in a file. Mutable and Immutable: What is immutable object? If we modify the content of an object then that object is called Mutable Object. If we cannot modify the content of an object then it is called Immutable Object. Example for Immutable Object is all String class objects. Example for Mutable Object is String Buffer class objects. Ex: String class objects String x=Satya; System.out.println(x); // O/P :: Satya String y=abc; System.out.println(y); // O/P :: abc y=x+y; System.out.println(y); // O/P :: Satyaabc

Here x,y are String class objects. In above example y=x+y statement, we ae modifying the content of object y then why we are calling String objects are Immutable? Because

x y

Satya abc Satyaabc

When we write y=x+y, here the Original value of bac of object y is not modified, the JVM creates a new object that is having satyaabc thats why we are saying string objects are Immutable. Disadvantage with Immutable Object: When we are write y=x+y; JVM is creating a new object. String Buffer class: It is available in java.lang package. We can modify String Buffer class object contents, thats why String Buffer class objects are Mutable Objects. How to create an object for string buffer class? StringBuffer sb=new StringBuffer(Satya); How to create empty StringBuffer object? StringBuffer sb=new StringBuffer(); StringBuffer sb=new StringBuffer(50); Here sb is a StringBuffer class object, which is ready to hold 50 characters. If we add more than 50 characters then also no problem because StringBuffer clas objects grow dynamically thats why these objects are called Mutable Object. Method in StringBuffer class: Append(x): Here x= Integer (or) character (or) String . . . Ex:

StringBuffer sb=new StringBuffer(Satya); Sb.append(d); System.out.println(sb); Output: Satyad Insert(int pos,x): Here x= Integer (or) character (or) String . . . Ex: StribgBuffer sb=new StribgBuiffer(Hello); Sb.insert(2,x); Ouput: Hexllo Length(): Int n= sb.length(); System.out.println(n); Output: 5 Reverse(): Ex: Sb=Satya; Sb.reverse(); System.out.println(sb); Output: aytaS Tostring(): It converts StribgBuffer class object into String class object. How to convert String class object into StringBuffer class object? String x= new String(abc); StringBuffer sb=new StringBuffer(x); import java.io.*; Public class SB { public static void main(String args[]) throws Exception // Create empty StringBuffer object StringBuffer sb=new StringBuffer(); BufferedREader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(Enter First Name :: ); String fn=br.readLine(); System.out.println(Enter Middle Name :: ); String mn=br.readlLine(); System.out.println(Enter Last Name :: ); String ln=br.readLine(); System.out.println(sb.append(fn)); System.out.println(sb); System.out.println(sb.append(ln)); System.out.println(sb); Int n=fn.length(); System.out.println(sb.insert(n,mn)); System.out.println(sb); }

Output: Enter First Name :: Satya Enter Middle Name :: Narayana Enter Last Name :: Reddy Satya SatyaReddy

SatyaNarayanaReddy Satya What is a Native method? Most of the Native methods will be implemented in c language. The mechanism to integer Native methods and Java code is called JNI( Java Native Interface). Disadvantage with Native methods: Allows Virus

Loss of Portability, because Native Method contain DLL( Data Link Libraries). Let an application/program is having java code and Native Method then this application runs on a machine which is having DLLs.
What is Instance of Operator? It test whether that object is belongs to that class or not. Syntax: <object name> Instanceof <class type>; Ex: emp Instanceof employee; If emp object is belongs to employee class then instance of operator returns True else return False. What is transient Variable? Class abc { int a; transient int b; } In the example a is called instance Varibale and b is called transient variable. Transient variables are not persistent. Transient variables are not serialize or Serialization. Serialize(meaning): The process of writing state of an object into a file is called Serialize or Serialization. Transient variables may not have the data permanently. (persistent : It can hold object value long time) Naming Convention in Java:Use all small letters for packages. Ex: java.io, java.lang Class name must starts with capital letters. Ex: String. Interface must start with capital letter. If aclass or Interface having more than one word then each woird should starts with capital letter. Ex: StringBuffer, FileInputStream. Java is case sensitive. Methods starts with small letter. Ex: length, concat. If method is having morethan one word then from second word onwards each word should starts with capital letters. Ex: charAt, toUpperCase, equalsIgnoreCase. Declare constants with capital letters. Ex: PI, Font.BOLD (where Font is class). If at all we are writing classes or methods follow above conventions. Java are incompartable? Yes, because we can,t assign one class object to another class object. We can assign derived class object to base class object. We cant assign base class object to derived class. Ex:

Class A { ___ ___ } class B extends A { public static void main(String args[]) { A a1=new A(); // a1 is base class object B b1= new B(); // b1 is derived class object. A1=b1; // which is wrong, because we cant assign derived class object to base class object. B1=a1; // we can assign base class object to derived class object. A1=(A)b1; // Type casting. } } If we want to assign derived class objects to base class objects, do type casting. Ex: Class F { public void x() { System.out.println(F); } } class R extends F { public void x() { Syste.out.println(R); } public static void main(String args[]) { F f1=new F(); R r1=new R(); F1.x(); // X R1.x(); R1=f1; F1.x(); // X R1.x(); F1=(F)r1; R1.x(); } } Class A { ___ ___ ___ } abstract class B { ___ ___ ___ } abstract class C {

___ ___ ___ } interface class D { ___ ___ ___ } interface class E { ___ ___ ___ } class A extends B,C; // which is wrong, because multiple inheritance is not supported by java. Class A implements D,E; // We can achieve multiple Inheritance in java through interface. Class A extends B implements D,E; // class can extend abstract calss. Class B extends C implements D; .. Abstract class can extend Abstract Class. Class B implements D; // Abstract class can implement interface. Class B extends A; // Abstract class can extends a class. Interface D extends A; // which is wrong, because interface cannot extends class. Interface D extends B; // which is wrong, because interface cannot extends abstract class. Interface E extends D; // An interface can extends another interface. Class A extend D; // which is wrong, because class cant extend interface. Class A implements D; // class can implements interface. Interface D implements A; // Which is wrong, because interface cant implement or extend the class. Interface E implements D; // An interface cant implement another interface. Why we are using String Class Objects instead of char array (A[30])? a.No memory wastage. b.Grow dynamically. c. No size limit. d.Flexible. e.Safe f. High Performance. Multiple Classes:NOTE: If we have more then one class, make at maximum only one class as public. If we have more then one class, then java program name will be the class name which is having main(). Ex: Class Person { String name; Int age; Public void talk() { System.out.println(Hello+name); System.out.println(Age+age); } } public class Demo { public static void main(String args[]) { Person x=new Person();

x.talk(); } } Output: Hello NULL Age 0 Note: We must save the above program with Demo.java only. Because the Demo class has define as public and it contain the main(). Default value for String is NULL. Default value for int is 0. Default value for float is 0.0. Default value for long is 0. Default value for double is 0.0. Default value for char is (single space). Default value for boolean is false. Default value for object is NULL. Public class Demo { public static void main(String args[]) { Person x1=new Person(); Person x2=new Person(); X1.talk(); X2.talk(); } } Output: Hello NULL Age 0 Hello NULL Age 0 Note: We can create more than one object for same class. In above example the disadvantage is all objects are taking same values. To overcome the disadvantage we can write as follow. Public class Demo { public static void main(String args[]) { person x1=new Person(); Person x2= new Person(); X1.name=Abc; X1.age=10; X2.name=Xyz; X2.age=20; X1.talk(); X2.talk(); } } Output: Hello Abc Age 10 Hello Xyz Age 20 Class F { public void x() { System.out.println(F); } } class R extends F {

public void x() { System.out.println(R); } public static void main(String args[]) { F f=new F(); R r=new R(); F.x(); r.x(); f=r; // We can assign derived class object to base class object. f.x(); r.x(); r=f; //it is wrong, because we cant assign base class object to derived class object r=(R)f; f.x(); r.x(); } } Output: F R R R R R. Note: In above program we are not providing any security for the data. To provide security for the data in java we will use Access specifiers. Access Specifiers In java there are four access specifiers. 1.public 2.protect 3.default 4.private Default access specifier in java is Default. Generally variable can be declared as private and member function as public. C:\Satya\a.java m1,m2 (Let in a.java we have two methods m1 and m2). C:\Satya\b.java m1,me ( In b.java we can access m1 and m2 if methods are default or public) C:\Satya\c.java In c.java we can access m1 and m2, if m1 and m2 are public. But we cant access m1 and m2 if they are default. Note: Default methords/data can be accessable in the same directory(package). We cannot access default methods out side the package. Access With in same class Any class same package Sub class same package Sub class out side package Class outside package Public Yes Yes Yes Yes Yes Protect Yes No Yes Yes No Default Yes No Yes No No Private Yes Yes No No No

Differences between constructors and methods. CONSTRUCTOR

1. Constructor name is always class name. 2. Constructor does not return any value. 3. Constructor will be called automatically. 4. Constructors cant be inherent. 5. Constructors cant be Virtual. 6. We cant write constructors with in the unions. 7. Constructor cannot change the content of an object which is already exist. 8. We cant get constructors address. METHODS a. b. c. d. e. f. g. h. Method name is not class name. Methods can return a value. We need to invoke methods explicitly. Methods can be inherent. Methods can be virtual. We can write methods in the Unions. Method can change the content of an object which is already exist. We cant get method address. CONSTRUCTOR: Another name for Constructor is CTOR. Constructors generally used to initialize the variables. Constructors can take arguments. Constructor can be overloaded. A constructor without arguments is called Default Constructor. Constructor with arguments is called parameterized constructor. Ex: Class Person { String name; Int age; Person() // Initializing variables using Constructor. { name=abc; age=20; } public void talk() { System.out.println(name); System.out.println(age); } } class Demo { public static void main(String args[]) { Person x1=new Person(); Person x2=new Person(); X1.talk(); X2.talk(); } } Output: Abc 20 Abc 20 Note: Encapsulation is body, abstraction is VIP.

Encapsulation provides security for abstraction. Encapsulation provides implementation of abstracts in any ways. In above example we have create a two objects call x1 and x2. The two objects have same values. To overcome the disadvantage we are moving to parameterized constructor. Public static void main(String args[]) { Person x1=new Person(); Person x2=new Person(); X1.(abc,20); X2.(xyz,10); } Output: Abc 20 xyz 10 Explain about this key word? this refers current object. We can use this key word in three ways: i. To refer the variable. ii. To refer the methods. iii. To refer the constructor(perametarised). Ex: Class Abc { int no; Ac() // Default constructor { this(100); // It invokes parameterized constructor. This.getvalue(); // It invokes getvalue(). } Abc(int no) { this.no=no; } public void getvalue() { System.out.println(no); } } public class Demo { public static void main(String args[]) { Abc x1=new Abc(); } } Output: 100 Note: Accessor Method:- If any method is not modifying the content of an object then that method is called Accessor Method. In below example display() method is Accessor method. Mutator Method:- If any method modifying the contents of an object then it is called Mutator Method. In the below example odi() is mutator method. Ex: Class Abc {

int no=100; disp() { System.out.println(no); } modi() { no++; System.out.println(no); } } class Demo { public static void main(String args[]) { Abc x=new Abc(); x.disp(); // Accessor method x.modi(); // Mutator method x.disp(); } } Output: 100 101 101 Constructor acess specifies is always same as class Access specifier? Yes. Ex: Class Abc { Abc() // constructor access specifier is default. { ___ ___ } } public class Abc { Abc() // here CTOR access specifier is public { ___ ___ } } Method Overloading: How to identify a method uniquely or what is a method signature? If no.of arguments are differ then we can identify method uniquely. Ex: Abc(int i); Abc(int i, int j); If datatype differs then we can identify methods uniquely. Ex: Abc(int i); Abc(float j); If perameters sequence is differ then we can identifying method uniquely. Ex: Abc(int i, int j, float k);

Abc(int i, flaot j, int k); Ex: Class Abc { void add(int a, int b) { System.out.println(a+b); } void add(int a, int b, int c0 { System.out.println(a+b+c); } } public class Demo { public static void main(String args[]) { Abc x=new Abc(); x.add(10,20); x.add(10,20,30); } } Output: 30 60 In above example add() is behaving differently at different situations hence we can say that add() is overloaded. Static Polymorphism: If method overloading is done at compile time then it is called static polymorphism. Static polymorphism=Early binding. Example for static polymorphism is method overloading. Dynamic polymorphism: If method overloading is done at runtime then it is called dynamic polymorphism. Dynamic polymorphism=late binding. Example for dynamic polymorphism is method overriding. Here JVM makes the decision for invoking the methods. Static methods Class Abc { static int add(int a,int b) { return(a+b); } static int add(int a, int b, int c) { return(a+b+c); } } public class Demo { public static void main(String []args) { System.out.println(abc.add(10,20)); System.out.println(abc.add(10,20,30)); } } Note: We can invoke static methods without the help of creating an

object. Hence static method invocation save the memory. Constructors will not be static. Static methods will not be constants. We cant use this operator for static methods. We cant make volatile static methods. We cant use virtual before static methods. INHERTANCE Class Tea { name, id, add,sal; } class Std { name, id, add; } In above example name, id, add is there in both Tea class and Std class. To implement Tea class and Std class I need to provide separate implementation of name, id, add in both classes. Disadvantage: Code redundancy: That mean repeatedly we are writing the same code. To overcome above disadvantage we are moving to Inheritance. Getting a new class from existing class is called inheritance. There new class = derived class (or) Sub class. Existing class= Base class (or) Super class. Inheritance is a relationship among the classes. Inheritance follow is a relationship. Derived class can share the Derived class can share common structure and/or behaviors of base class. Derived class had more qualities compare with base class.

SINGLE INHERITANCE

MULTIPLE INHERITANCE

HIRARCHICAL INHERITANCE

MULTI LEVEL INHERITANCE

MULTI PATH INHERITANCE

HYBRID INHERITANCE (Multi path + Multi Level + Hierarchical) Note: In java multiple inheritance is not possible, but with the help of interfaces we can achieve multiple inheritance. To do inheritance we need to use extends key word in java. Why multiple inheritance is not allowed in java? Multiple Inheritance gives 1. Name collision. 2. Repeated Inheritance. Ex:

The advantage of inheritance is code reusability. Ex: Case I: Class A { int i; A(int i) { this.i=i; } void show() { System.out.println(Base Value of i is :: +i); } } class B extends A {

int i; B(int i,int j) { super(j); // It invokes base class constructor. This.i=i; } void show() // Method over writing. { System.out.println(Derived value of i is :: +i); } } public class Demo { public static void main(String args[]) { B ob=new B(10,20); ob.show(); } } Output: Derived class i :: 10 Case 2: In above example if class B show() is not there then class A show() is executed. Hence output is Base class value of i :: 20. Case 3: To execute class A show() and class B show() do the following modification in class B show(). Modify class B show() like shown below. Void show() { System.out.println(Derived class i value is :: +i); Super.show(); } Output: Derived class i value is :: 10 Base class i value is :: 20 Case 4: A ob=new A(100); ob.show(); Output: Base class i value is :: 100

public static void main(String args[]) { A o1=new A(100); B o2=new B(200,300); A re; // Here re is the reference for class A. re=o1; re.show(); re=o2; re.show(); } Output: Base class i value is :: 100. Derived class i value is :: 200. Note: Object will take memory, reference will not take any memory. In above example re is the reference for class A. Hence using base class references we can access base class methods and derived class methods. Case 6: Public static void main(String args[]) { A o1=new A(100); B o2=new B(200,300); B re; // re is reference to class B.

Case 5:

re o2; re.show(); re.o1; // which is wrong. } Note: Using derived class references we can access only derived class members not base class members. super is a key word. extends is also a key word. super must be first statement in the constructor. We cant write more than one time super in the same CTOR. We cant use super in main(). Constructors are not members of the class thats why Constructors are not inherited. In above example show() is available in base class and derived class with same signature and same return type. This concept is called Method overriding. OVER LOADING 1. 2. 3. 4. 5. 6. 7. Over loading is done within a same class. Inheritance is not required. Return type may or may not be same. One method is not hidden by another method. This is example for Static Polymorphism. Method is recognized by compile. Method over loading is done at compile time. OVER RIDING A. B. C. D. E. F. G. H. Over riding is done between two classes. I inheritance is required. Signature must be same. Return type must be same. Method may be hidden by another method. It is example for Dynamic Polymorphism. Method is recognized by JVM. Method over riding is done at run time.

ABSTRACT CLASSES abstract class Abc { int a=10,b=20; abstract int area(); } class Tri extends Abc { int area() { return((int)1/2*a*b); } } class Rect extends Abc { int area() { return (a*b); }

} class Sc extends Abc { int area() { return(a*a); } } public static void main(String args[]) { Abc x=new Abc(); // This is wrong, we cant create object for Abstract class Tri x1=new Tri(); Rect x2=new Rect(); Sc x3=new Sc(); System.out.println(x1.area()); System.out.println(x2.area()); System.out.println(x3.area()); } Output: 100 200 100 Method without body is called abstract method. Before abstract method use a keyword called abstract. Abstract methods are unimplemented methods (in future we are going to implement these abstract method according to the requirements). A class at least with one abstract method is called abstract class. For abstract classes use abstract key word before the class name. Abstract classes must be base classes, not derived classes. We cant create an object for abstract class because abstract class will have abstract method and abstract method will not have body. Abstract class may have one or more variables. Abstract class may have one or more abstract methods. Abstract class may have one or more non abstract methods. INTERFACES Interface will have all abstract methods. To write interfaces, we need to use key word called interface. Interface will have two things 1. Methods, 2. variables. All methods are by default public, abstract. All variables are by default public, static and final. To implement interface methods in a particular class we need use implement key word. We cannot create an object for interface. Because interface will have abstract methods and abstract methods are not going to have body.

Ex: interface Abc { void connect(); // It is by default public, abstract. } class OracleDb implements Abc { public void connect() { System.out.println(Write code for connect to Oracle DB); } }

class AccessDb implements Abc { public void connect() { System.out.println(Write code for connect to Access DB); { } class Demo { public static void main(String args[]) throws Exception { Class c=Class.forName(args[0]); Abc o=(Abc) c.newInstance(); o.connect(); (or) c.new Instance().connect(); } } javac Demo.java java Demo OraceDb Output: Write the code for connecting OracleDb. Javac Demo.java Java Demo AccessDb Output: Write the code for connecting Access DB. ABSTRACT CLASSES A. B. C. D. E. F. G. With abstract classes we can do first difference. We should specify abstract before the method. Possible access specifiers are public/protect/default. Need not be. We can access base class members using super key word. It has at least one abstract method. May have not abstract methods. Abstract class will be extended using extends key word.

INTERFACE CLASSES a. b. c. d. e. f. g. h. i. With interface we can do multiple inheritance. Need not specify abstract before the method because by default it is abstract, pubic. Possible access specifiers is public. Variables are by default public, static and final. We cant access base class members using super key word. All are abstract methods. No non abstract methods. Interfaces are implemented usingimplements key word.

MULTIPLE INHERITANCE USING INTERFACES interface father { float h1=5.8; void property(); } interface mother {

float h2=5.5; void property(); } class child implements father, mother { float hc=(h1+h2)/2; void property() { System.out.println(x property); } void showheight() { System.out.println(hc); } } class Demo { public static void main(String args[]) { child x=new child(); x.property(); } } Interface i1 is having three methods m1,m2,m3. Interface i2 is having two methods m4,m5. Then if I implement i1,i2 in same other class. We need to provide implementation for any method then make that class as abstract. PACKAGES Package is the place to store the classes. Group of classes is called the package. Package can have classes and also interfaces. We can write our own packages. Some of the predefined packages are java.io, java.lang

Advantages: o o o o It isolates the classes and interfaces. Package is like a directory. API Application programming Interface. API will have documentation(Help)/(javap)

How to write packages:Syntax: package <package name>; // This must be first statement in the program Ex: Package p1; Public class Abc { public void show() { System.out.println(Iam in Package); } } javac d . Abc.java Here after compilation we shall get Abc.class and this class will be strode in p1 not the current directory. That means one sub directory with the name p1 is ging to be created under current directory.

How to use above package: import p1.*; (or) import p1.Abc; class Demo { public static void main(String args[]) { Abc o=new Abc(); o.show(); } } Output: Iam in package1. Advantages: o Isolate the classes and interfaces. o Code reusability. How to add one more class for package p1? Xyz.java Package p1; Public class xyz { public void disp() { System.out.println(Iam in package 1 and xyz class ); } }; c:\satya> -d . Xyz.java We shall get xyz.class which is stored in p1 package.

How to use above two classes in a program: Import p1.Abc; Import p1.Xyz; Public class { public static void main(String args[]) { Abc o1=new Abc(); Xyz o2=new Xyz(); o1.show(); o2.disp(); } } c:\> javac Demo.java c:\> java Demo Output : Iam in package1 Iam in package1 and Xyz class. How to use interfaces in packages: There is a package called java.util, in this package Date class is available. Date d newDate();

Now d is going to have current date and time of the system. Mydate.java Package p2; Pubic interface mydate { void showdate(); } javac d . mydate.java Now we will get a class file[my date.class] Mydateimp.java Package p2; Import java.util.Date; Import p2.mydate; Public class mydateimp impolements mydat { public void show() { System.out.println(d); } } Demo.java Import p2; Public class Demo extends MydateImp { public static void main(String args[]) { Demo o1=new Demo(); o1=showdate(); (or) MydateImp o2=new MyDateImp(); o2.showdate(); } } Output: Iam in package p1.p2.p3 Note: Package p1; After executing the statement if p1 is already available then it will use the same p1. If p1 is not available then it creates a new p1(sub directory). EXCEPTION HANDLING Errors are three types: 1.Compile time errors 2. Run time errors 3. Logical errors. Compile Time errors: Public class Abc { public static void main(String args[]) { System.out.println(SATYA) } } In above example after System.out.println there is no semicolon. Hence it is compile time error. Compile time error = Syntax error.

Compile time errors are detected by compilers. Run Time Errors: Public class Abc { public static void main() { System.out.println(SATYA); } } In above example there is no (String args[]) in public static void main(). Hence it is runtime error. Run time errors = Exception. Handling system errors is called Exception handling. Run time errors are detected by JVM. Can we call compile time errors or exception? Yes, Because according sun exception = Any exceptional invent occur in the program is called exception. What is the difference between error and exception? Errors cant handle by the programmer. But exceptions can be handle by the programmer.

Logical Errors: main() { int sum; int a=10; sum+=a; System.out.println(sum); } Output : Garbage value In above example we are getting the result garbage, because intervals sum is not initialize any value. Hence it is called logical error. Logical error cant be detected by the compiler. Logical errors cant be detected by J.V.M. Demo.java Public class Demo { public static void main(String args[]) { int n=abc.length(); int a=50/n; System.out.println(a); System.out.println(Hello); } } javac Demo.java java Demo 20 abc Output: 25 Hello javac Demo.java java Demo

Here run time error (Exception occurred). How to handle the Excepitons ? Using try, catch blocks. Demo.java Public class Demo { public static void main(String args[]) { try { int n=abc.length(); int a=50/n; System.out.println(a); } catch(Arithmetic Exception ae) { System.out.println(ae); // ae, will have details of exception. } finally { System.out.println(Hello); } } } java Demo.java java Demo 20 abc abc.length()=2=n a=50/2=25; Output: 25 Hello In this case there is no exception from try block. Thats why catch block statements are executed only when there is exception from try block. Java Demo abc.length() = 0 =n a=50/0 Exception occur. Now catch() block will be executed. Output: Hello In above case there is a exception from try block. Thats why catch block will be executed. Note: try { ____ ____ } Generally we are going to write the statements in try block which are going to throw an exception. catch(Exception name obj) { ___ ___ }

When there is a exception try block then all the catch block statements are executed and that exception details is available in object. finally { ____ ____ } Finally block statements are going to be executed when there is no error or there an error. Hence generally in finally block we are going to write file closing operations, memory release operations and etc. Without try block catch block will not exist. Without catch block try will exist. A try can have more than one catch. How to handle more than one exception? For each exception we need write separate catch block. Ex: Demo.java Public class Demo { public static void main(String args[]) { try { int n=abc.length(); int a=50/n; System.out.println(a); int x[]={10,20,30,40,50}; x[50]=200; } catch(Arithmetic Exception ae) { System.out.println(ae); } catch(ArrayIndexOutOfBoundsExceptin ob) { System.out.println(ob); } } } javac Demo.java java Demo 20 Satya abc.length=2=n. a=50/2=25. Output: 25 Now one exception came from try block that exception AIOOBE. Hence corresponding catch block will be executed. Java Demo abc.length = 0=n a=50/0 Hence corresponding catch block will be executed. In this case the 2nd catch block will not be executed. Note: For one try block we can write more than one catch block. But only one catch block will be executed.

THROWS: If we dont want to handle the Exceptions we can write throws. Ex: Demo.java Public class Demo { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); System.out.println(s); } } In above example br.readLine() throw an exception called IOException. Here we are not handle the IOException. Thats why we use throws Exception at the command line. THROW:: Public class Demo { public static void main(String args[]) { int a=5; System.out.println(Hello); try { if(a<10) throw new RunTimeException ( a value is less than 10); System.out.println(Hai); } catch(RunTimeException rte) { System.out.println(rte); } } } javac Demo.java java Demo Output: Hello If(5<10) True a value is less than 10. In above example RunTimeException is the class. Throw must be used in try block. Throw generally used to send our own exceptions details. In above example a<10 is******* How to throw more than one Exceptions using throw? throws E1, E2, E3, Ex: throws IOException, ArithmeticExceptin All exceptions are classes. IOException ClassNotFoundException FileNotFoundException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException ArithmeticException RunTimeException

InterruptedExcepiton NoSuchMethodException

All these exceptions are under the throwable class. throwable class is a sub class of Object class . Object class is available in java.lang package. Hence in java object class is super class. Object

Throwable

Exception

Error

IO Exception

Interrupted

Run time Exception

Exception

File Not Found Exception ception

EOF Exception

Index Out of Bound

Arithmetic

Exception

Ex-

Array Out Of Bound Exception Memory Management in JAVA:-

String Index Out Of Bound

Exception

In c or c++ when we allocate memory dynamically. After completion of the program it is our responsibility to delete the memory. If we are not doing de allocation then we cant reuse that memory this is called garbage collection. In java no need to take care about de allocating the memory. Garbage Collector automatically de allocates the memory in java. We can run Garbage Collector on demand by calling gc(). Methods are totalMemory() and freeMemory(). When an object is no longer referred to any variable then java automatically clean the memory used by that object. Memory is automatically allocated if needed on both stack, heap area. That memory is freed by GC.

Which method is used to GC? finalize().

Each class in java have a finalize()? Yes. finalize() belongs to java.lang.Object class. Which a. b. c. Ans:: is true? A class have only one finalize(). finalize() mostly used in simple class. finalize() overloading is not possible. Both a and c are true.

When we write finalize() for your class, we are over riding a finalize() from super class (Yes/No) ? Yes. When variables goes out of the scope then that variables automatically referred by GC. Java GC runs as ahigh priority thread, waiting for low priority thread. GC, will run immediately when system is out of memeory (Yes/No) ? Yes. When your program wish to run thr GC? a. Before it enters a compute intense of section of code. b. Before it enters a memory intense section of code. c. Before objects are finalize. d. When it knows there will be some idle time. Ans: a, c andd. Objects pass by address, methods are pass by value. What will happen to exception object after exception handling? It will go to GC and free the memory. String []S; = String []S; = String []. Which is used to get the values of instances variables? Dot(.). Which cast will be used to convert longet to smaller? Explict. Ex: int a; Int x=20L; Int a=(int)x; Each new object has its own distinct set of instance variables? Yes. Each object has its copy of the instance of its class? Yes. The instance variable of each objects are separated from the other objects? Yes. How many ways we can use dot operator? 1. To store some value in instance variable. 2. To access the instance variable. 3. To call the methods. Which a. b. c. are the keywords in java? Null Sizeof Thread

d. e. Ans:

Extends Syncronise. d and e.

What are the different modifiers in java? Public, private, protect, default, static, transient, final, volatile, and abstract. In above sentence first four are called access modifiers. A class can be sub class of it self? Yes. What modifiers may be used with top level classes? Public, final and abstract. Any user defined exception is a sub class of exception class. A package is used to separate the hierarchy of the classes. All standard class of java are included in java.lang package. Can anonymous class implements interface? Yes. What is a market interface? Interface without methods is called marker interface. Ex: Remote, Clonable, Serializable. Object class is super class for all other classes? Yes. Some of the methods in object class which are declared as final? Getclass(), notify(), notifyall(), wait(). Tell me some of the interfaces defined in java.lang package? Cloneable, Runnable, comparable. Class class can be used to load other classes? Yes. Class Loader class can be used to load other classes? Yes. To clean the buffer which method is used in java? Flush(). Why java is robust? Because of strong exception handling. Why java is safe? 1. No pointers. 2. It have strong type checking. 3. exception handling. 4. security. Difference between inheritance and composition? Composition: 1. It is another way to reuse the code. 2. with this concpt we can create an object of another in the current clas and call the methods of other class in the current class. 3. Here current classes not connect with another class. 4. It models has a relationship. Ex: Class abc

{ disp() { ___ ___ ___ } } class Demo { public static void main(String []arg) { abc o1=new abc(); o1.disp(); } } In above example there is no link between Abc and Demo but in inheritance there is a link between Abc and Demo. In inheritance all methods available in Abc is accessed Demo also. But in composition all methods are nto accessed only by calling methods. Ex: for Inheritance Class Abc { disp() { ___ ___ } } class Demo extends Abc { public static void main(String args[]) { Abc o1=new Abc(); O1.disp(); (All methods of Abc are accessible here) } } Un checked Exceptions = Runtime Exception Checked Exceptions = Compile time Exception

Note:

Wrapper Classes: Wrapper class is a class whose object can stores the Primitive data type. Wrapper classes contain only one field. Wrapper classes belongs to java.lnag package. DATA TYPE Char Byte Int Long Float Double WRAPPER CLASS Character Byte

Integer Long Float Double Character class: Constructor is:: character (char ch); Methods: Static boolean isDigit(ch); It returns True when ch is between 0 to 9. Static boolean isLetter(ch); It returns True when ch is between a to z (or) A to Z. Static boolean isUpperCase(ch); It return True when given ch is in Upper Case. Static boolean isLowercase(ch); It returns True when given ch is in Lower Case. Static boolean isSpaceChar(ch); It returns True when ch is coming from space bar. Static boolean isWhiteSpace(ch); It returns True when given character ch is a tab or Enter key. Static char toUpperCase(ch); It converts given character ch into Upper Case. Static char toLowerCase(ch); It converts given character ch into Lower Case. Ex: Import java.io.*; Class Demo { pubic static void main(String args[]) throws IOExcepiton { BufferedReader br= new BufferedReader(new InputStreamREader(System.in)); System.out.println(Enter a Character :: ); Char ch=(char)br.read(); If(character.isDigit(ch)) System.out.println(Character is Digit); else If(charcter.isUpperCase(ch)) System.out.println(Character is in Upper Case); else System.out.println( I dont Know); } } Javac Demo.java Java Demo Output: Enter a Character:: P Character is in Upper Case Enter a Character:: ctrl+Z I dont know. Byte class: Constructor is:: Byte(byte b); (or) Byte(String s); Methods: Int toCompart(byte b); It returns positive or negative or zero. Ex: Import java.io.*;

Class Demo { public static void main(String args[]) { BufferedReader br=new BufferedReader(new InputStream Reader(System.in)); System.out.println(Enter a byte no:: ); String s= br.readLine(); // Create Byte object Byte b1=new Byte(s); System.out.println(Enter a byte no: ); String s1=br.readLine(); // Create Byte object Byte b2=Byte.valueof(s1); Int n=b1.CompareTo(b2); If(n==0) System.out.println(Both are Same); If(n>0) System.out.println(b1 is big); If(n<0) System.out.println(b2 is big); } } javac Demo.java java Demo Enter a byte no :: 35 S=35 B1=35 Enter a byte no :: 23 S1=23 B2=23 Int n=35.toCompare(23); N=12 (35-23) n>0 Output: B1 is big Enter a byte no :: 500 S=500 B1=500 (wrong) Enter a byte no :: 600 S1=600 B2=600 (wrong) Output: Error Because 500 and 600 are not hold into a byte. Integer Class: Ex: Import java.io.*; Class Demo { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(Enter a number :: ); String s=br.readLine(); Int n=Integer.parseInt(s); System.out.println( Decimal is : +n); System.out.println(Integer.toBinaryString(n)); System.out.println(Integer.toOctalString(n)); System.out.println(Integer.toHexString(n));

} } javac Demo.java java Demo Enter a number :: 45 S=45 N=45 Output: Decimal is :: 45 101101 55 2D In the above program Integer.toBinaryString(n): It is a method in Integer class. It converts given number into binary string. Integer.toOctalString(n): It is a method in Integer class. It converts given number into octal string. Integer.toHexString(n): It is a method in Integer class. It converts given number into hex string. Float class: Constructor is: Float(float no) (or) Float (String s) Methods: Float flaotValue(); Double doubleVlaue(); String toString(); Static flaot ParseFlaot(String s); It throws an exception called NumberFormat Exception. Double class: Constructors is: double(double no) (or) double (String s) Methods: Float flaotValue(); Double doubleVlaue(); String toString(); Static double ParseDouble(String s); It throws an exception called NumberFormat Exception. Math class: Math class is available in java.lang package. Methods: Static double Sin(double arg) Static double Cos(double arg) Static double tan(double arg) Static double log(double arg) Static double sqrt(double arg) Static double pow(arg1,arg2) Static double ceil(arg1,arg2) Static double floor(arg1,arg2) Static double max(arg1,arg2) Static double min(arg1,arg2) Static double abs(double arg) Static double toDegree(arg) Static double toRadius(arg) Static int round(double arg) Ex: Round(4.6) 5

Round(4.4) 4 Static double random() It can generates Random Numbers. // Example program to generate random numbers between 0 to 10 class Random { public static void main(String args[]) throws Exception { while(true) { double d=10*(Math.random()); int i=(int) d; System.out.println(i); Thread.sleep(200); If(i==0) System.exit(0); } } } Thread.sleep(200) : Thread is a class vailable in java.lang package. It sleeps the process 200 mille seconds. Math.random() : It generates Random numbers between 0 to 1 Ex: .231, .56, .49871 . . . But we want numbers between 0 to 10, hence multiply the results with 10 Ex: Double d= 10*.23 D=2.3 Now convert it into integer Int i=(int) 2.3 I=2 LINKED LIST It is a class available in java.util package. To create linked list object LinkedList ll=new LinkedList(); LinkedList class having some methods which is shown below. ll.add(string):- It adds an object apple into the linked list. Ex: ll.add(apple); ll.add(pos,string):- It adds the string object at second position in the linked list. Ex: ll.add(2,xyz); ll.removeLast():- It removes last object from the linked list. ll.removeFirst():- It removes first object from the linked list. ll.remove(pos):- It removes object in the given position. Ex: ll.remove(2); ll.set(pos,new element):- It replace old object which is at given position by new element. Ex: ll.set(2,Satya); import java.io.*; import java.util.*; class Demo { public static void main(String args[]) throws IO Exception { // create list LinkedList ll=new LinkedList(); ll.add(abc); ll.add(xyz);

ll.add(pqr); System.out.println(ll); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Int c=0; Int pos=0; While(c<=4) { System.out.println(1.Add); System.out.println(2. Remove); System.out.println(3. Change); System.out.println(4. Exit); System.out.println(Enter your choice :: ); C=br.read(); Switch { case1:System.out.println(Enter position :: ); pos=br.read(); System.out.println(Enter an object :: ); String s=br.readLine(); ll.add(pos,s); break; case2:System.out.println( Enter position :: ); pos=br.read(); ll.remove(pos); break; case3:System.out.println(Enter position :: ); pos=br.read(); System.out.println(Enter new element); String s=br.readLine(); ll.set(pos,s); break; default:return; } } } } Output: Abc Xyz pqr 1. Add 2. Remove 3. change 4. exit Note: System.out.println(ll) it is going to display all the elements in linked list at a time. How to display LinkedList elements one by one? If we want to display elements one by one then attach integrator interface to linked list object. Iterator i=ll.Iterator(); Iterator interface have has next method. Objects will take memory but instance doesnot take memory. Replace x.statement with the followint statements. Iterator i=ll.Iterator(); While(i.hasnext()) System.out.println(i.hasnext());

ARRAYS:

1. 2. Ex:

Arrays available in java.util package. Arrays class having some methods i.e. sort(), binarysearch() and equals(). a. Arrays.sort(array); It sorts all the elements in array (assending order) b. Arrays.sort(arr,5,10); It sorts e,ements 5th ,6th,7th,8th,9th which are there in arr array. c. Arrays.binarysearch(arr,elem); It returns the position (+ve) if given element is found in the arr array, else it returns ve value. d. Arrays.equals(arr1,arr2) It checks weather given two arrays are equal or not. Ex: Import java.util.*; Import java.io.*; Class demo { public stativ void main(String args[]) throws Exception { int a[]=new int[50]; BufferReader br=new Bufferreader(new InputStreamReader (System.in)); System.out.println(Enter no. of elements you want :: ); Int n=br.read(); For(int i=0;i<n;i++) { System.out.println(Enter element :: ); A[i]=Integer.ParseInt(br.readLine()); } displays (a,n); System.out.println (After Sorting); Arrays.sort (a); Display (a,n); Int no=Arrays.binarySearch (a,20); If(no<0) System.out.println (Given element is not found); Else System.out.println (Given element is not found); Display (int a [], int n) { for (int i=0; i<n;i++) System.out.println (a[i]); } } } Output: Enter no. of elements you want :: 3 Enter element :: 10 Enter element :: 40 Enter element :: 30 After Sorting:: 10 30 40 Given element is not found Arraylist: Arraylist al=new ArrayList (); ArrayList al=new ArrayList (50); ArrayList is a class available in java.util package. ArrayList is having the following methods

al.add(apple); Al.add(2,apple); Al.remove(mango); // It removes an object mango from array list. Al.size (); // It display no. of object available in the array list. ArrayList objects grow dynamically. ArrayList objects cant be synchronizing. Vector: The default vector capacity is 10. 1. Vector is a class available in java.util package. 2. Vector class is like ArrayList class. But ArrayList objects cant be synchronized , Vector objects can be synchronized. 3. Vector class objects grow dynamically. 4. Creating an object for Vector class. Vector v1=new Vector(); Vector v1=new Vector(50); 5. Vector class is having some methods as shown below. V1.add(apple); V1.get(2); // It retrives the object at 2nd location. V1.remove(2); V1.clear(); // It removes all the objects from the vector class. V1.capacity(); // It returns the size of the Vector. V1.lastIndexOf(object); Ex: v1[abc,xyz,abc,pqr] V1.lastIndexOf[abc]; // It displays the index of last occurrence V1.indexOf(object); // first occurrence. Threads: If up do single work at a time then it is called single task. If up does more than one work at a time then it is called multi tasking. Multi tasking: 1. Process based Multi tasking: Let p1, p2, p3 are three programs available for execution. If up executes three programs simultaneously then it called process based multi tasking. NOTE: up will do only one work at a time but it is going to switch form on e program to another program with in fraction of mille seconds. Hence we can see the results like multi tasking based on the time factor up switches between the programs. Ex: p1 p2 p3 10 min. 2 min. 4 min. 10 min. p1 (10 min.) 2 min. p2 (12 min.) 4 min. p3 (16 min.) (Timing given for each program)

Ex:

Let there is a program p1 and it is having instructions like Instruction 1: 2: 3:

n:

In above example every instruction is dependent on another insturciton. Hence it is having Single Thread Control. 2. Thread based multi tasking: Let there is program called p1 and it is having three blocks of code and no block is depending upon another block in this case assign each block as a thread. Hence this three block of code will be executed simultaneously Within the program. Each thread will have its own path for execution. Achieving multi tasking within the program is called Thread based multi tasking. Executing more than one thread simultaneously is called Multi Thread.

Block 1

Block 2

Block 3

Ex:

(Thread Based) Word (Because when ever we are typing it is also displaying simultaneously) Servers Browsers

Advantages with Thread based Multi Tasking: 1. Economic 2. Maximum utilization of --3. To design servers. 4. To handle Multi Programming: Executing more than one program simultaneously is called Multi Programming. Multi Programming = Multi Tasking

Multi programming is always Multi Tasking, but Multi Tasking is not Multi Programming. Process: Program under execution Unit of work under execution Set of activities under execution. Process was introduced multi programming.

Thread:

In java thread is a class, available in java.lang package. Thread is nothing but another way (path) of execution of the same program. Thread class is having following methods: Start (): It creates a new thread and calls the Run method. Stop (): It terminates the thread. Run (): In Run method we are going to provide the code Resume (): Pause ();

for execution.

{ }

Stop() cant be over ridden Start (), Run () can be over ridden. The Run() internal code is, run()

THREAD A. B. C. D. Communication is between the threads. Hence low cost. No extra resources are requiring. Because of above two reasons thread is a light weight task. Here context switching is there.

PROCESS a. b. c. It is heavy weight task. Because of the following reasons. For communication it requires IPC (Inter Process Communication) Hence it is costly. Extra resources are requiring.

Why Multi Tasking? Let there are three programs p1, p2, p3. To complete p1 it takes three hours. To complete p2 it takes six hours. To complete p3 it takes one minute. If no Multi Tasking, which means after executing p1, program two is executing after executing p2, program p3 will be executed. Hence total execution time is 9.1 hours. Class Test { String x; Test(String m) { x=m; } public void show() { for (i=0; i<100;i++) System.out.println(x); } } class Demo { public static void main (String []args) { Test t1=new Test(Hello); Test t2=new Test(Satya);

T1.show(); T2.show(); } } Output: Hello Satya Hello Satya 100 times 100 times In above example Hello is printed 100 times then Satya will be printed 100 times. If we want to print the result like Hello we are move to Threading Concept. Single Threading: How to create thread? Extends your class to Thread (or) implements the Runnable interface. Write code in run() method. Thread t1=new Thread(obj, [thread name]); Write start() method. Ex: Class Test extends Thread { String x; Test(String m) { x=m; } pubic void run() { for (i=0;i<100;i++) System.out.println(x); } } class Demo { public static void main(String args[]) { Test o=new Test(Hello); Thread t1=new Thread(0); T1.start(); // It creates a new thread and invoke run(). } } Output: Hello Hello ------Hello (100 times) How to stop the thread in between? Import java.io.*; Class Test extends Thread { String x; Boolean stop=false; Test(String x) { x=m;

} public void run() { for(i=0;i<100;i++) { System.out.println(x); If(stop) Return; } } class Demo { public static void main(String args[]) { Test o=new Test(Hello); Thread t1=new Thread(o); T1.start(); // accept one key. System.in.read(); t1.stop=true; } } Output: Hello Hello ------Multi Threading: Ex: Class Test Extends Thread { String x; Test(String m) { x=m; } public void run() { for(i=0;i<100;i++) System.out.println(x); } } class Demo { pubic static void main(String args[]) { Test o1=new Test(Hello); Test o2=new Test(Satya); Thread t1=new Thread(o1); Thread t2=new Thread(o2); T1.start(); T2.start(); } } Output: Hello Satya -----

(100 times)

--Note: Some times we may get the result kike shown below. Output: Hello Satya Hello Satya Satya ------Because system by default will give some priority value for each thread. How to set our own priorities for thread? Threads priorities are between 1 to 10. Normal thread priority is 5. To set thread priorities use the following statements: T1.setPriority(2); T2.setPriotity(3); Ex: Class Test Extends Thread { String x; Test(String m) { x=m; } public void run() { for(i=0;i<100;i++) System.out.println(x); } } class Demo { pubic static void main(String args[]) { Test o1=new Test(Hello); Test o2=new Test(Satya); Thread t1=new Thread(o1); Thread t2=new Thread(o2); T1.setPriority(2); T2.setPriority(3); T1.start(); T2.start(); } } Output: Hello Satya Hello Satya ------Note: In above example for threads system will give some names. It is better way to give your own names. How to set the names for threads? T1.setName(thread1); How to get the thread name? T1.getName(); // It returns a string, that is thread name. How to know which thread is running at given time? Thread.CurrentThread().getName(); Current Thread : It is a method in Thread class. It tells which thread is running.

getName() : It gives name of the thread. Explain join method? Join() is the method in thread class. When main thread results will depending upon the child thread. In this case join() method waiting for main thread until child thread completes. What is the difference between extend a class to the thread class and implementing a class to Runnable interface? 1. If we extend our class to thread class then the run method is over ridden. Ex: Class Thread { run() { dummy } stop() { --} start() { --} } class abc extends Thread { run() { --} } interface Runnable { run(); } Runnable is the interface provide by them. In run() there is a abstract method called Run(). If we implements runnable() method in this case run() is not over ridden. Run() only implemented. Thats why we are using class abc implemts Runnable. Ex: Class abc implements Runnable { ------} Can we provide Run() method more than one time in the class(y/n)? No. Thread Synchronization: Class Test implements Runnable { int A=1; int w; Test(int i) { w=I; } public void Run() { System.out.println(Available berth : +A); If(A>=w) { String x=Thread.CurrentThread().getName(); System.out.println(w+berth allotted for +x); Try {

Thread.sleep(2000); A=A-w; } catch(interruptedException I) { } } else System.out.println(Sorry no berth); } } class Demo { public static void main(String args[]) { Test ob=new Test(); Thread t1=new Thread(ob); Thread t2=new Thread(ob); T1.setName(first); T2.setName(seond); T1.start(); T2.start();; } } When more than one thread is acting on the same object, in this case allow only one thread to access object at a time. That means another thread has to wait until first thread completed. In above example one seat is allotted two persons because here two threads are acting on the same object at a time. Thats why above code is not synchronized. Then it is called Thread unsafe. How to synchronized above code? Class Test implements Runnable { int A=1; int w; Test(int i) { w=I; } public void Run() { synchronized(this) { System.out.println(Available berth : +A); If(A>=w) { String x=Thread.CurrentThread().getName(); System.out.println(w+berth allotted for +x); Try { Thread.sleep(2000); A=A-w; } catch(interruptedException I) { } } else System.out.println(Sorry no berth); } }

} class Demo { public static void main(String args[]) { Test ob=new Test(); Thread t1=new Thread(ob); Thread t2=new Thread(ob); T1.setName(first); T2.setName(seond); T1.start(); T2.start();; } } Output: W=1 Available berths : 1 T1 If(A>=w) If(1>=1) True T1 X=first 1 berth allotted for first A=0

T2 W=1 T2 Available berths : 0 If(o>=1) False Sorry no bearth. Give life cycle of a thread?

Start() Resume () Notify() (or) notify All() I/O completion Sleep interrupt Yields() expires I/O Sleep() stop() wait() Suspend() request

dispatch()

Where yields() is a method and dispatch is not a method. Wait(), notify(), notifyAll() are inherited form object class or not? Yes. Note: wait(), notify(), notifyAll() are declared as final in object class. What is a mutex object? It is synchronized. It is licked. How to test whether thread is alive or not? t.isAlive(); // It returns true when thread is alive. How to set the priorities?

Note:

T1.setPriority(3); (or) t1.setPriority(Thread.MAX-PRIORITY-7); // (10-7) = 3 Thread class is having three constants MAX-PRIORITY = 10 MIN-PRIORITY = 1 NORM-PRIORITY = 5

Every java program will have a default thread called main thread. Class Demo { public static void main(String args[]) { Thread t=Thread.CurrentThread(); System.out.println(t); System.out.println(t.getName()); System.out.println(t.getPriority()); } } Output: [main, 5, main] main (t.name) 5 Note: Runnable interface is having only one method that is run(). What is default thread group? main. Hence our thread are sub groups of main. What is Daemon thread? Daemon thread is a service thread. It servers other threads. Ex: Garbage collector. How to know whether thread is Daemon thread or not? System.out.println(t1.isDaemon()); It returns true when t1 is Damon thread, other wise false. How to convert ordinary thread into Daemon thread? Thread t=new Thread(0; t.setName(One); t.setDaemon(true); // It converts normal thread into Daemon thread Garbage collector thread belongs to which priority? Low priority. Daemon thread is low priority thread? Yes. Suspend() is used to terminate the thread? No. What is the data type for the parameter of the sleep()? Long.[sleep(<long value>)] What are the threads will start the java program? Main thread, finalizer, Reference handler, signal Dispatcher. What are the different levels of lockings using the synchronized key word? Class level, method level, block level, object level locking. How can you achieve thread synchronization? Using monitors.(programs with synchronized block). Every object with synchronized method is called monitor. Ex: class Demo { public synchronized void disp() { --}

} What is the procedure to own the monitors by many threads? Not possible. How many threads can access a monitor at a time? Only ONE. How to create our own thread groups? ThreadGroup tg=new ThreadGroup(Satya); How to know the parent thread name? System.out.println(tg.getParent()); Output: main What is the disadvantage with synchronization? Program may slow down. Only one thread can access at a time. How to improve the performance of the program? By writing block level synchronization. What is Dead block? If program or thread (in multi threading) further not processing that means simply hanging then that situation is called Dead block. It is runtime error. Explain starvation thread? If there are more threads in this case there may be a chance particular thread may not get the up. That thread is not executed by the up. Those threads are called Starvation threads. CLONE: 1. Take one object, clone that object then we will get a new object which is similar to existing object. 2. Getting extra copy of an object from existing object is called cloning. Can we create an object without using new? Yes. Emp e1=new Emp() Emp e2=e1; Here e2 is not an object it like the reference. Disadvantage here is if we modify e1 and e2 will be affected and/or if we modify e2, e1 will be effected. To overcome this disadvantage we are v-moving to cloning. Why cloning object? Cloning objects are individual objects. How to create cloned objects? Implement cloneable interface in our class; call clone() of super class. That means clone() is available in object class. Why cloneable interface is called tagged interface or marked interface? Cloneable interface is not having any method. Why cloneable interface? It allow for cloning the class object. Note: cloneable interface is like shown below Interface cloneable { } Class Emp implements cloneable { int id, String name; Emp(int id, String name) { this.id=id; this.name=name; } void disp() { System.out.println(id);

System.out.println(name); } Emp myclone()throws cloneNotSupportedException { return((Emp)super.clone()); // super.class() return an object of object class thats why convert that object into our class (Emp)object that is by using(Emp) super class. } } class Demo { public static void main(String args[]) throws CloneNotSupportedException { Emp e1=new(Emp 101,Satya) E1.disp(); Emp e2=e1.myclone(); E2.disp(); } } Output: 101 This result from original object(e1). Satya 101 Satya Note: This result from cloneable object(e2).

If I modify e1, e2 will not be effected or if I modify e2, e1 will not be effected.

We can also do above program by over riding clone method of object class. Class Emp implements cloneable { int id; String name; Emp(int id, String name0 { this.id=id; this.name=name; } void disp() { System.out.println(id); System.out.println(name); } public object clone() throws CloneNotSupportException { return super.clone(); } } class Demo { public static void main(String args[])throws CloneNotSupportException { Emp e1=new EMP (101, Satya); e1.disp(); Emp e2= (Emp) e1.clone (); e2.disp(); } }

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