Java New Notes for MSc IT

Share Embed Donate


Short Description

Download Java New Notes for MSc IT...

Description

String and StringBuffer String » » » » »

String is a class in "java.lang" built-in package. String is declared as final class String implements marker interfaces "Serializable", "Comparable", "CharSequence". The compiler makes sure that each String constant actually results in a String object. String object can be created in two ways

1. Using 'new' Operator Syntax: String s=new String("javasree"); 2. without using 'new' operator Syntax: String s="javasree";

Constructor List String() :

Constructs a new empty String.

String(String) :

Constructs a new String that is a copy of the specified String.

String(char[]) :

Constructs a new String whose initial value is the specified array of characters.

String(char[], int, int) :

Constructs a new String whose initial value is the specified sub array of characters.

String(byte[], int, int, int) :

Constructs a new String whose initial value is the specified sub array of bytes.

String(byte[], int) :

Constructs a new String whose initial value is the specified array of bytes.

Strings are special, in that they are the only object with an overloaded operator. When you use '+' with at least one String argument, both arguments have String conversion performed on them, and another String (not guaranteed to be unique) results. String is special-cased when doing data serialization - rather than listing the fields of this class, a String object is converted to a string literal in the object stream. String objects are immutable (ie) once string object is created it cannot be changed but we can change string reference variable. Because String objects are immutable they can be shared. Hash code of Strings will be calculated as follows: Ex: String s="abcde" Hash code of 's' is calculated = a*31^4+b*31^3+c*31^2+d*31+e When a string is concatenated, every time a new string object will be created as shown below :

Ex: String st= "javasree"; st=st + ".com"; The last statement in above example a new String object "javasree.com" will be created and assigned to reference variable 'st'. Now st point to "javasree.com" not "javasree" This always consumes lot of memory each time a new object is created. To solve this problem sun has provided concept called "String constant Pooling" or "String object Pooling"

String Constant Pool » String Constant Pool is some memory which contains String constants (or) a Pool of String Constants Ex: case (I) String s1=new String("abc"); String s2=new String("abc"); case (II) String s="abc"; String st="abc"

Uses of String Constant Pooling Mechanism Under case(I) » For the objects created for string with 'new' operator, JVM won't verify pool, directly it create a new string object. » String Constant pool is not eligible for Garbage Collection. Under case(II) » For objects created for string without 'new' operator, first JVM will verify pool to whether the object is available in the pool or not. » If available, that object reference will be assigned to reference variable. » It won't create a new object. » JVM will maintain String Constant Pool, Pool list until the system is turned off.

check

will

Example illustrating difference between "==" & "equals()": class St { public static void main(String as[]) { String s1=new String("abc"); String s2=new String("abc"); if(s1==s2) System.out.println("equal"); else System.out.println("not equal"); if(s1.equals(s2)) System.out.println("equal"); else System.out.println("not equal"); } } Output: not equal equal

String Buffer Introduction : * StringBuffer is a class in "java.lang" build-in package. * StringBuffer is declared as final class * StringBuffer implements marker interfaces "Serializable", "CharSequence". * A String buffer implements a mutable sequence of characters. * String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved. * Every string buffer has a capacity. Every new String Buffer object created default 2 bytes of length will be allocated as capacity of the object. As long as the length of the character sequence contained in the StringBuffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger as follows: New capacity=old capacity * 2

Constructor List public StringBuffer(); public StringBuffer(int length); public StringBuffer(String str);

Example using String Buffers class Sb { public static void main(String as[]) { StringBuffer sd1=new StringBuffer(); StringBuffer sd2=new StringBuffer("sri"); System.out.println(sd1.length()); System.out.println(sd1.capacity()); System.out.println(sd2.capacity()); System.out.println(sd2.length()); } } Output : 0, 16, 19, 3.

Differences between String & StringBuffer : String

StringBuffer

1.String objects are immutable

1.StringBuffer objects are mutable

2.String objects don't have default capacity

2.Every string buffer has a default capacity

3.Implemented interfaces : Serializable, Comparable, 3.Implemnted interfaces : Serializable, Char Sequence. Char Sequence 4. String is special-cased when doing data serialization

4.String buffers are safe for use by multiple threads.

