Documentation JAVA
Documentation JAVA
J2ME- Java Micro Edition --> used to develop applications for mobile
applications.
//Statements
}
}
Note: We have to give the className as File name then it is executable else we get
error in compilation.
Main Method --> The program is executed from the main method.
Class:
//Statements
Main:
//Statements
Statements:
System.out.println("Hello World");
Statement Terminator:
Reserved words: class, main, void, static, public, private, protected, etc.
Comments: Comments never be executed these are used to provide the information
to the coding people.
/*_______________________
_________________________*/ --> MultiLine Comments
Program Errors:
Syntax Errors or compilation errors: These are detected by the compiler during
compilation.
Runtime Errors:
Logical Errors:
Location have address, Bytes have address, bytes can be more than one long byte.
Declaration of dataTypes:
Primitive data types--> boolean, byte, char, double, float, int, long, short
Assignment operator(=)
int A=36;
initializes A value as 36
Comparison Operators:
== equal to
<= less than or equal to
!= not equal to
When we try to do arithmetic with different data types then the compilation error
occurs, to overcome this we can use type casting
Type Casting
EX:
double d=189.66;
float f=(float)189.66;
Access Modifiers
private --> Can be accessed within the class, we can use it generating getters and
setters methods.
static --> does not require initialization before it can be used and remains in the
place after use, without being destroyed.
Variable Types
Variable: Name of the location of memory used to hold a data value. Different
types of data require different amount of memory. Compiler job is to reserve
sufficient memory.
Starts with a letter (a-z or A-Z), does not allow any special characters at the
starting. For exception we can use _, $ in between the name
1. Arithmetic
2. Relational
3. Logical
4. Assignment
6. Conditional
7. Bitwise
8. Special
Arithmetic
* --> multiplication
/ --> Division
Relational
== equal
!= not equal
Logical
|| --> or
! --> not
++ --> increment
-- --> decrement
Conditional (Ternary)
Control Flow
if(condition){
//statement
}
if(condition){
//statement
}else {
//statement
}
switch
switch(expression){
break;
case valuen://statement
break;
default: //statement
Loops
Loops allows us to execute a statement multiple times, Often they are referred as
loops like conditions statements, they are controlled by boolean expressions.
Types of Loops
1. While Loop
2. do loop
3. do while loop
4. for loop
While Loop
while(condition){
//statements
If the condition is true statement is executed, then the condition is executed again,
if it is still true. The statement will execute untill the condition is false.
ex:
int count = 1;
while (count<=3) {
System.out.println(count);
count++;
The loop must eventually make condition false. If not, it is called as infinite loops
user have to interrupt program.
Nested Loops
Similar to nested if statements, loops can be nested as well body of loop contain
another loop.
Do-While
do {
//statement
} while (condition)
The statement is executed initially and the condition is evaluated.
ex:
int count=0;
do {
count++;
System.out.println(count);
} while(count<3);
For Loop
//statement
}
ex:
System.out.println(i);
The initialization can be used to initialize or declare the variable, as like while loop
condition, for loop is tested prior. Executed zero or more times.
Access Modifier
An Access modifier specifies which class can access in a given classes and its
fields, constructors and methods.
Class, fields, constructors and methods can have one of the four different JAVA
access modifiers.
1. public
2. private
3. default
4. protected
1. public
2. protected
3. private
Private: May only used by instance of class that declares a variable or methods or
object of the class in main method.
Private modifier
class Data{
//private variable
obj.name="Programmer";
}
Getters and Setters
class Data{
//get method
return this.name;
//Set Method
this.name=name;
return name;
d.setName("Rupesh");
System.out.println(d.getName());
Public
//public method
System.out.println(legCount);
//accessing variable
animal.display();
Default
If we do not explicitly specify any access modifier for classes, methods, variables,
etc., then by default the default access modifier is considered.
class Logger{
void message(){
System.out.println("This is a message");
}
If we try to use the Logger class in another class outside of default package, we
will get a compilation error.
Final Modifier
Final features may not be overwritten, A final class may not be sub-classed, A final
variable cannot be changed once it has been assigned a value.
ex:
class Warlus{
int weight;
Warlus(int w){
weight=w;
class Tester{
void test(){
//wrong
w1=new Warlus(1400);
//correct
w1.weight=1800;
Abstract Modifier
ex:
return count==0;
Static Modifier
staticTest(){
x++;
No matter how may instances of staticTest we have the 'x' variable is same for all.
st.x=69;
//or
staticTest.x=69;
They can access the class's static data, Since static methods are with an instance od
a class there is no "this" variable.
Static Initializers
int x=5;
static {
x=69;
String
Sequence of characters treated as Single unit may include letters, digits, special
characters, etc.
class String
Determine String length, String always knows their size, Strings don't have length
instance variable
ex: str.length();
Method charAt
Method getChar
Comparing Strings
not use == ( gives true when the strings are at same address i.e., same string)
Method compareTo()
str.compareTo(str1); 0 if str and str1 are same, negative if a<b, positive if a>b.
Method regionMatches()
Method indexOf()
Method LastIndexOf()
subString(startIndex)
subString(startIndex, endIndex)
Concatenating Strings
str.contat(str1);
-replace(char, char);
-toUpperCase();
-toLowerCase();
-trim(); --> Remove all spaces at the beginning and ending of the string
-toCharArray();
Method valueOf()
String Buffer
String buffer is used for creating and manipulating dynamic String data. i.e.,
modifiable String, can store characters based on capacity-- Capacity expands
dynamically to handle additional characters.
StringBuffer Constructors
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String It creates a String buffer with the specified string..
str)
StringBuffer(int It creates an empty String buffer with the specified capacity as length.
capacity)
Modifier and Type Method Description
public synchronized append(String s) It is used to append the specified string with
StringBuffer this string. The append() method is
overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public synchronized insert(int offset, String It is used to insert the specified string with
StringBuffer s) this string at the specified position. The
insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public synchronized replace(int startIndex, It is used to replace the string from specified
StringBuffer int endIndex, String str) startIndex and endIndex.
public synchronized delete(int startIndex, int It is used to delete the string from specified
StringBuffer endIndex) startIndex and endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int It is used to ensure the capacity at least equal
minimumCapacity) to the given minimum.
public char charAt(int index) It is used to return the character at the
specified position.
public int length() It is used to return the length of the string i.e.
total number of characters.
public String substring(int It is used to return the substring from the
beginIndex) specified beginIndex.
public String substring(int It is used to return the substring from the
beginIndex, int specified beginIndex and endIndex.
endIndex)
Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable)
String. The Java StringBuilder class is same as StringBuffer class
except that it is non-synchronized. It is available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as
length.
Arrays
Creating an Array
-Declare an array
Syntax:
- <types> [] variable_name;
ex:
Double[]myList;
Double myList[];
Defining
MyList=new int[10];
Assigining Variables
Reusing of Arrays
primes[0]=2;
Arguments of method can accept orbitary number of values, Arguments that can
accept variable number of value is called varargs
Varargs useful for any method that needs to deal with an indeterminate number of
Objects.
Parameters in varargs
Parameters are specified after the method name, inside parameters as required.
class varargs{
OOPs
Inheritance
When an object is created using new, the system must allocate enough memory to
hold all its instance variables. This includes any instance variables.
ex:
class person{
String name="John Smith";
name="Sally Halls";
long empId=37518;
double sal=65000.00;
Hierarchy
There is no limit to the numbers to the number of subclass a clas can have.
Super class constructor can be called using the "super" keyword in a manner
similar to "this". It must be the first line of code in the constructor. If a call to super
is not made the system will automatically attempt invoke the non-argument
constructor of the superclass.
ex:
accountNumber=anAccountNumber;
ownerName=aName;
}
}
super(anAccountNumber, aName);
overdraftLimit=aLimit;
Method Overloading
Subclass inherit all methods from their superclass, sometimes, the implementation
of the method in the superclass does not provide the functionality required by the
subclass. To Override a method, provide implementation in the subclass the
method in the subclass must have the exact same signature as the method it is
overriding.
ex:
if ( anAmount>0.0){
balance=balance+anAmount;
}
public float withdraw(float anAmount){
if(anAmount>0.0&&(balance>anAmount)){
balance=balance-anAmount;
return balance;
balance=balance-anAmount;
//Statements
- This can be used to improve performance because, there wiil be no subclass, ther
will be no poly-morphism.
//Statements
}
PolyMorphism
Assume the Dog class inherits Animal class, redefining the "Make noise" Method.
MyAnimal<--- My Dog
MyAnimal.MakeNoice();
PolyMorphism vs Inheritance
Processing collections
Bank Account
/ \
/ / \
CD Account
- The classes from which the common features were taken become subclassed to
the newly created superclass.
- Often the superclass does not have a meaning or doesn't directly relate to a thing
in the real world.
- Because of this, abstract cannot be instantiated. They act as place holder for
Abstraction.
- Creational patterns: Abstract class provides interface for creating objects. The
subclasses do the actual object creation.
- Ensure that you receive acceptable return in terms of functionality given the
added complexity.
}
Abstract Methods
- Methods can also be abstracted, An abstract method is one to which has been
provided, but no implementation for that method is given.
ex:
public abtract class Transacitons{
//Note: no implementation.}
//Statements
//Statements
What is Interface?
- Interfaces cannot contain instance variable, However, they can contain public
static final variable(i.e. constant class variable).
Declaring an Interface
//Statements
}
public int turnRight(int degrees){
//Statements
Implementing Interfaces
- A class can only inherit from one superclass. However, a class may implement
several interfaces.
- Any class which implements an interface must provide implementation for all
methods defined within the interface.
Declaring an Interface
//Statements
//Statements
}
Inheriting Interfaces
Interfaces Types
- When a class is defined, the compiler view the class as a new type.
- The same thing is true of interfaces. The compiler regards an interface as a type.
int i;
car myFleet[];
Steerable anotherFleet[];
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i].turnRight(45);
Hierarchy of Java Exception classes
%b boolean
%c character
%d integer
%e scientific notation
%f floating point
%s String
%n a new line
%% -%