Java

Share Embed Donate


Short Description

i...

Description

12.02.2010 What is Java? Java is a technology from Sun overtaken by Oracle developed by James Gosling in 1991 with initial name ‘Oak’ with the goal to work with any kind of device. It was renamed to Java in 1995. It is divided in four sub-technologies 1. 2. 3. 4.

Java SE (Java Standard Edition) Java EE (Java Enterprise Edition) Java ME (Java Mobile Edition) Java Fx

Resource http://java.sun.com Tools Required 1. JDK (Java Development Kit) 2. JRE (Java Runtime Environment) 3. IDE (Integrated Development Environment) a. NetBeans b. Eclipse c. Visual Age d. JDeveloper e. JCreator f. Etc. Versioning in Java Java provides two kinds of version 1. Product Version 2. Developer Version Developer Version Deals with JDK      

1.0 1.1 1.2 1.3 1.4 1.5

 

1.6 1.7

Product Version Product version deals with Java as product which shows the reliability, scalability and strength of Java.        

1.0 1.1 1.2 (Java 2) 1.3 1.4 5.0 6.0 7.0

Rules in Java 1. Java is case sensitive 2. File extension will be .java 3. Compiler used is JAVAC.EXE Introduction to PATH PATH is an environmental variable used to hold list of folders to search an executable file (.exe, .com, .bat) in given folders. Setting temporary PATH SET PATH=%PATH%;C:\jdk1.6\bin Set Permanent Path My Computer  Properties  Advanced  Environmental Variables  System Variables  PATH  Edit…  Add your path Syntactical Rules in Java 1. All keyword and package names must be in lower case 2. All class and interface names starts with upper case. (PascalCase) a. Math, System, BufferedReader, InputStreamReader 3. All fields and methods starts with lower case (camelCase) a. length(), parseInt() Features of Java 1. Simple and Sober

2. 3. 4. 5. 6. 7.

Secure Object Oriented Multi Threaded Portable Platform Independent Robust a. Java provides a big set of libraries for almost any purpose b. Java provides built-in garbage collector for automatic memory management c. Java provides in-built features exception handling to trap the runtime errors

13.02.2011 What makes Java Platform Independent? Is JVM is platform Independent? Java provides a software called JRE (Java Runtime Environment) which contains sub softwares like Java Virtual Machine (JVM) and Garbage Collector. JVM contains other software like Class Loader, Code Verifier and Just-in-time compiler (JIT) .java  JAVAC  .class (byte code language)  JVM (Class Loader  Coder Verifier  JIT  Binary Code)  Execution JVM is a machine dependent software but makes the Java platform Independent. Writing First Java Program 1. File Name must be .java 2. Every executable class must have an entry point called main() a. public static void main(String args[]) Hierarchy in Java JAR File  package  class  field, methods and static objects JAR is Java Archive. It is a compressed file created from JAR.EXE tool. It contains a set of packages. A package is a collection of related set of class. 

   

java.lang o A package that provides commonly used classes o Math, String, System, Integer, Float, Double, Character etc. o It is by default java.io java.util java.awt java.awt.event

     

javax.swing java.sql javax.servlet javax.servlet.jsp javax.servlet.jsp.tagext etc.

Working with General Input/Output Operations -

-

Java provides in-built object inside System class o in o out o err in is a static object of InputStream class from java.io package out and err are the static objects of PrintStream class from java.io package

Methods of PrintStream class -

print() println() printf()

//First.java class Sample { public static void main(String args[]) { System.out.printf("Hello to Java"); } } Compiling the Program JAVAC Example JAVAC First.java  Sample.class Running a class Use JAVA.EXE tool JAVA Example JAVA Sample File naming rules in Java

1. 2. 3. 4.

A file name can be upto 255 characters including space and extension A program can have many classes All or none of the classes can have the main() Program name and class name can be same or different except if the class is public then both must be same

Using NetBeans 6.9.1 public class Sample { public static void main(String[] args) { int a=5,b=6; System.out.printf("Product of %d and %d is %d",a,b,a*b); } }

Data Types in Java Special keyword used to define type of data and range of data. Can be of two types 1. Primitive Types 2. User Defined Types Primary Types can be Integrals (All are signed) 1. byte – 1 byte 2. short – 2 byte 3. int - 4 bytes 4. long - 8 bytes Floating 1. float - 4 bytes 2. double - 8 bytes Characters 1. char

- 2 bytes (Unicode)

Booleans 1. boolean – 2 bytes Literals or Constant Values The values that we use from our side for assignment or some expression are called as literals. Integrals -