INNER CLASSES A class that is declared and defined inside some other class is called an Inner class. Sometimes it is also called a nested class. In Java it is a feature added since jdk1.1.The inner classes give additional functionality to the program and make it clear. Let us look at the basic construction of the inner class.Like variables and methods, we can write classes also inside a class or interface. We have four types of inner classes.

» Non-static Inner classes » Static Inner classes » Method-Local Inner classes » Anonymous Inner classes

Non Static Inner Classes: class Outer { int x; void m1() { System.out.println(x); Inner i=new Inner(); i.m2(); } class Inner { int y; void m2() { System.out.println(x); System.out.println(y); } } } class InnerClassDemo { public static void main(String arg[]) { Outer out=new Outer(); out.m1(); } }

» Outer class members can be accessed inside the inner class directly. » Inner class members can not be accessed inside the outer class directly but we can access by creating object of inner class. » The scope of non-static inner class is the outer class where it is defined. » Inner classes have access to their enclosing class's scope. ]» The accessibility of the members of the enclosing class is crucial and very useful. » The access to enclosing class's scope is possible because the inner class actually has a hidden reference to the outer class this reference.

Static Inner Classes: » Unlike an outer class an inner class may be private, static or abstract. Marking an Inner class static has some interesting effects with regards to accessing the fields of the enclosing class. » The effect of marking it as static means there is only one instance of any variable no matter

how many instances of the outer class are created. » In this situation how could the static inner class know which variables to access of its non-static outer class? The answer is that it could not know, and thus a static inner class cannot access instance variables of its enclosing class. » The methods of a static inner class can of course access any static fields of its enclosing class, as their will only be one instance of any of those fields. class Outer { static int x; void m1() { System.out.println(x); Inner i=new Inner(); i.m2(); } static class Inner { int y; void m2() { System.out.println(x); System.out.println(y); } } } class InnerClassDemo { public static void main(String arg[]) { Outer out=new Outer(); out.m1(); Outer.Inner outin=out.new Inner(); outin.m2(); } }

Method-Local Inner Classes When you define a class inside a method that is called as method-local inner class. The scope of this class is within the method itself where it is defined. Below is a example of the method-local inner classes.

class InnerDemo { void m1() { System.out.println("Hello"); class Hello {

void m2() { System.out.println("I am in method-local inner class"); } } Hello h=new Hello(); h.m2(); } }

Anonymous Inner Classes » A class without a name defined inside a method is called an Anonymous Class. Anonymous Classes are defined in the place they are constructed. » In certain situations an inner class need to be defined without name. » This type of inner class declarations is called anonymous inner classes. » You will see this type of inner class declaration in GUI event handling mechanisms of Java.

Declaring of Anonymous class: Anonymous inner classes are defined by coke in a block following the use of new operator and an associated constructor. new may be used with the name of a class or the name of an interface. If an anonymous inner class is defined in a block following the application of new on class X then it defines a class that extends class X. If an anonymous inner class is defined in a block following the application of new to interface Y then it defines a class which implements interface Y.

interface Animal { void eat(); void sleep(); } class AIDemo { Animal ani=new Animal(); { void eat() { System.out.println("eating"); } void sleep() { System.out.println("sleeping");

} } }

*Important Tips on Anonymous Following are a few important points that should be kept in mind while writing Anonymous classes: » Anonymous inner class cannot have constructor. » The declaration and instantiation of anonymous inner classes should be done at the same place. » An anonymous class can either explicitly extend a class or explicitly implement an interface, but you cannot do both extending and implementing of an interface.

» An anonymous class cannot have a constructor. Since you do not specify a name for the class, you cannot use that name to specify a constructor.

PACKAGES Packages are java's way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact, packages act as "containers" for classes. By organizing our classes into packages we achieve the following benefits.

1. The classes contained in the packages of other programs can be easily reused. 2.In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have same name. They may be referred by their fully qualified name, comprising the package name and the class name.

3. Packages provide a way to "hide" classes thus preventing other programs or packages from accessing classes that are meant for internal use only.

4.Packages also provide a way for separating "design" from "coding". First we can design classes and decide their relationships, and then we can implement the java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.

5. Package is a collection of classes,which is a folder to store ".class" files.Sun has given some packages which are built in packages.

Java API Packages: Java API provides a large number of classes grouped into different package according to functionality. Most of the time we use the packages available with the java API. The below figure shows the functional breakdown of packages that are frequently used in the programs.

Frequently used API packages

Java System Packages and their Classes: Package.name Contents Java. lang

