CORE JAVA SunMicrosystem divided the Java into three groups: 1) J2SE(Java2 Standalone Edition): Deals with developing a standalone application.(Core Java, Adv.Java). 2) J2EE(Java2 Enterprise Edition): Deals with developing business application for Internet. 3) J2ME(Java2 Micro Edition): Deals with developing embedded system and wireless application. Java Program Execution: Features Of Java: 1) Simple: Java is simple programming language. Learning and practicing java is easy because its look like c,c++. Pointers are eliminated in java due to the following reason: i) Pointer creates confusion for a programmer. ii) Pointer may crash a program. If we can’t use pointers properly crash occurs. iii) Using pointers virus and hacking programs are developed. 2) Object Oriented: i) Object: An object is anything that exists in the real world. Object will have properties and it may perform some actions. x.java x.clas s Byte code 1 JVM Result
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CORE JAVA
SunMicrosystem divided the Java into three groups:
1) J2SE(Java2 Standalone Edition): Deals with developing a standalone application.(Core Java, Adv.Java).
2) J2EE(Java2 Enterprise Edition): Deals with developing business application for Internet.
3) J2ME(Java2 Micro Edition): Deals with developing embedded system and wireless application.
Java Program Execution:
Features Of Java:
1) Simple: Java is simple programming language. Learning and practicing java is easy because its look like c,c++.
Pointers are eliminated in java due to the following reason: i) Pointer creates confusion for a programmer. ii) Pointer may crash a program. If we can’t use pointers properly crash occurs. iii) Using pointers virus and hacking programs are developed.
2) Object Oriented: i) Object: An object is anything that exists in the real world. Object will have
properties and it may perform some actions.
Properties: Properties are represented as variables in java.Actions: Actions are represented as methods.An Object contains variables and methods.
ii) Class: A class is a model to create the objects. Class does not exist physically. A class also contains properties and actions.
3) Distributed: Java is distributed programming language.
4) Robust: In Robust we have two features:
i) Exception Handlingii) Memory Management
Memory Mangement: Memory allocation is done by JVM. JVM contains class loader
x.java x.class
Byte code
1
JVM Result javac
subsystem to allot memory. Memory Deallocation is done by JVM Garbage collection. Garbage collection automatically removed unused objects.
5) Portable: Java is system independent. All java program are portable because it will give same result anywhere.
6) High Performance: JVM contains i) JIT compiler and ii) Interpreter
JIT: Just in Time compiler is useful to increase the speed of the execution.
Interpreter: Interpreter shows the line number.
Demo Program:
Demo.java
import java.lang.*;class Demo {
public static void main(String[] args) {
System.out.println("Hello World!");}
}
import: import is a keyword which is used to import the packages.
java: java is a java library.
lang: lang is the name of the default package.
class: Class is a keyword to define class name.
public: Public data available to all other programmer.
static: static keyword is used to call main method without creating object.
void: void is a return type. Main method doesn’t return any value but it will execute all the Statement.
main: Name of the main method.
String[] args: Here args is the name of the array. The type of the array is String.
System: System is a class.
out: Out is a static field. Static field can’t changed.
2
println: Name of the method.
JVM Architecture:
JVM is divided into five sections:
1) Method Area: It contains the class code and method code.
2) Heap: Objects are created on Heap memory.
3) Java Stack: Java Stack are the places where java methods are executed.
4) PC Register: These registers store memory address of next instruction to be executed by the microprocessor.
5) Native Method Stack: These are the places where native methods are store.
Comments: Comments represents the description of aim and features of a program. The main advantage of comments are Readability. Readability means understandable by everyone. There are three types of comments in java.
i) Single line comment: This comment starts with //.ii) Multiline comment: This comment starts with /* and ends with */.iii) Documentation comment: This comment starts with /** and ends with */.
Q: What is an API document?A: (Application Programming Interface). It is a document containing description of all the features of software or product or technology. We can create our own API document by using javadoc command.
Q: What is the difference between #include and import?A: #include makes the compiler to copy the entire header file code into a c or c++ program. Thus it increases the size of the program and waste memory and processor time.
Import makes JVM to goto the java library, execute the code there, comes back and substitute the result into a java program.
Q: What is JRE(Java Runtime Environment)?A: JRE=JVM + JavaLibrary
Q: What is command line argument?A: The values pass to main method is called command line argument. The values store in String type array.
3
Naming Rule:
1) Package names in java are written in all small letters. Ex: java.lang.*,java.io.* etc2) Each word of class name and interface name start with a capital letter. Ex: Thread, String 3) Method name start with a small letter than each word start with a capital letter. Ex: read(), readLine() etc4) Variable names also follow the above method rule. Ex: String empName, int empNum etc.5) Constant should be written using all capital letters. Ex: int final PI=22/7, MAX=10 etc.6) All keywords should be written in all small letters. Ex: import, public, static etc.
Data Type: A datatype represents the type of data stored in memory.
Primitive Data Type or Fundamental Data Type:
I) Integer Data Type
Data Type Memory Sizei) byte 1byteii) short 2 bytesiii) int 4 bytesiv) long 8 bytes
II) Float Datatype
i) float 4 bytesii) double 8 bytes
III) Character Datatypei) char 2 bytes
IV) Boolean datatypei) boolean 1bit(true or false)
Q: What is the difference between float and double?A: float can represent upto 7 digit after decimal point accurately. Double can represent upto 15 digit accurately after decimal point.
Operator: An operator is a symbol that perform some operations.
Ex: A + B (Here + is an operator and A,B is called operand)
Operand is a variable in which the operator acts. An operator can act upon single operand than it is called “unary” operator. An operator can act upon 2 operand than it is called “binary” operator. If an operator act upon 3 operand than it is called “ternary” operator.
Note: If equal precedence than precedence will count from left to right.
Example:
class OpeTest {
public static void main(String[] args) {
int a=10*4+20/2-5;int b=10*(4+20)/2-5;int c=(10+20)/5+5;int d=(10+20)/(5+5);System.out.println(a+" "+b+" "+c+" "+d);System.out.println("Value of a is-->"+a);System.out.println("Value of b is-->"+b);System.out.println("Value of c is-->"+c);System.out.println("Value of d is-->"+d);
}}
Ternary operator:
class Ternary{public static void main(String args[]) {int i = 20;int j = 55;
7
int z = 0;//z = i < j ? i : j; // ternary operator(output is 20)z = i > j ? i : j; // ternary operator(output is 55)System.out.println("The value assigned is " + z);}}
Reverse:
class Reverse {
public static void main(String[] args){
int r=0,rev=0;int n=63674;while(n>0){
r=n%10;rev=(rev*10)+r;n=n/10;
}System.out.println("The Reverse Number is-->"+rev);
}}
Control Statement: Executing the statement one by one is called Sequential Execution. Executing the statement randomly is called Random Execution. Random Execution is useful to write better program. Random Execution is possible by using control statement. Control statements are the statements which change the flow of execution of a program.
1) if-else statement: This statement is useful to perform a task depending upon whether a condition is true or false.
Example 1:
class IfTest { public static void main(String[] args)
{int num=-4;if(num==0){System.out.println("It is zero");}else if(num>0){
}System.out.println("April is in the " + season );
}}
9
2) do-while loop: This loop is used to repeat early execute a group of statements as long as given condition is true.
Example:
class DoWhileTest {
public static void main(String[] args) {
int x=0;do{System.out.println(x);x++;}while(x>=10);
}}
3) while loop: This loop is repeatedly execute a group of statements as long as given condition is true.
Example:
class WhileTest {
public static void main(String[] args) {int i=2;while(true)//while(i<=10)
{System.out.println(i);i+=2; //i=i+2}
}}
4) for loop: This loop is repeatedly execute a group of statements as long as given condition is true. For loop is more suitable for executing the statement a fixed number of times.
Example:
class ForTest {public static void main(String[] args) {
int i=1;
10
for(;;)//infinite loop//for( i=1;i<=20;i++)
{System.out.println(i);}//System.out.println(i);
}}
5) switch statement: Switch statement is useful to execute a particular task from among several task depending upon the value of a variable.
System.out.println("Enter a value");//char ch=(char)br.read();String ch=br.readLine();//int ch1=Integer.parseInt(ch);float ch1=Float.parseFloat(ch);double ch1=Double.parseDouble(ch);System.out.println("You have entered-->"+ch1);
Array: An array represents a group of elements of same data type. By representing a group of elements with a single array we can make programming easy.
Types of Array:
i) One dimensional array 1Dii) Two dimensional array 2Diii) Multi dimensional array 3D
1) One dimensional array 1D: One dimensional array represents a single row of data or a single column of data.
Creating One dimensional array:
i) We can declare and initialize a one dimensional array using assignment operator. Ex: int marks[]={10,20,30,40,50};
ii) We can create an empty array using new operator and later on we can store the elements into the array.Ex: int marks[]=new int[5]; marks[0]=10; marks[1]=20; marks[2]=30; marks[3]=40; marks[4]=50;
String: A String represents a group of character. In java String is a class. Any String is a object of String class in java.
Creating a String:
i) We can create a String by declaring and initializing a String class object.Ex: String st = “Hello”;
ii) Using new operator we can create a String class object and store data into it.
Ex: String st = new String(“Hello”);
iii) We can create a String class object from a character array.Ex: char a[]={‘h’,’e’,’l’,’l’,’o’}; String st = new String(a);
hashCode: hashCode is a unique identification number allotted to every object by the JVM. hashCode number used to refer to object position in memory.
Types of Objects:i) Mutable Object: Mutable Objects are the Objects whose contents(data) can be modified. Ex: StringBuffer
18
ii) Immutable Object: Immutable Objects are the Objects whose data can not be modified. Ex: String
Example 1:
class Str1 {
public static void main(String[] args) {
String s1="This is java";System.out.println("hashcode for s1=-->"+s1.hashCode());String s2=new String("I like");System.out.println("hashcode for s2=-->"+s2.hashCode());char arr[]={'a','p','t','e','c','h'};String s3=new String(arr);System.out.println("s1="+s1);System.out.println("s2="+s2);System.out.println("s3="+s3);System.out.println("The no. of character in s1 including spaces="+s1.length());System.out.println("s1 join with s2 with s3="+s1.concat(s2)+" "+s2.concat(s3));
// System.out.println(s1+" "+s2+" "+s3);boolean x=s1.startsWith("This");if(x)System.out.println("s1 starts with This");elseSystem.out.println("s1 does not starts with This");String r=s1.toUpperCase();String s=s2.toUpperCase();String r1=s1.toLowerCase();System.out.println("After converting s1="+r);System.out.println("After converting s2="+s);System.out.println("After converting s1="+r1);
}}
Example 2:
class Str2 {
public static void main(String[] args) {
String s1="Hello";System.out.println("hashcode for s1=-->"+s1.hashCode());String s2="Hello1";System.out.println("hashcode for s2=-->"+s2.hashCode());//if(s1==s2)
19
if(s1.equals(s2))System.out.println("Both are equals");elseSystem.out.println("Both are not equals");
}}
Example 3:
class Str3 {
public static void main(String[] args) {
String s1="Hello";System.out.println(s1);
String s2="Hai";s1=s1+s2;System.out.println(s1);
}}/*Garbage Collector remove the previous value and storing the new value*/
Example 4:
String Methods:
//1) codePointAt():-- The codePointAt() method returns the character(Unicode code point) at the specified index.
//2) codePointBefore():-- The codePointBefore() method returns the character(Unicode code point) before the specified index.
//3) codePointCount():-- The codePointCount() method returns the number of Unicode code points between two indices in the String.
//4) startsWith():-- The startsWith() method returns a boolean value to test whether the string starts with a specified prefix.
//5) endsWith():-- The endsWith() method returns a boolean value to test whether the string ends with a specified sufix.
//6) toUpperCase():--The toUpperCase() method converts the characters in the string to upper case.
//7) toLowerCase():--The toLowerCase() method converts the characters in the string to lower case.
//8) valueOf():--The valueOf() method returns the string representation of the specified argument.The argument can have any one of the values:boolean, char, float, double, int, long etc.
20
//9) toCharArray():-- The toCharArray() method copies the content of the String to a new character array.
//10) equalsIgnoreCase():-- The equalsIgnoreCase() method compares two strings, ignoring case and returns a boolean value. If the strings are equal the method returns a true value, otherwise false.
class StringMethod{
public static void main(String[] args) {
String str="Aptech Global Learning Solutions";String str1="APTECH GLOBAL LEARNING SOLUTIONS";char[] array={'A','p','t','e','c','h',' ','G','l','o','b','a','l'};System.out.println(str.codePointAt(0));//65System.out.println(str.codePointBefore(1));//65System.out.println(str.codePointCount(0,5));//5System.out.println(str.startsWith("Apt"));//trueSystem.out.println(str.endsWith("tions"));//trueSystem.out.println(str.toUpperCase());//APTECH GLOBAL LEARNING SOLUTIONSSystem.out.println(str.toLowerCase());//aptech global learning solutionsSystem.out.println(String.valueOf(array));//Aptech GlobalSystem.out.println(String.valueOf(array,7,6));// Globalchar[] array1;array1=str.toCharArray();System.out.println(String.valueOf(array1));//Aptech Global Learning SolutionsSystem.out.println(str.equalsIgnoreCase(str1)); //true
}}
Example 5:
StringBuffer Methods:
//1) charAt():-- The charAt() method returns the character value at the specified index.
//2) deleteCharAt():-- The deleteCharAt() method deletes the character value at the specified position.
/*3) getChars():-- The getChars() method copies specified number of character into an array.syntax:void getChars(int begin,int end, char[] destArray,int destArrayBegin)*/
21
//4) length():-- The length() method returns the total number of characters from the StringBuffer object.
//5) replace():-- The replace() method replaces characters from the StringBuffer object with new characters.
//6) setCharAt():-- The setCharAt() method replaces a character from the StringBuffer object with a new character at the specified index.
//7) setLength():-- The setLength() method sets the length of the StringBuffer to a new value.
//8) capacity():-- The capacity() method returns the current capacity of the StringBuffer object. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
//9) substring():-- The substring() method creates a new string from the stringBuffer object.
class StringBufferMethod {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("Aptech Global Learning Solutions");StringBuffer sb1=new StringBuffer("Aptech Global Learning Solutions");System.out.println(sb.charAt(7));//GSystem.out.println(sb.deleteCharAt(5));//Aptec Global Learning Solutionschar[] array=new char[10];sb1.getChars(0,6,array,0);System.out.println(array);//AptechSystem.out.println(sb1.length());//32System.out.println(sb1.replace(23,32,"Services"));//Aptech global Learning Servicessb1.setCharAt(7,'g');System.out.println(sb1);//Aptech global Learning Services//sb1.setLength(35);System.out.println(sb1);//Aptech global Learning Servicessb1.setLength(13);System.out.println(sb1);//Aptech global StringBuffer sb2=new StringBuffer();System.out.println(sb2.capacity());//16System.out.println(sb1.capacity());//48
The languages like c, pascal, fortron these are called procedural languages because they follow an approach called procedural approach.
The languages like c++ and java called object oriented because they follow an approach called object oriented programming approach.
Features of OOPS:
1) Object and class
Object: An object is anything that exists in the real world. An object contains properties and Actions. Properties are represented as variables. Actions are represented as methods. So an object contains variables and methods. Class does not exist physically but Object does exist physically.
Class: A class is a model or idea to create the objects. From the class we create objects. A class also contains variables and methods. An object does not exist without a class but a class exist without any objects.
2) Encapsulation: Writing variables and methods as a single unit is called encapsulation. Class is an example of encapsulation. The advantage of encapsulation is the programmer can use same name for the member of two different classes.
3) Abstraction: Hiding unnecessary data from the user is called abstraction.
4) Inheritance: Producing a new class from an existing class is called inheritance. The newly produced class automatically built inherit all the features of the existing class. Reusability of code is the main advantage of inheritance
5) Polymorphism: If something exist in various forms it is called polymorphism. If a single method perform various task it is called polymorphism.
6) Message passing: Calling a method is called message passing.
Access Specifier: An access specifier is a keyboard that specifies how to access the members of class or the class itself. There are four access specifier in java:
1) Private: Private member of a class are not accessible in another class either in the same package or in another package. The scope of private specifier is class scope.
23
2) Public: Public members of a class are available in another class of same package or of an another package. The scope of public spcifier is global scope.
3) Protected: Protected members are available in another class in the same package but they are not available in another package class. Note: Protected members are always available to subclasses(inheritance) in the same package or another package.
4) 4) Default: Default members are available in another class in the same package but they are not available in another package class. The scope of default specifier is package scope.
Problem with Private specifier:
Problem 1:
class Person {
private String name;private int age;//String name;//int age;void talk(){
System.out.println("Hello I am -->"+name);System.out.println("Hello My Age -->"+age);
}}class FirstType{
public static void main(String[] args) {
Person p1=new Person();p1.talk();
Person p2=new Person();p2.name="san";p2.age=25;p2.talk();}
}/*note: Defect in this program is if we declare the variables as private we can't use that variable in other class*/
24
Problem 2:
class Person {
private String name="san";private int age=25;//String name="xyz";//int age=20;void talk(){
System.out.println("Helllo I am -->"+name);System.out.println("Helllo My Age -->"+age);
}}class SecondType{
public static void main(String[] args) {
Person p1=new Person();p1.talk();Person p2=new Person();p2.name="abc";p2.age=29;p2.talk();
}}//Note:defect in this program is private variable can't be initialize second time.
Problem 3:
class Person {
private String name;private int age;//String name;//int age;Person()//default constructor{
System.out.println("Helllo I am -->"+name);System.out.println("Helllo My Age -->"+age);
25
}}class ThirdType{
public static void main(String[] args) {
Person p1=new Person();Person p2=new Person();p1.talk();p2.talk();
}}//Note: defect in this program is default constructor can initialize only one set of value.
Constructor: A constructor is similar to a method which initializes the instance variables of a class. A constructor name and class name should be same. A constructor may have parameters and may not have parameters. A constructor without any parameter is called default constructor. A constructor with one or more parameters is called parameterized constructor. A constructor does not return any value not even void. A constructor is called only once at the time of creating an object.
Q: What is the difference between default constructor and parameterized constructor?A: default constructor is used to initialize every object with same data. Parameterized constructor is used to initialize every object with different data.
Constructor Overloading: Writing two or more constructor with the same name but with a difference in the parameter is called constructor overloading.
Example:
//Parameterized Constructorclass Constru{
private String a;private int b;private int c;Constru()//default constructor{
a="xyz";b=30;//c=45;
}Constru(String a,int b){
this.a=a;this.b=b;
}
26
Constru(String a,int b,int c){
this.a=a;this.b=b;this.c=c;
}void display(){
System.out.println("Hello name is-->"+a);System.out.println("Hello age is-->"+b);System.out.println("Hello age is-->"+c);
}//Note: In this program we are able to get different set of values by using parameterized constructor, even the variable are declared as private.
Method: A method is a group of sttements similar to class. (or) A method represents a group of statements to execute a task. A method will have two parts:
i) Method Header or Method Prototype: This part contains method name, method parameters and method return type.
ii) Method Body: A method body represents a group of statements containing logic written inside { }
If a method returns some values we should use return statements inside to the method body. We can return only one entity.
1) Static Method: Static methods are the methods which does not act upon the instance variables of a class. Static methods are declared as static by using a static keyword. Static methods are called using classname.methodname. Here no need to create an object. Static methods can act upon static variable. Static variable should be declared as static. Ex: static double d1,d2,d3;
Example:
//Static method exampleclass Sta{
//static int a=10;static int a1=10;
static void display(){
System.out.println(a1);}
}class Static
{public static void main(String[] args)
{Sta.display();
}}
2) Instance Method: These are the methods which act upon instance variables of a class. Instance methods are called using objectname.methodname.
a) Accessor Method: These methods access or read the instance variables.
b) Mutator Method: These methods not only read the instance variable but also modifies the contents of the object.
Person p=new Person("xxx",36,'M');p.display();Person p1=p.modify(p);//Here we are not creating an object to p1. Here p1 is a reference variable.p1.display();p.display();Person p2=new Person("sai",22,'M');p2.display();}
}
3) Factory Method: A Factory method is a method that returns an object of the class to which it belongs. All the Factory methods are static method. When we
30
use Factory Method we can not use new operator.
Example:
//Example for Factory Methodimport java.text.*;class FactMe {
public static void main(String[] args) {
final double PI=(double)22/7;double r=54.87;double area=PI*r*r;System.out.println("Area="+area);NumberFormat obj=NumberFormat.getNumberInstance();obj.setMaximumFractionDigits(2);String str=obj.format(area);System.out.println("Formatted Area="+str);obj.setMinimumFractionDigits(6);String str1=obj.format(area);System.out.println("Formatted Area="+str1);
}}
Inner Class: A class within another class is called inner class. We can not write private before main class. Private can be used only before inner class. Inner class not available to the other programmer. We can create an object to inner class only in its outer class.
Example:
//Inner class exampleclass BankAcct//Outer class {
Inheritance: Producing a new class from an existing class is called inheritance. The existing class is called super class and the newly produced class is called sub class. Subclass object contains copy of the super class. The main advantage of inheritance is the reusability of the code. We can create an object to the subclass only in inheritance.
Note: a) From above program all the Teacher class members are available to student class. b) To access or read all the members of Teacher class(Super class) to Student class(Sub class) we use extends keyword.
Example 2:
class OneDemo {
OneDemo(){System.out.println("OneDemo in super class!");}
}class TwoDemo extends OneDemo{
TwoDemo(){System.out.println("TwoDemo in sub class");}
}class TDemo extends TwoDemo{
TDemo(){System.out.println("TDemo in sub class");}
}class InheritDemo{
public static void main(String[] args) {
TDemo t=new TDemo();}
}
Note: a) From above program first super class constructor is executed and than the sub class constructor is executed. b) Super class parameterized constructor is not available to sub class. c) Super is a keyword that refers to super class from a sub class. It means super can refer super class instance variable, super class constructor and also super class methods.
34
Example 3:
//Example for super
class One{
int x;One(int x){
this.x=x;}void show(){
System.out.println("super class method");}
}class Two extends One{
int x;Two(int a,int b){
super(a);x=b;
}void show(){
super.show();System.out.println(super.x);System.out.println("Sub class method="+x);
}}
class SuperDemo{
public static void main(String[] args) {
Two t=new Two(100,299);t.show();
}}
Polymorphism: The word came from two Greek word. i) Poly—Poly means many and ii) Morph—morph means forms. If something exist in several form it is called polymorphism. If the same method performs various task is called polymorphism. Different method bodies are required to perform various task. In polymorphism there are two types:
35
a) Static polymorphismb) Dynamic polymorphism
Dynamic polymorphism: Dynamic means at runtime. The polymorphism executed at runtime is called dynamic polymorphism or runtime polymorphism or dynamic binding or dynamic linking. Here java compiler does not know which method is called by the user at the time of compilation. JVM can bind the method, call with the method body at the time of running the program.
Example:Method Overloading: Writing two or more methods with the same name but with different method Signature.
//Method Overloadingclass Sample {
void add(int a,int b){
System.out.println("sum of two="+(a+b));}void add(int a,int b,int c){
Method Signature: Method Signature represents method name and method parameters. When two or more methods are written with the same method name and there is a difference in the method signature from can identify those method s different method.
The difference in the method signature may be due to the following factor:
a) There may be a difference in the number of parameter.Ex: void add(int a, int b) void add(int a, int b, int c)
36
b) There is a difference in the data type of parametersEx: void add(int a, int b) void add(float a, float b)
c) There is a difference in the sequence of parameters.Ex: int swap(int a, char b) Int swap(char a, int b)
Method Overriding: Writing two or more methods in super and sub classes with the same name and same signature is called method overriding. In method overriding JVM execute a method depending on the data type of reference variable used to call a method.
Two t=new Two();t.calculate(25);t.calculate(9);t.calculate(36);
}}
Static Polymorphism: The Polymorphism executed at compile time is called static polymorphism
37
or static binding.Use of Final keyword:
1) Final keyword is writing before constants.2) Final keyword is used before the class name to prevent inheritance.3) Final methods can not be overridden.
Type Casting or Casting: Converting one data type into another type is called type casting or casting.
Casting primitive data type:
1) Widening: Casting a lower data type into a higher data type is called widening. Ex: char ch = ‘A’ int i = (int) ch;//65
2) Narrowing: Converting a higher data type into lower type is called Narrowing. Ex: int n = 65; Char ch = (char) n;
Abstract class: A method consists of two parts: method header and method body. Method header represents the future the programmer wants in a class. Method body represents how to implements this future. Implementing means writing body for method. When a method has got different implementation in different objects than the programmer cannot write method body in the super class.
A method without method body is called a abstract method. A class that contains abstract method is called abstract class. To declare abstract method class should be declare using keyword abstract. Concrete methods mean complete methods. We cannot create object to abstract class.
Points:
1) An abstract class is a class with zero or more abstract methods.2) An abstract class can have abstract method, concrete method and instance
variables. 3) Both the abstract class and abstract methods should be declared as abstract.4) We cannot create an object to abstract class.5) We can create reference variables of abstract class type.6) All the abstract methods of abstract class should be implemented in its
subclasses.7) If any method is not implemented that subclass should also be declare as
abstract.8) Abstract class reference variable can be used to refer to the objects.9) Abstract class reference cannot refer to individual method of a class.10) A class cannot have both abstract and final.
System.out.println("Regno of Maruti="+regno);System.out.println("Maruti uses manual steering="+direction);System.out.println("please drive the maruti car");
}void breaking(int force){
System.out.println("Breaking of Maruti="+force);System.out.println("Maruti uses hydralic breaks");System.out.println("Apply breaks stop the car");
}}class Santro extends Car{
Santro(int regno){
super(regno);}void steering(int direction){
System.out.println("Regno of Santro="+regno);System.out.println("Santro uses manual steering="+direction);System.out.println("please drive the Santro car");
39
}void breaking(int force){
System.out.println("Breaking of Santro="+force);System.out.println("Santro uses hydralic breaks");System.out.println("Apply breaks stop the car");
Interface: An interface is a specification of method prototype. All the methods of interface are by default abstract only. We cannot create an object to interface.
Points:
1) Interface is a specification of method prototype or method header.2) An interface contains zero or more abstract methods.3) All the methods of the interface are public and abstract by default.4) An interface can also contain variables which are public, static and final by
default.5) When an interface is written any third party vendor can implement it.6) All the abstract method of the interface should be implemented in a class called
implementation class.7) If any method is not implemented than that class should be declare as abstract.8) We cannot create an object to an interface.9) We can create a reference of an interface.10) Interface reference can be used to refer to the objects of its implementation
classes.11) We can write a class within an interface.12) An interface cannot implement another interface.
40
13) An interface can extends another interface. 14) A single class can implement multiple interfaces.
Example1:
import java.io.*;interface MyInter{
void connect();}
class OracleDb implements MyInter{
public void connect(){
System.out.println("Connecting to oracle");}
}class SybaseDb implements MyInter{
public void connect(){
System.out.println("Connecting to sybase");}
}class Inter {
public static void main(String[] args) throws Exception{
Packages: A packages represents a sub directory that contains a group of related classes and interfaces. Packages hide classes and interfaces in separate subdirectories. Accidental deletion is not possible. The classes of one package are different from the classes of another package. Packages provide the reusability of code. We can create our own package as well as extend already available packages.
Example 1
Addition.java
package ddd;public class Addition{double d1,d2;public Addition(double d1,double d2){
package cdf;import java.util.Date;public class MyDateImpl implements MyDate{
public void showDate(){
Date d=new Date();System.out.println(d);
}}
Useinterface.java
import cdf.MyDateImpl;class Useinterface{
public static void main(String[] args) {
MyDateImpl m=new MyDateImpl();m.showDate();
}}
SubPackage Example
Sample.java
package demo.aptech;
45
public class Sample{
public void show(){
System.out.println("sub packages");}
}
UseSample.java
import demo.aptech.Sample;class UseSample{
public static void main(String[] args) {
Sample s=new Sample();s.show();
}}
Exception Handling:
Bug: A bug is an error in software. Debugging means removing the errors
Types of Error:
1) Compile time error: These are the errors in the syntax or grammar of the language. These errors are detected by the compiler at the time of compilation. Desk checking(line by line) is the solution for compile time errors.
2) Runtime error: These errors will arise due to inefficiency (enough memory not available) or unable to execute the statement by processor. Ex: something divides by zero. Runtime errors are detected by JVM.
3) Logical error: These are the errors in the logic of the program. These errors are not detected by the compiler or JVM. The programmer is completely responsible for logical errors.
Exception: An Exception represents runtime errors.
Checked Exception: The Exception which are detected by java compiler at the time of compilation are called Checked Exception.
Unchecked Exception: The exception which are not detected by java compiler and they are detected by JVM at runtime are called Unchecked Exception:
Note: An Exception is an error that can be handled but an error cannot be handled.
46
Example:
//without handling
class Exce11 {
public static void main(String[] args) {
System.out.println("open the files");int n=args.length;System.out.println("Number of args are-->"+n);int a=45/n;System.out.println(a);int a1[]={10,20};a1[3]=40;System.out.println("The value of a is"+a1);System.out.println("close the file");}
}
When there is an exception JVM come out of the program and we loss the remaining statement also. When there is an exception the programmer should do the following task:
1) We should write all the statements where there may be an exception inside try block. When there is an exception inside try block JVM doesn’t abnormally terminate the program. It will jump into catch block.
2) When there is an exception JVM stores exception details in the Exception Stack. In catch block the programmer should display exception details and also any messages to the user.
3) The programmer should close all the files and databases and perform cleanup operation by writing them in finally block. The statements inside finally blocks are always executed wether there is an exception or not.
Example:
//handling the exceptionclass Exce1 {
public static void main(String[] args) {
System.out.println("open the files");try{
int n=args.length;System.out.println("Number of args are"+n);
47
int a=45/n;}catch(Exception ae){
System.out.println(ae);}finally{
System.out.println("close the file");}
}}
1) Exception Handling means there will not be a damage or no loss of data. 2) By using multiple catch blocks we can handle multiple exceptions.3) A try block can be followed by several catch blocks.4) A catch block does not exist without a try block.5) A try block exists without catch block.6) One exception we can handle at a time even though there is multiple exceptions.
Throws clause: Throws clause is useful to throughout an exception from a method without handling it.
Throw clause: Throw clause is useful to create an exception class object and throws it out of a try block.
Example:
class NestedTry {
public static void main(String[] args) {
int a=args.length;int c[]={1};try{
int b=90/a;
System.out.println("b is : "+b);try{
if (a==1)a=a/(a-a);System.out.println("a is : "+a);if (a==2)c[3]=9;
}
48
catch(ArrayIndexOutOfBoundsException e){
System.out.println("array is out of bounds : "+e);}}catch(ArithmeticException e){
if(no<500) throw new MyException(no); System.out.println("Normal Exit"); } public static void main(String ar[]) { try
{
52
check(1000);check(350);
} catch(MyException me) {
System.out.println(me); }
}}
Exception List:
Exception Meaning:
1) ArithmeticException Arithmetic error, such as divide-by-zero.
2) ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3) ArrayStoreException Assignment to an array element of an incompatible type.
4) ClassCastException invalid cast.
5) IllegalArgumentException Illegal argument used to invoke a method.
6) IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
7) IllegalStateException environment or application is in incorrect state.
8) IllegalThreadStateException Requested operation not compatible with current thread state.
9) IndexOutOfBoundsException Some type of index is out-of-bounds.
10) NegativeArraySizeException array created with a negative size.
11) ClassNotFoundException class not found.
12) CloneNotSupportedException Attempt to clone an object that does notimplement the Cloneable interface.
13) IllegalAccessException Access to a class is denied.
14) InstantiationException Attempt to create an object of an abstract class or interface.
15) InterruptedException One thread has been interrupted by another thread.
53
16) NoSuchFieldException A requested field does not exist.
17) NoSuchMethodException A requested method does not exist.
18) NullPointerException invalid use of a null reference.
19) NumberFormatException invalid conversion of a string to a numeric format.
20) SecurityException Attempt to violate security.
21) StringIndexOutOfBoundsException Attempt to index outside the bounds of a string.
22) UnsupportedOperationException An unsupported operation was encountered.
Wrapper Class: A wrapper class is a class whose object contains a primitive data type.
Character class: A Character class contains a value of primitive type char in an object. An object of type Character contains a single field whose type is char.
Example:
//Character Testimport java.io.*;class CharTest{
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Please Enter a character");char ch=(char)br.read();if(Character.isDigit(ch))System.out.println("It is a Digit");else if(Character.isUpperCase(ch))System.out.println("It is capital");else if(Character.isLowerCase(ch))System.out.println("It is small");else if(Character.isSpaceChar(ch))System.out.println("It is coming from spacebar");else if(Character.isWhitespace(ch))System.out.println("It is coming from enter,tab");elseSystem.out.println("Sorry I donot know that character");
}}
54
Byte class: A Byte class contains a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.
Example:
import java.io.*;class ByteTest{
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter first byte no.");String s1=br.readLine();Byte b1=new Byte(s1);System.out.println("Enter second byte no.");String s2=br.readLine();Byte b2=new Byte(s2);int n=b1.compareTo(b2);System.out.println("CompareTo() methods return the difference between two
no="+n);if(n==0)System.out.println("Both are equal");else if(n>0)System.out.println("b1 is bigger="+b1);elseSystem.out.println("b1 is smaller="+b1);
}}
Integer class: A Integer class contains a value of primitive type int in an object. An object of type Integer contains a single field whose type is int.
Example:
import java.io.*;class IntTest {
public static void main(String[] args) throws IOException{
Stream: A stream represents flow of data from one place to another place. There are two types of stream:
1) InputStream: InputStream read or accept data that is coming from some other place.
2) OutputStream: OutputStream send or write data to some other place.
Byte Stream: Byte Stream handles the data in the form of bits and bytes. To handle the data in the form of bytes the abstract class InputStream or OutputStream are used.
InputStream Division:
1) FileInputStream2) FilterInputStream
a) BufferedInputStreamb) DataInputStream
3) Object InputStream
OutputStream Division:
1) FileOutputStream2) FilterOutputStream
a) BufferedOutputStreamb) DataOutputStream
3) Object OutputStream
CharacterStream or TextStream: They will handle the data in the form of chracters
//Using Writer create and pass the data into the fileimport java.io.*;class Create2{
public static void main(String[] args) throws IOException{
String str="This is an Institute I am a student";FileWriter fw=new FileWriter("textfile.txt",true);BufferedWriter bw=new BufferedWriter(fw);for(int i=0;i<str.length();i++)bw.write(str.charAt(i));bw.close();
}}
Example 4:
//Reading file using FileReaderimport java.io.*;class Read2{
public static void main(String[] args) throws IOException{
Threads: A thread represents a process or execution of statements.
Microprocessor uses internally a thread to execute the program.
Execution process or worked is called thread.
Example:
class Thr1 {
public static void main(String[] args) {
System.out.println("This is first statement");
62
Thread t=Thread.currentThread();t.setName("Mythread");System.out.println(t.isAlive());System.out.println("Thread name is");System.out.println("current thread="+t);}
}
Note: Every java program contains internally a thread called main. Default priority of main thread is 5 Thread group name is main
Executing statements is of 2 types:
1) Single Tasking: Executing only one task at a time is called single tasking
2) Multitasking: In multitasking several program executing at a time. We have two types in Multitasking
a) Process based multitasking: Executing several programs simultaneously is called process based multitasking.
b) Thread based multitasking: Executing different parts of the same program with the help of threads is called Thread based multitasking.
Example 1:
//creating and running a thread using extends Threadimport java.io.*;class Tdemo extends Thread {
Thread Synchronization or Thread safe: when a thread is acting on an object, preventing other threads from acting on the same objects is called thread Synchronization or Thread safe.
Example:
//Synchonization(two threads acting on single object)class Reserve implements Runnable{
int available=3;int wanted;Reserve(int i){
wanted=i;}public void run(){
synchronized(this){
System.out.println("The number of berths available="+available);if(available>=wanted){
System.out.println("Priority of pd1 is "+pd1.getPriority());System.out.println("Priority of pd2 is "+pd2.getPriority());
}}
Applet: An Applet is a program that comes from internet server into a client and gets executed at client side and displays the result. An applet represents byte code embedded in a HTML page.
Applet = byte code + HTML
Applet Life cycle methods:
1) public void init(): This method is used for initializing the variables, parameters and to create Components (button,images). This method is executed only once at the time of applet loaded into memory.
2) public void start(): This method will execute when applet gains the focus.
3) public void stop():This method will execute when applet loss the focus.
4) public void destroy(): This method is executed only once when the applet is terminated from Memory.
Example 1:
import java.awt.*;import java.applet.*;/*<applet code="MyApplet1" width=600 height=400></applet>*/public class MyApplet1 extends Applet{
//passing value from HTML to appletimport java.awt.*;import java.applet.Applet;public class MyApplet3 extends Applet{
Font f=new Font("Ariel",Font.BOLD,24);String msg;public void paint(Graphics g){g.setFont(f);g.setColor(Color.blue);g.drawString(msg,10,50);}public void init(){
msg=getParameter("para");if(msg==null)msg="Null value returned";
}}
<html><head><title>My page</title></head><body bgcolor=blue><h2>This page shows use of Applet</h2><p><applet code="MyApplet3.class" width=400 height=100><param name=para value="Passing value from HTML"></applet></body>
70
</html>
Example 4:
//Draw graphicsimport java.awt.Graphics;import java.awt.Font;import java.awt.Color;import java.applet.Applet;public class MyApplet4 extends Applet{
public void paint(Graphics g){Font f=new Font("Courier",Font.BOLD,16);Color c=new Color(200,235,255);g.drawLine(10,1,10,60);g.drawLine(10,1,60,10);g.drawRect(10,10,50,50);g.setFont(f);g.setColor(c);g.drawString("Have a nice Day!",110,50);
}}
<html><head><title>My page</title></head><body bgcolor=red><h2>This page shows use of Graphics</h2><p><applet code="MyApplet4.class" width=400 height=100></applet></body></html>