Default is int Use l or L with long as suffix

o int num=10; o long p=5L; Floatings - Default is double o Use f or F with floats o double num=5.6; o float k=5.6; //compile time error o float k=5.6F; //compile time error Character Literals - Enclosed in single quotes o char ch=’A’; String Literals -

All strings are Managed by String class Enclosed in double quotes o String name=”Vikas”;

19.02.2011 Using classes from different packages Use import command To import specific class import ; To import all classes of a package import ; Example import java.io.*; import java.util.Scanner; Using Scanner class of java.util package to read the data from Keyboard Create an object of Scanner class Scanner sc=new Scanner(System.in); Different methods of Scanner class String next() int nextInt() float nextFloat() double nextDouble() Example WAP to input name and age of a person and check it to be valid voter. import java.util.Scanner; class Voter { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.print("Name : "); String name=sc.next(); System.out.print("Age : "); int age=sc.nextInt(); if(age>=18) System.out.printf("Dear %s you can vote",name); else System.out.println("Dear "+name+" you cannot vote"); } }

Importing the static members of the class Use import static keyword Example import static java.lang.System.*; import static java.lang.Math.*; Full Code import static java.lang.System.*; import java.util.Scanner; public class Voter { public static void main(String[] args) { Scanner sc=new Scanner(in); out.print("Name "); String name=sc.next(); out.print("Age : "); int age=sc.nextInt(); if(age>=18) out.printf("Dear %s you can vote", name); else out.printf("Dear %s you cannot vote",name); } } Reading data using BufferedReader class of java.io package When we input data from keyboard (System.in), a stream of bits get passed and provided to object of another class InputStreamReader which convert the bit pattern into a character. These characters get buffered into memory space using another class BufferedReader. Use readLine() method of BufferedReader class to read the data. public String readLine() throws IOException

Wrapper Classes Special classes under java.lang package, corresponding to some data type which provides advance functionality on data types as well conversion from String type to numeric types.

Data Type

Wrapper Class

byte short int long float double char boolean

Byte Short Integer Long Float Double Character Boolean