Language support classes. These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions.

Java.util

Language utility classes such as vectors, hash tables, random numbers, date, etc.

Java.io

Input/Output support classes. They provide facilities for the input and output of data.

Java.net

Classes for networking. They include classes for communicating with local

computers as well as with internet servers. Java.awt

Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on.

Java. applet

Classes for creating and implementing applets.

Creating Packages: »» We must declare the name of the package using the package keyword followed by a package name.

»» this must be the first statement in a java source file. Then we define a classjust as we normally define a class.

»» Example:package firstPackage; public class FirstClass { ------------------}

//package declaration //class definition

Here the package name is firstPackage. Naming Conventions: Packages can be named using the standard java naming rules. By convention, however, packages begin with lowercase letters. This makes it easy for users to distinguish package names from class names when looking at an explicit reference to a class. We know that all class names, again by convention, begin with an uppercase letter. For example, look at the following statement:

Double y= java.lang.Math.sqrt(x); This statement uses a fully qualified class name Math to invoke the method

sqrt(). Note that methods begin with lowercase letters. Accessing a Package: It will be recalled that we have discussed earlier that a java system package can be accessed either using a fully qualified class name or using a shortcut approach through the import statement. We use the import statement when there are many references to a particular package or the package name is too long and unwieldy.

The same approaches can be used to access the user-defined packages as well. The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching a class is a follows:

import firstpackage.secondpackage.MyClass; After defining this statement, all the members of the class My Class can be directly accessed using the class name or its objects (as the case may be) directly without using the package name: We can also use another approach as follows:

import packagename.*;

Here, package name may denote a single package or a hierarchy of packages as mentioned earlier. The star (*) indicates that compiler should search this entire package hierarchy when it encounters a class name. This implies that we can access all classes contained in the above package directly.

Using a Package: Let us now consider some simple programs that will use classes from other packages. The listing below shows a package named package1 containing a single class

Package package1; public class ClassA {

public void display() { System.out.println("Class A"); } } This source file should be named classA. Java and stored in the subdirectory package1 as stated earlier. Now compile this java file. The resultant classA.class will be stored in the same subdirectory.

Importing classes from other packages: import package1.ClassA; import package2.*; Class PackageTest2 { public static void main(String as[]) { ClassA objectA= new ClassA(); ClassB objectB= new ClassB(); objectA.displayA(); objectA.displayB(); } } Compiling the packages:

Compilation of the PackageTest2 is shown below.

Javac -d . PackageTest2.java; * Here -d indicates folders will be created with the same pattern as declared in the package . * "." Indicates compiled .class file will be stored within the same drive. * We can specify the path instead of '.'

Running the package: Running of the package "Package package1.PackageTest2" shown below. * Java package1.PackageTest2;

Access specifiers (or) Visibility modifiers We have four types of Access specifiers :

1. private 2. default 3. protected 4. public » Private members can be accessed within the class only. » Default members can be accessed within the class, subclass and non-subclass of within the package. » Protected members can be accessed within the class, inside subclass and non-subclass of same package and subclasses of different packages. » Public members can be accessed anywhere.

Order of access specifiers :

The table given below will make the concept of access modifiers more clear : Access Modifiers

default

Private

Protected

Public

Accessible inside the class

yes

yes

yes

yes

Accessible within the subclass inside theSame package.

yes

no

yes

yes

Accessible outside the package

no

no

no

yes

Accessible within the subclass outside the package

no

no

yes

yes

Method Overriding : Implementing the super class method is a subclass with the same-method signature, return type and access specifiers is called method overriding.

Rules for method overriding : » Superclass method signature must be same as subclass method signature. » Subclass method 'return type' must be same as superclass method return type.

» When superclass method has the access specifier then subclass method must have same access specifier (or) any other which has highest privileges than super class specifier.

When super class method is throwing method level exception, in subclass the following is legal : 1. We can omit the method level exception. 2. We can throw the same exception. 3. We can throw any other exception which is subclass to superclass method exception. 4. Don't throw superclass of superclass method exception. Note : » private methods can be overridden. » static methods can be overridden. » static methods can't be overridden as non-static methods. We can't override main method with string array as arguments.