Example WAP to input a number and convert into octal, hexa decimal and binary. Check a character to be alphabet, digit and special character. public class WrapperTest { public static void main(String args[]) { int num=3456; System.out.println(Integer.toBinaryString(num)); System.out.println(Integer.toHexString(num)); System.out.println(Integer.toOctalString(num)); char ch='$'; if(Character.isDigit(ch)) System.out.println(ch+" is a digit"); else if(Character.isLetter(ch)) System.out.println(ch+" is an alphabet"); else System.out.println(ch+" is special character"); } } Conversion from String type to numeric type datatype variable=wrapperclass.parseDatatype(stringdata); Example int age=Integer.parseInt(br.readLine()); double basic=Double.parseDouble(br.ReadLine()); Mixing Scanner and BufferedReader import static java.lang.System.*; import java.io.*; import java.util.Scanner; public class Mix {

public static void main(String args[]) throws IOException { Scanner sc=new Scanner(in); BufferedReader br=new BufferedReader(new InputStreamReader(in)); out.print("Name "); String name=br.readLine(); out.print("Age : "); int age=sc.nextInt(); if(age>=18) out.printf("Dear %s you can vote", name); else out.printf("Dear %s you cannot vote",name); } } Creating static objects We can define static objects in some class and access them any time in any class import static java.lang.System.*; import java.io.*; import java.util.Scanner; public class MyClass { public static Scanner sc=new Scanner(in); public static BufferedReader br=new BufferedReader(new InputStreamReader(in)); } Using Static objects import static java.lang.System.*; import java.io.*; public class Mix { public static void main(String args[]) throws IOException { out.print("Name "); String name=MyClass.br.readLine(); out.print("Age : "); int age=MyClass.sc.nextInt(); if(age>=18) out.printf("Dear %s you can vote", name); else out.printf("Dear %s you cannot vote",name); }

} 20.02.2011 What is Class? What is Object? What is Reference? How object different from Reference? What is Class? A class is a set of specifications or blueprint about an entity to create similar set of objects. A class defines a set of attributes and behavior about the entity. A class is user defined data type created with class keyword. class { //members } Members inside a class A class can have three kinds of members Fields or Attributes Methods or Behaviors Static Objects Types of class members These members can be categorized in two categories 1. Static or Class Members 2. Non-Static or instance members Class members do not require an object to use them but can be used though the objects. Use static keyword with such members. Instance members always require an object. What is an object? A real entity created based on class specifications is called object or instance. Use new keyword along with special method called Constructor to create an object. To use the object for different operations we need to hold reference of it. =new (); Example Number x=new Number()

Number y=new Number(); What is a Constructor? A constructor is a special method inside a class having some features 1. 2. 3. 4.

Same name as class No return type Used to initialized fields of an object If no constructor is created then default or blank constructor is created automatically, but if create any parameterized constructor then blank constructor is not created automatically, we have to create it, if required. 5. Constructors can be overloaded 6. Constructor can be private as well Note:  

Use JAVAP tool of JDK to view members inside a class. Data can be passed to the instance variable using two ways i. Using constructor ii. Using methods

E.g. JAVAP Number Example 1 Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a method like setNumber(). class Number { double num; void setNumber(double n) { num=n; } double square() //non-static { return num*num; } double cube() //non-static { return square()*num; } double cubeRoot() //non-static { return Math.pow(num,1.0/3); } }

class Test { public static void main(String args[]) { Number x=new Number(); Number y=new Number(); x.setNumber(6); y.setNumber(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); } }

Example 2 Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a constructor. class Number { double num; Number(double n) { num=n; } double square() //non-static { return num*num; } double cube() //non-static { return square()*num; } double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test { public static void main(String args[]) { Number x=new Number(6); Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot());

} } Example 3 Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a constructor or using a method. class Number { double num; Number() { } Number(double n) { num=n; } void setNumber(double n) { num=n; } double square() //non-static { return num*num; } double cube() //non-static { return square()*num; } double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test { public static void main(String args[]) { Number x=new Number(); x.setNumber(6); Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); } }

Example 4 What happens when parameter name and field names are same. In such cases use this keyword to refer the current object class Number { double num; Number() { } Number(double num) { this.num=num; } void setNumber(double num) { this.num=num; } double square() //non-static { return num*num; } double cube() //non-static { return square()*num; } double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test { public static void main(String args[]) { Number x=new Number(); x.setNumber(6); Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); } } Assignment Create a class Customer having fields accno, name and balance. Create constructor to open an account. Create methods deposit(), withdraw() and showBalance().

class Customer { int accno; String name; double balance; Customer(int accno, String name, double opamount) { this.accno=accno; this.name=name; balance=opamount; } void deposit(double amount) { balance+=amount; } void withdraw(double amount) { balance-=amount; } void showBalance() { System.out.println("Current Balance is : "+balance); } } class ICICI { public static void main(String args[]) { Customer c=new Customer(123,"Amit Verma",9000); c.deposit(5000); c.withdraw(3400); c.showBalance(); } } Home assignment Create a class Book having field bookno, title, author, status, lastissuedate and price. Create constructors and methods to create an instance of book. Create method issue(), receive() and isavailable(), getIssueDate(). Test the application with three books. Solution public class Book {

int bookno; String title,author,lastissuedate=null; boolean status=true; double price; public Book() { } public Book(int bookno, String title, String author, double price) { this.bookno=bookno; this.title=title; this.author=author; this.price=price; } String getTitle() { return title; } void setData(int bookno, String title, String author, double price) { this.bookno=bookno; this.title=title; this.author=author; this.price=price; } public void issue(String issuedate) { lastissuedate=issuedate; status=false; } public String getIssueDate() { return lastissuedate; } public boolean isAvailable() { return status; } public void recieve(String rcvdate) { lastissuedate=null; status=true; } public static void main(String[] args) { Book b[]=new Book[3]; b[0]=new Book(12,"Programming in C","Balgurwawmi",600);

b[1]=new Book(13,"Programming in Java","James Gosling",750); b[2]=new Book(15,"Programming in .NET","Microsoft Press",567); b[0].issue("12-Feb-2011"); if(b[0].isAvailable()) System.out.println("Book "+b[0].getTitle()+ " is avaible"); else System.out.println("Book "+b[0].getTitle()+ " is not availble");

} }

26.02.2011 Pillars of OOPs Encapsulation It stats that place all the members of a class under one body. class { //members } Abstraction Java provides four abstraction layers to control the accessibility of members. -

Private o Within the class Public o Anywhere access Protected o In current class or in child class Package (default) o Within the package or current folder

What is a package? How to create a package? How to use a package? How to distribute a package? What is JAR? Package A package is a folder having related set of classes which can be bundled into a JAR or ZIP file. Each of the classes placed in a package must have package command on top. package ; How to create a package? Create a folder to hold your packages. e.g. d:\pkg17 Now decide the package name

e.g. testpackage Now create the classes and place into this package folder. Each of such classes must have package command on top. package testpackage; public class General { public static long factorial(int n) { if(n==0 || n==1) return 1; else return n*factorial(n-1); } } Using the package -

Import the classes of the package Set the classpath to lookup the classes and package on the disc

Set classpath=%classpath%;d:\pkg17; package testpackage; public class General { public static long factorial(int n) { if(n==0 || n==1) return 1; else return n*factorial(n-1); } } Distributing the package Convert the folder into a JAR or ZIP To create the zip file, select all the package and convert into a zip file and set into classpath Example set classpath=%classpath%;c:\testpackage.zip; Creating JAR files (Java Archive) Create JAR file using JAR.EXE tool with options

c – for create t – for Tabulate x – for Extract v – for Verbose f – for File Name JAR cvf Example First goto the folder having packages JAR cvf test.jar . Now set the test.jar file into classpath set classpath=%classpath%;c:\test.jar; 27.02.2011 Polymorphism When an items can perform more than one task, it is called as polymorphism. It is a concept which get implemented using overloading. Java allows only method overloading. When two or more methods have the same name but different number of arguments or type of arguments, called as method overloading. Return type do not participate in overloading. Example Create a class Test having three methods to calculate area of circle, square and rectangle. class Test { public void area(int side) { System.out.println("Square is "+side*side); } public void area(double r) { System.out.println("Square is "+Math.PI*r*r); } public void area(int l, int w) { System.out.println("Area is "+l*w); } }

Inheritance Most important pillar of OOPs which provides re-usability of code. Classes can be at three levels 1. Parent class 2. Super class 3. Child class All classes in Java are child of Object class. Java allows only single inheritance. Use extends keyword to inherit a class into other class. class A { } class B extends A { } If B is a current class, A is super class and Object is parent class. Use this keyword to refer object of current class and super keyword to refer object of super class. Example Create a Num2 having two fields a, b. Create methods to return bigger one and product of those numbers. Create another class Num3 working on three numbers. Also create method for product and biggest one. Use inheritance. class Num2 { int a,b; public Num2(int a, int b) { this.a=a; this.b=b; } public int g2() { return a>b?a:b; }

public int p2() { return a*b; } } class Num3 extends Num2 { int c; public Num3(int a, int b, int c) { super(a,b); this.c=c; } public int p3() { return p2()*c; } public int g3() { return g2()>c?g2():c; } } class IntTest { public static void main(String args[]) { Num3 x=new Num3(4,5,6); System.out.println(x.p3()); } } Method Overriding A method in parent class, re-written in child class with same signature but different contents, is called as method overriding. While overriding we can increase the scope of overridden method but cannot decrease it. class Num2 { int a,b; public Num2(int a, int b) { this.a=a; this.b=b; } public int greatest() {

return a>b?a:b; } public int product() { return a*b; } } class Num3 extends Num2 { int c; public Num3(int a, int b, int c) { super(a,b); this.c=c; } public int product() //overriding { return super.product()*c; } public int greatest() //overriding { return super.greatest()>c?super.greatest():c; } } class IntTest { public static void main(String args[]) { Num3 x=new Num3(4,5,6); System.out.println(x.product()); } }

Method overriding is mainly used for Runtime Polymorphism or Dynamic Method Dispatch (DMD). 05.03.2011 Golden rule of Inheritance A parent can hold reference to its childs and invoke only those methods of child whose signature is provided from parent to the child. Runtime Polymorphism

When reference of a parent is re-used to hold reference of multiple child classes, it is called as runtime polymorphism. It allows to execute the methods of childs using the same reference, it is called as dynamic method dispatch (DMD). It can be done only if method overriding is done. Example class A { public void show() { System.out.println("Calling from A"); } } class B extends A { public void show() //Overriding { System.out.println("Calling from B"); } public void welcome() { System.out.println("Welcome to B"); } } class C extends B { public void show() //overriding { System.out.println("Calling from C"); } } class D { public void show() { System.out.println("Calling from D"); } } class X { public static void main(String args[])

{ A p; //Runtime polymorphism p=new A(); p.show(); p=new B(); p.show(); p=new C(); p.show(); // dynamic method dispatch (DMD) } } Types of classes Java provides three kinds of classes 1. Concrete class 2. Abstract class 3. Final class A class that can be instantiated and can also be inherited, is called as concrete class. It is by default. class X { } A class that is always made for inheritance purpose only but can never be instantiated, such classes is called as abstract class. Use abstract keyword to declare a class as abstract. An abstract class may or may not have any abstract method but if a class contains any abstract method the class must be declared as abstract. A class that can be instantiated but can never be inherited is called as final class. Use final keyword to create such classes. Types of Methods The methods again can be of three types 1. Concrete methods 2. Abstract methods 3. Final methods Concrete methods A method having the body contents and allows to overriding the contents, is called as concrete method. It is by default.

Abstract methods When a method has the signature but no body contents, it is called as abstract method. Such methods can be declared at two places 1. Inside an abstract class 2. Inside an interface If declared inside an abstract class, use abstract keyword but if declared inside an interface then no keyword is required. All methods inside an interface are public and abstract by default. Abstract methods are made for overriding purpose only. Final methods A method that can be used in child class but can never be overridden is called as final method. Use final keyword with such methods Method Overloading Vs Method Overriding Multiple methods having same name but different signatures in same or child class is called as method overloading. When a method of parent class, re-written in child class is called as overriding. It can never be in same class. While overloading we can increase or decrease the scope of overridden method but while overriding we can increase the scope of overridden method but can never decrease it.

Example Create a class as Common to manage common data of Customer, Vender and Employee like name, email,mobile etc. abstract class Common { private String name,email,mobile; public Common() { } public Common(String name, String email, String mobile) { this.name=name; this.mobile=mobile; this.email=email; } public void setName(String name)

{ this.name=name; } public String getName() { return name; } public void setEmali(String email) { this.email=email; } public String getEmail() { return email; } public void setMobile(String mobile) { this.mobile=mobile; } public String getMobile() { return mobile; } } class Customer extends Common { private int cid; public Customer() { } public Customer(int cid,String name, String email,String mobile) { super(name,email,mobile); this.cid=cid; } public void setCid(int cid) { this.cid=cid; } public int getCid() { return cid; } } class Vendor extends Common { }

class Employee extends Common { } public class Inheritance { public static void main(String[] args) { Customer c=new Customer(); c.setCid(456); c.setName("Rakesh"); c.setEmali("[email protected]"); c.setMobile("9898889889"); System.out.printf("Name is %s, Email is %s and CID is %d",c.getName(),c.getEmail(),c.getCid()); } }

Interfaces A user defined data type very similar to class but contains all abstract methods and final fields. All methods are public and abstract by default and all fields are public and final by default. It allows implementing multiple inheritance in Java. Use interface keyword to declare an interface When inheriting an into a class use implements keyword When inheriting an interface into another interface use extends keyword Example public interface Finance { void budget(); } public interface Hr { void salaryInfo(); } public class ERP implements Hr,Finance { public void budget() { System.out.println("Budget is 4Cr"); } public void salaryInfo() { System.out.println("Salary will be given on 7th"); } } class ITC { public static void main(String args[]) { Hr x=new ERP(); x.salaryInfo(); Finance f=new ERP(); f.budget(); } } 06.03.2011

What are the finals? If used with fields, makes the constant If used with the method, do not allows the method to overriding If used with class, do not allow to inherit a class static blocks static constructor Finalizer Garbage collection Can we run some before the entry point? Yes, using static blocks. Can we run a Java program without using entry point? Yes, using static block. Can be initialize static fields? Yes, using static blocks What is the output of following? class Test { static { System.out.println("Hi"); } public static void main(String args[]) { System.out.println("Hello"); } static { System.out.println("Kese Ho"); } } Output Hi Kese Ho Hello Static Blocks

A block of code which always executes before the entry point static { //statements } Example class Test1 { static { System.out.println("Hi"); System.exit(0); } }

class Test1 { static int num; static { num=6; System.out.println(num); System.exit(0); } } What is Finalizer? A method from Object class which automatically get called when object is garbage collected by the Garbage Collector. protected void finalize() We need to override this method in our class to provide some cleanup work.

Can be forcibly call the Garbage Collector? Yes, using System.gc() method Creating .jar file using NetBeans

Create a new project as Java Class Library Add your packages Add classes within the packages Build the project It creates a .jar file under dist folder Using a .jar file in NetBeans Create a new project and add your .jar file into libraries Revision 1. import 2. import static 3. this 4. super 5. extends 6. implements 7. abstract 8. final 9. static 10. interface 11. class 12. for-each loop 13. finalize() Arrays Array is again a variable that can hold multiple values of similar data type. Use new keyword to create an array. Each array is treated like object and provides length property. int num[]=new int[5]; int num[][]=new int[3][4]; Object x[]=new Object[5]; We can use a variable to define size of array.

Example //Array Test class ArrayTest1 { public static void main(String args[]) {

int num[]=new int[5]; num[0]=56; num[1]=577; num[2]=333; num[3]=222; num[4]=555; for(int i=0;i
View more...

Comments

Copyright ©2017 KUPDF Inc.