Java Language Java Character set : » Alphabets (A---Z),(a---z) » Digits (0--------9) » Special Symbols (+,-,/,{,},[,],*.....etc) Identifiers : Identifiers are the name which you can form using character and character set we can use identifiers for following : » Variable name » Method name » Class name » Interface name » Package name » Constants Following are the rules we need to follow to form legal identifiers : a) We have to use the characters from java character set only. b) First character must be alphabets.Digits & special symbols are not allowed except "_" and "$"

c) Key words cannot be used as identifiers. d) Identifiers cannot be keywords. Keywords : Keywords are the words which have predefined meaning. You can not change the meaning of the keywords it is called as reserve words. We have 49 key words. Access Specifiers Key words : » private » public » protected Variable, Method & Class keywords : » class » interface » static » abstract » final » volatile » transient » native » strictfp » instanceOf » new » synchronized Data types : » int » float » char » double » long » short » byte » boolean

Package : » package » import Reference variable key words : » this » super Control statement keywords :

» » » » » » » » » »

if else for while do switch break continue default case

Exception handling key words : » try » catch » throw » throws » finally » assert Depricated list key words : » goto » const MISC : » implements » extends » void » return

DATA TYPES We have 8 primitive data types in java : No

Data types

Default value

Size in byte

Range

1.

byte

1

0

-128 to +127

2.

short

2

0

-32,768 to +32,767

3.

int

4

0

-2,147,483,648 to +2,147,483,647

4.

long

8

0

-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

5.

float

4

0.0f

1.40129846432481707e-45 to

3.40282346638528860e+38 6.

double

8

0.0d

4.94065645841246544e-324d to 1.79769313486231570e+308d

7.

char

2

'\u0000'

'\u0000' (or 0) to '\uffff' (or 65,535)

8.

boolean

not specified

false

not require

Note : byte, short, int, long, float & double are number types in Java. All the number's are signed i.e we can store both +ve & -ve values . For example, in integer 1 bit is signed bit & remaining 31 bits are data bits. Variables : Variable is a name which is given to memory location. (or) Variable is name which is used to access the data in the program. Declaration of variables : Data type var1, var2, var3......; Ex: int a,b,sum; float f,g; char c,d; Before using the variable in the program, we should declare that first other wise it will give syntax error. The statement which you are using to declare the variable is called declaration statement. Initialization variables at declaration time: Data type var1=value1, var2=value2.......; Ex: int x= 10, y=20; Simple program : Class Hello { public static void main(string as[]) { System.out.println("welcome to [email protected]"); } } Compiling java program:javac Hello.java Run java program:java Hello Class Vardemo {

static int I; static short s; static byte b; static long l; static float f; static double d; static char ch; static boolean b; public static void main(String args[]) { int a=99; System.out.println(a); System.out.println(s); System.out.println(i); System.out.println(b); System.out.println(l); System.out.println(f); System.out.println(d); System.out.println(ch); System.out.println(b); }} Syntax : find data type =value; Ex: final int x=20; Constants are called final variables whose values cannot be changed. Literals : Literal is nothing but a value .we have 4 types of literals : 1.Integer literal. 2.floating point literal. 3.character literal. 4.String literal. 1.Integer literal: Integer literal is nothing but collection of digits without a decimal point .We have 3 types of integer literal in JAVA : a)decimal Integer literal(o....9). b)octal Integer literal(0...7). c)Hexa decimal Integer literal(0...9, A...F, a....f). 2.Floating point literal :It is collection of digits with decimal points(or) exponential notation Ex:12.56, 123e-7 3.character literal: single character which is enclosed between single quotation is called character literal. Ex: 'A','a','+' Character literals uses ASCII character set to store the values internally. i.e. every character which is enclosed between single quotation marks will be same as ASCII value. 4.String literal : one or more character enclosed between double quotation marks is called a String literal. Ex:"srinivas"; "ab+12999"; Operators

1.Arithmetic Operator(+,-,*,/,%) 2.Assignment Operator(=,+=,-=,*=,/=,%=) 3.Relational Operator (=,==,!=) 4.logical operator(--,++) 5.ternary operator(?:) 6.Bitwise Operator(>>, right shift & bit wise logical and | bit wise logical or ^ bitwise logical xor ~ bit wise logical not (negation) Bit wise operators operator on bits of given values.

Java Language JAVA's encoding technique is 1's compliment. Left shift(2 class BitWise{ public static void main(String as[]){ int a=16; System.out.println(a>>2); System.out.println(a
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF