Lynda Java

STATIC MEANS will call it from class not from instance of the class.


every thing is an object
you will be placing code inside class definition. And wraping that code inside function called methods.

executable code is inside the main method.

public class SimpleApplication
{ public static void main(String[] args
{System.out.println("Hello Worls!");
}
}

here tha name of the class is simple application. It has single method or function called main, and returns void or nothing.

in this version of application there are 2 classes.

public class Simple Application
{
public static void main(String[] args)
{
Welcomer welcomer = new Welcomer();
welcomer.sayHello();
}
}

puclic class Welcomer
{
private String welcome= "Hello";
public void sayHello()
{System.out.println(welcome);
}
}

 Starting Class is called simple application. because its the one with the main method.
And as the application starts the main method is called. And the code in that method create a instance of another class called
welcome. That class is shown at the bottom of the screen.


Down
it declares a variable called welcome, outside method, we call those variable as instance variables or fields.
in this case there is instance variable  named welcome and its private to the class, which means it cand be read
by the code within the class,  whose value is hello.
when the function "sayHello" is called from the class, then that class is responsible for outputtig the string to the console.

Frm the main application we create instance of that class called Welcome that is the upper case version, that is the data type.
then there is lowercase version is the name of the variable "welcome" say that is equal to the  new instance of ther Welcomer class, thats the object. And an object can have method and properties.
We call the object "sayHello" method , and the result is to output the string to the command line.

In java we say ervery thing is an object because it is very common to create instance of class to execute some code. and that code will be wraped inside the class.



String welcome = new String ("Hello");

here we create new instance of the string class. And welcome is an object.

public class Main{
public static void main(String[] args)
{char[] chars = {'H','e','l','l','l','o'}; //create an array of characters
String s = new String(chars);// we wrap the array inside string named s. Now we have either an array of 6 objects. Or string of single object.
System.out.println(s);
}}

By breaking things down in small peices, in java, its make easy to expand the code we want to see or fix.



String Class.

java.Lang.String

charAt(int) :char
compareTo(Object): int
concat (String) :String
copyValueOf (char[]): String
endWith (String) : boolean
getBytes(): byte[]
indexOf(String) :int




Types of Variable
There are 2 types of variable

1. Primitive : Stored in the fastest possible memory. They are all in lower case. (int, double, float, boolean)
Numeric, Single character, Bollean

int newVariable = 10;
data type , variable name , initial value

literal value
byte b = 1;
short s= 10;
int i = 10;
long l =100L; // if we dont use L, then internally the value will be cast based on rule. will be cast to byte. and then it will b upcast to long, then will b using                  more memory.
float f = 150.5f;
double d= 150.5d;


HELPER CLASSES
HELPER CLASS

helper class include conversion and output.
Primitive   DATATYPE HELPERCLASS
byte   Byte
short Short
int Interger
long Long
float Float
double Double

double doubleValue = 156.7d;
Double doubleObj = new Double(doubleValue);

byte myByteValue = doubleObj.byteValue();
int myIntValue = doubleObj.intValue();
float myFloatValue = doubleObj.floatValue();

in primitive data type we dont initialize a value it will be defaulted to zero.

FOR PRECESSION then use bigdecimal.

correct:
double d = 115.737;
String ds = Double.toString(d);
BigDecimal bd = new BigDecimal(ds);
System.out.println("The Va.ue is "+bd.String());

out put 115.737;


wrong
double d = 115.737;
BigDecimal bd = new BigDecimal(d);
System.out.println(bd.toString());
output 115.737433333333388080980;


2. Complex Object; We declare complex object as instance of a java class. They are all in upper case. (String, Strings, date, everthing else.

when set value of complex objext , you use the new keyword and a particular function/method called the constructor method of the class.The name of the constructor method matches the name of the class.So when u declaring soething as string then u r going to use method called string.

Date newDate = new Date();
   //Custotor method.

if we eliminate the assignment from the variable name name will exist but it wont point to anything in the memory .



When u declare variable inside the function, the variable is local to the function. and the function complete exceuting the variable goes away, its no longer available. We call it derefrenced.


sccess
void doSomething()
{String sayHello = new String("Hello");
System.out.println(sayHello);
}

error
void doSomething()
{
{String sayHello = new String("Hello");
}
System.out.println(sayHello);

}






CONVERSION

conerting upward.(implicit)
byte-> short-> int-> long-> float-> double

int intValue = 120;
double doubleResult = intValue;

result 120.0


conerting downward.(explicit)
byte<- short<- int<- long<- float<- double

here will get compile time error. Bcoz java knows we can loose some data. So here we do things explicitly. Here we take int value and cast it to an integer.

Simple Casting // uses less code than helper class, and we are not creating a new object.
double doubleVlaue = 3.99;
int intResult = (int)doubleValue; // (int) it means take the double value and cast/convet/truncating value to an integer and then u can pass the value over.


Helper Class Method
double doubleValue = 3.99;
double doubleObj = new Double(doubleValue);// here we create the instance of the double class , wrapped arounnd the primitive.
int intResult = doubleObj.intValue();







Operators

Types
Assignment int intValue = 10;
int newValue = intValue +5; = 15  
int newValue = intValue -5;= 5
int newValue = intValue *5; = 50
int newValue = intValue /5; = 2
int newValue = intValue %5; = 0
intValue++; 11
intValue--; 9
intValue += 5; 15
intValue -= 5; 5
intValue *= 5; 50
intValue /=5; 2


POST FIX and PREFIX

int intValue = 10;
System.out.println(intValue ++); Output 10 ,  new value = 11
System.out.println(++ intValue); Output 11 ,  new value = 11

>, >= , <,<=, instanceof

String s = "Hello";
if (s instanceof java.lang.String)
{System.out.println("s is a String");}



COMPARING STRING
String s1 = "Hello";
String s2 = "Hello";
if (s1.equals(s2))
{System.out.println("They match");
}
else
{System.out.println("They dont match");}
}


Compaing primitive
if (this == that)
if( this != that)
if(!this) // reverse the value of the boolean expression
if(this && that) // if this and that are true
if(this || that) if either of the variable equate to true



Equality
Mathematical
Conditional
ternary








CHARACTERS
java allows to represent string in one of two ways. as complex objects or as single characters. When u r working with single character then u can work with either primitive data type or wrapper class.

unicode are like ASCII value. u\0024 = $


STATIC MEANS will call it from class not from instance of the class.
System.out.println(Character.toUpperCase(a1));

use system library to see all kinds of method like toUpper etc.


True and flase are stored in boolean

public class Main
{
public static void main(String[] args)
{
boolean b1 = true;
boolean b2 = false;
boolean b3 = !b1;  // reversing b1
System.out.println(" the value of b1 is"  +b1);
System.out.println(" the value of b1 is"  +b2);
System.out.println(" the value of b1 is"  +b3);

int i =1;
boolean b4 = (i!= 0);
System.out.println( the value of b4 is" +b4);

//parsing
String i = "True";
boolean b5 = Boolean.parseBoolean(s);
System.out.println( the value of b4 is" +b4);


}}


searh java.lang.object
//java.lang means it is available to code.












While printing the whole value will be converted to string

public class Main
{
public static void main(String[] args)
{
char c = 'z';
boolean bool = 'true';
byte b = 127;
short s = 32000;
long l = 10000L;
int i = 200000;
float f = 150.5f;
double d= 150.5d;
System.out.println(c);
System.out.println(b);
System.out.println(s);
System.out.println(l);
System.out.println(i);
System.out.println(f);

System.out.println("The value of c is" +c);
System.out.println(s+ "The value of c is");

Date myDate = new Date();
System.out.println(" The new date is" +myDate);

//clt+spacebar java.util

}}













sIMPE  Calculator

public class Calculator
{
public static void main(String[] args)// it has a main method that makes a call to get input method.
{
String S1 = getInput("Enter a value");
System.out.println(s1);
}

private static String getInput(String prompt) // accept a input and return as a string
{BufferedReader stdin = new BufferedReader // BufferedReader and InputStreamReader are classes.
{
new InputStreamReader(System.in));
System.out.print(prompt):
System.out.flush();
try{return; stdin.readLine();
}
catch (Exception e) {
return "Error: "+e.getMessage();
}
}
}



//

public class Calculator
{
public static void main(String[] args)// it has a mai n method that makes a call to get input method.
{
String S1 = getInput("Enter a numeric value");
String S2 = getInput("Enter a numeric value");

double d1 = Double.parseDouble(S1);  // call the Double Wrapper class
double d2 = Double.parseDouble(S2);
double result = d1+d2;

System.out.println(" The answer is" +result);


}

private static String getInput(String prompt) // accept a input and return as a string
{BufferedReader stdin = new BufferedReader // BufferedReader and InputStreamReader are classes.
{
new InputStreamReader(System.in));
System.out.print(prompt):
System.out.flush();
try{return; stdin.readLine();
}
catch (Exception e) {
return "Error: "+e.getMessage();
}
}
}









CONDITION

public class Main
{
public static void main(String[] args)
{
int monthNumber = 3;

if (monthNumber >=1 && monthNumber <= 3)
{System.out.println("You are in quater 1");
}
else if (monthNumber >=4 && monthNumber <= 6)
{System.out.println("You are in quater 1");
}
else  
{System.out.println("You are not in first half of the year");
{
}
}



public class Main
{
public static void main(String[] args)
{
String month = "Feburay";
if(month.equals("Febuary))
{System.out.println("It is the second month");
}}}

for primitive value mathermatical equality operator for string use method of the string class like equals or contains.





SWITCH

injava 6 - u can use switch with interger, shorts, byte and enum.

injava 7 - u can use switch with string also.






public class Calculator
{
public static void main(String[] args)// it has a main method that makes a call to get input method.
{
String input  = getInput("Enter a value between 1 and 12");
int month = Interger.parseInt(input);
System.out.println(s1);

switch (month)
{case 1:
System.out.println("The month is January");
break;  // used to break out to code block
case 2:
System.out.println("The month is Feurary");
break;
case 3:
System.out.println("The month is March");
break;
default: //execute this code when none of the previous case execute to true
System.out.println("You chose another month.");
}



}

private static String getInput(String prompt) // accept a input and return as a string
{BufferedReader stdin = new BufferedReader // BufferedReader and InputStreamReader are classes.
{
new InputStreamReader(System.in));
System.out.print(prompt):
System.out.flush();
try{return; stdin.readLine();
}
catch (Exception e) {
return "Error: "+e.getMessage();
}
}
}





Working with enums

advantage of enumeration is that u can explicity say therse are the only possible value. Limiting the possibilty.


create a new class
at
public enum Month
{JANUARY,FEBUARY,MARCH;
}



public class SwithWithNums
{
public static void main(String[] args)// it has a main method that makes a call to get input method.
{
Month month = Month.FEBRUARY;

switch (month)
{case JANUARY:
System.out.println("The month is January");
break;  // used to break out to code block
case FEBRUARY:
System.out.println("The month is Feurary");
break;
case MARCH:
System.out.println("The month is March");
break;
default: //execute this code when none of the previous case execute to true
System.out.println("You chose another month.");
}



}
}










LOOPS



public class Main
{
staic private String[] months =
{"January","February", "March", "April", " May", "June", July", "August", "September","October", "November","December"}
//looping an array
public static void main(String[] args)
{ for (int i=0, i< args.length,i++) //for loop,here we are creating complex object
{System.out.println(months[i]);}

for(String month: months)  //for each month in a months array
{System.out.println(months[i]);}    // for each   here we are creating new counter variable


//while loop
int counter = 0;
while (counter < months.length)
{System.out.println(months[counter]);
counter++;}

//do while loop
int counter = 0;
do
{System.out.println(months[counter]);
counter++;}while (counter < months.length);
}

}






METHODS


Function is code that is wrappedup  and then given a name so that it will be called from other part of the application. In java we have a special name for function called method. Method comes from object oriented vocabulary. And refers to a function that is member of the class.
There are global funtion that are available to entire execution enviroment.
Every function is member of a class.

As u start up a application from a command line , java  virtual machine looks for a method called main.
Which has a folling characteristic public, static, void, and an argument.

When u declare a method u describe a access modifier. pubic, private and protected.

pubic: method is available to entire application or atleast any part of the application within the class.So if the class is pulic and method is pubic it can be called from anywhere.
private is opposite of public, the method is only availble within its class. Protected has to do with inheritence, protected method is aviable to currennt
class or any of its subclass

protected package:



Static: means  the method we call is a class method . A class method is called directly from class definition.
where as instance method is called from a instance of a class or object.

 in order to call a method from a main method which is static , the called method should be static. Static method can call static method.
instance method can call instance method, without having to say from where they are comming from.
But for a staic method to call a non staic method, we have to create a instance of the object.



void: means i am not returning nothing

method : doSomething, camel case. readable.




public class Main
{
public static void main(String[] args)
{
doSomething();
}

}


private static void doSomething()
{
System.out.println("This method has been called");
}

}





public class Calculator
{
public static void main(String[] args)// it has a mai n method that makes a call to get input method.
{
String S1 = getInput("Enter a numeric value");
String S2 = getInput("Enter a numeric value");

double result = addTwoValues(s1,s2);
System.out.println("The answer is "+result);

double resultofMultiple = addMultipleValues(1,2,3,4,5);
System.out.println(" The answer of multiple value is"" +resultofMultiple);

}

private static double addTwoValues(String S1, String S2)
{

double d1 = Double.parseDouble(S1);  // call the Double Wrapper class
double d2 = Double.parseDouble(S2);
double result = d1+d2;

return result;  // data type passed here (result) must match should match the data type declared(double).


//System.out.println(" The answer is" +result);


}

private static String getInput(String prompt) // accept a input and return as a string
{BufferedReader stdin = new BufferedReader // BufferedReader and InputStreamReader are classes.
{
new InputStreamReader(System.in));
System.out.print(prompt):
System.out.flush();
try{return; stdin.readLine();
}
catch (Exception e) {
return "Error: "+e.getMessage();
}
}


private static double addMultipleValues(double ... values) // here we tell java that it can as many arguments as long it is doubles.(numeric primitive)
{ double result = 0d;
for (double d: values)
{result +=d;
}
return result;
}
}




------------------------------------------------------------------------------------------------------------------


COMPLEX OBJECTS


STRING

-----------------------------------------------------------------------------------------------------------------------------------------
when we create a string we create instance of class, unlike primitive variable.

public class Main
{
public static void main(String[] args)
{String s1 = "Welcome to california";
System.out.println(s1);

String s2 = new String("Welcome to california");// new String is a constructor method. Because the name of the class is same as name of the method.
System.out.println(s1);


if (s1.equals(s2))
{System.out.println("They Match");
}
else
{System.out.println("They dont Match");
}


//for arrays
char[] chars = s1.toCharArray();
for(char c : chars)
{System.out.println(c);
}
}




STring class is one of the common complex class, it is immutable this means when we set a value of string value, then that value cannot be changed

public class Main
{
public static void main(String[] args)
{String s1 = "Welcome ";
s1 = s1 + "to california";
System.out.println(s1);

StringBuilder sb = new StringBuilder(s1);
sb.append("to california);
System.out.println(sb);

// when we are appending the value we are creating new instance or object of the string class, and we are abandoning the old object and it is there for garagabge collection, but we are using more memory.
//insert method : is used to insert text into a string, append method : is used to appned text to string// String builder : takes less memory, but good for single fret ebviroment//  String buffer is used when we used to syncronyze the use of string in multiple threads.

}
}




Sttring Parse

public class Main
{
public static void main(String[] args)
{String s1 = "welcome to california";
System.out.println("Length of String is " +s1.length());  // output is 10

// we can use parse string using method of string class

int pos = s1.indexOf("California")
System.out.println("Position of California: " +pos);

String sub = s1.subString(11);
System.out.println(sub);  //output is california

String s2 = "Welcome!    ";
int len1 = s2.length();
System.out.println(len1);    output 15
String s3 = s2.trim();
System.out.println(s3.length());  output 8

}
}


------------------------------------------------------------------------------------------------------------------------------------------


DATES


public class Main
{
public static void main(String[] args)
{
Date d = new Date();   //CLT+SPACEBAR // no argument contructor
System.out.println(d);  // the date class has a tostring method, when we pass the object to println , we get print represntation, ouput is today time(gregorian calender)

GregorianCalender gc = new GregorianCalender(2009, 1, 28);// using this method add subtract date
gc.add(GregorianCalender.DATE,1);  // adding 1 date, now to output value we have to convert back to date object.
Date d2 = gc.getTime();  // get time method returns instnce of date class.

For formatting we use
DateFormat df =  DateFormat.getDateInstance();  //factory method,   CLT+SPACEBAR
String sd = df.format(d2);
System.out.println(sd);

or
DateFormat df =  DateFormat.getDateInstance(DateFormat.FULL);  //factory method,   CLT+SPACEBAR
String sd = df.format(d2);
System.out.println(sd);

}
}

//in order to construct the instance of DateFormat, we dont use new keyword, the dateformat class has no of methods we can use, to return instance the DateFormat Class






COMPLEX OBJECTS


STRING

-----------------------------------------------------------------------------------------------------------------------------------------
when we create a string we create instance of class, unlike primitive variable.

public class Main
{
public static void main(String[] args)
{String s1 = "Welcome to california";
System.out.println(s1);

String s2 = new String("Welcome to california");// new String is a constructor method. Because the name of the class is same as name of the method.
System.out.println(s1);


if (s1.equals(s2))
{System.out.println("They Match");
}
else
{System.out.println("They dont Match");
}


//for arrays
char[] chars = s1.toCharArray();
for(char c : chars)
{System.out.println(c);
}
}




STring class is one of the common complex class, it is immutable this means when we set a value of string value, then that value cannot be changed

public class Main
{
public static void main(String[] args)
{String s1 = "Welcome ";
s1 = s1 + "to california";
System.out.println(s1);

StringBuilder sb = new StringBuilder(s1);
sb.append("to california);
System.out.println(sb);

// when we are appending the value we are creating new instance or object of the string class, and we are abandoning the old object and it is there for garagabge collection, but we are using more memory.
//insert method : is used to insert text into a string, append method : is used to appned text to string// String builder : takes less memory, but good for single fret ebviroment//  String buffer is used when we used to syncronyze the use of string in multiple threads.

}
}




Sttring Parse

public class Main
{
public static void main(String[] args)
{String s1 = "welcome to california";
System.out.println("Length of String is " +s1.length());  // output is 10

// we can use parse string using method of string class

int pos = s1.indexOf("California")
System.out.println("Position of California: " +pos);

String sub = s1.subString(11);
System.out.println(sub);  //output is california

String s2 = "Welcome!    ";
int len1 = s2.length();
System.out.println(len1);    output 15
String s3 = s2.trim();
System.out.println(s3.length());  output 8

}
}


------------------------------------------------------------------------------------------------------------------------------------------


DATES


public class Main
{
public static void main(String[] args)
{
Date d = new Date();   //CLT+SPACEBAR // no argument contructor
System.out.println(d);  // the date class has a tostring method, when we pass the object to println , we get print represntation, ouput is today time(gregorian calender)

GregorianCalender gc = new GregorianCalender(2009, 1, 28);// using this method add subtract date
gc.add(GregorianCalender.DATE,1);  // adding 1 date, now to output value we have to convert back to date object.
Date d2 = gc.getTime();  // get time method returns instnce of date class.

For formatting we use
DateFormat df =  DateFormat.getDateInstance();  //factory method,   CLT+SPACEBAR
String sd = df.format(d2);
System.out.println(sd);

or
DateFormat df =  DateFormat.getDateInstance(DateFormat.FULL);  //factory method,   CLT+SPACEBAR
String sd = df.format(d2);
System.out.println(sd);

}
}

//in order to construct the instance of DateFormat, we dont use new keyword, the dateformat class has no of methods we can use, to return instance the DateFormat Class






EXCEPTION



---------------------------------------------------------------------------------------------

Error in java can be seperated into 2 types compile time and run time error.

Complile time: a syntax error or error in the structure of the application.

Run time error: when a exception occurs a variable is generated , an exception object. It is instance of class exception or subclass of exception.

try catch

public class Main
{
public static void main(String[] args)
{
try
{
String[] string = {"Welcome"};
System.out.println(string[1]); //right click // surround with exception
}catch (Exception e)
{e.printStackTrace(); or System.out.println("There was an error");}  // error was ArrayIndexOutOfBoundException so use // catch (ArrayIndexOutOfBoundException e)
System.out.println("The application is still running");
}
}

throw Eception

public class Main
{
public static void main(String[] args)
{
try{
getArrayItem();
}
catch (ArrayIndexOutOfBoundException e)
{ System.out.println("Array was out of bound");=
}

private static void getArrayItem()
throws ArrayIndexOutOfBoundsException// when this particular code is running then it can throw this specific kind of exception object
{
String[] string = {"Welcome"};
System.out.println(string[1]);
}

}


------------------------------------------------------------------------------------------------------------------------------------------

Arrays

All of the item in the array should be of the same type

It is of the fixed array . If resizable array see class arraylist.


public class Main
{
public static void main(String[] args)
{
int[] a1 = new int[3]; // array of size 3 item
for (int i=0, i< a1.lenght, i++)
{System.out.println(a1[i]);}

//different int a1[]
int a1[] = new int[3]; // array of size 3 item
for (int i=0, i< a1.lenght, i++)
{System.out.println(a1[i]);}

int a1[] = {3,6,9}
for (int i=0, i< a1.lenght, i++)
{System.out.println(a1[i]);}

//once u have declare an array u can address the item in the array using array syntax, u can refer to the index of the item using zero base numbering inside bracket.
{System.out.println("The 1st item is " +a3[0]);}
}
}


------------------
2 dimensional Array

public class Main
{
public static void main(String[] args)
{
String[][] state = new String[3][2];

-----------------------------------------------------



ENCAPSULATION

Packaging complex functionality so that it is easy to use in application. We dont put all method in one class. we break code in multiple class.

1. We can restrict access. 1 part of the app can access the method and another part dont.
2. When we store data in a java class , if u wrap it up as encapsulated data u hav the option of hiding of how it is stored.   (whther that data is stored  as n array, aollection ofsome kind, or any other object)
3. Maintainable complex code.


non encapsulated code
static void main(String[] args)
{Olive[] olives = {new Olive(), new Olive(), new Olive()};
OliveOil oil = new OliveOil();
OlivePress press = new OlivePress();
for (Olive olive:olives)
{olive.crush();
oil.add(olive);
}
}
----------------------------------------

public class OlivePress  // custom class
{private Olive[] _olives;  //private variable

public void OlivePress( Olive[] olives)  // constructor method that allows to pass that data in as i create the instace of the class
{
this._olives = olives;
}


// use custom class to wrpa and maintain code
public OliveOil getOil()
{
if (_olives == null)
{
return null;
OliveOil oil = new OliveOil();
for (Olive olive:olives)
{
olive.crush();
oil.add(olive);
}
return oil;
}


calling complexity
static void main(String[] args)
{OlivePress press = new OlivePress({new Olive(), new Olive(), new Olive()});
Olive oil = press.getOil(olives);
}


benifts
breaking functionality into small , maintainable units
grouing function and data together. (individual classes, one for the data ,1 for the functionality and bind them together called loose coupling)






CLASSES
------------------------------------------------------------------


public class Calculator2 {

public static void main(String[] args) {
String s1 = getInput("Enter a numeric value: ");
String s2 = getInput("Enter a numeric value: ");
String op = getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");

int opInt = Integer.parseInt(op);
double result = 0;

switch (opInt) {
case 1:
result = addValues(s1, s2);
break;
case 2:
result = subtractValues(s1, s2);
break;
case 3:
result = multiplyValues(s1, s2);
break;
case 4:
result = divideValues(s1, s2);
break;

default:
System.out.println("You entered an incorrect value");
return;
}

System.out.println("The answer is " + result);
}

private static double divideValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 / d2;
return result;
}

private static double multiplyValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 * d2;
return result;
}

private static double subtractValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 - d2;
return result;
}

private static double addValues(String s1, String s2)
throws NumberFormatException {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 + d2;
return result;
}

private static String getInput(String prompt) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));

System.out.print(prompt);
System.out.flush();

try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}

}




------------------------------------------------------------------------------

Refactoring

public class Calculator2 {

public static void main(String[] args) {
String s1 = InputHelper.getInput("Enter a numeric value: ");
String s2 = InputHelper.getInput("Enter a numeric value: ");
String op = InputHelper.getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");

int opInt = Integer.parseInt(op);
double result = 0;

switch (opInt) {
case 1:
result = SimpleMath.addValues(s1, s2);
break;
case 2:
result = SimpleMath.subtractValues(s1, s2);
break;
case 3:
result = SimpleMath.multiplyValues(s1, s2);
break;
case 4:
result = SimpleMath.divideValues(s1, s2);
break;

default:
System.out.println("You entered an incorrect value");
return;
}

System.out.println("The answer is " + result);
}



}





public class SimpleMath
{ public static double divideValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 / d2;
return result;
}

public static double multiplyValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 * d2;
return result;
}

public static double subtractValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 - d2;
return result;
}

public static double addValues(String s1, String s2)
throws NumberFormatException {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 + d2;
return result;
}

}



import java.io.BufferReader;
import java.io.InputStreamReader;

pubic class InputHelper
{private static String getInput(String prompt) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));

System.out.print(prompt);
System.out.flush();

try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
}



---------------------------------------------------------
packaeges are physical foleders in disc



when u are declaring a method in java application , u can declare it either as a class method or instance method,  a class method is called from the definition of class, an instance method is called from the instance of the class or object.
when u r builing a library of utility function and u are going to pass all the value that the method is going to operate as argument, passed into the method when it is called.
 when u start working with more complex object, object that have persisitant data in them, u are going to use instance method.


Static: means this is a class method and it can be called from class definition. if we drop static void main , then its an instance method.
public: if we want the method to be called from anywhere in the aplication.
private:it is available within the class
protected: when it is availabele in this class or any of its subclass.


import com.lynda.olivepress.olives.Olive;
import com.lynda.olivepress.press.OlivePress;
public class Main
{
public static void main(String[] args)
{
//Olives olive = new Olives();// declare Olives(datatype), variable olive , instantiate new Olives();// java adds no argument constructormethod(method used to create instance of the class)
//olive.crush();

Olive[] olives = {new Olive(), new Olive(), new Olive()};
OlivePress press = new OlivePress();
press.getOil(olive);
}


package com.lynda.olivepress.olives

public class Olives
{
public void crush()
{ System.out.println("ouch");
}
}
 

package com.lynda.olivepress.press

import com.lynda.olivepress.olives.Olive;

public class OlivePress
{
public void getOil(Olive[] olives)
{ for (Olive olive : olives)
olive.crush();// non instance method calling a non instamce method
}
}

s




Inhertence and polyorphism

Inheritence means that there is a relationship between classes inyour application.
An inheritence relationship lets you inherit or extend functionality from one class to another.
In java there is only single inheritence. Each new class can extend or inherit functionality from only one class. This makes easier to manage your code.
(Becoz if we are running into a bug, then that bug can be either in the class u r working wid or class u inherited, but the issue will be there in a liner path.)

Inheritence relationship
1. Parent/Child
Parent has the functionality and the child is inherting.

2. Base/Derived.
Where the base class has the functionality and the derived class is extending it.

Superclass/Subclass.
In java the term which are commonly used are Superclass and Subclass.
The Super class has the functionalty and the subclass extending the superclass.
And each subclass in java can have 1 superclass.

Even if u dont extend a class, all of ur classes are exending to other class, a super class.


There a special class called object, with an upper case O, and this is at the top of java inheritence tree.



Polymorphism

If there is a inheritence relationship between a super class and a subclass, u can deal with a object thats instantaied from the subclass either as its native type, the subclass , or as its inherited or its extended type, the superclass.

to do this u declare the object and insted of declaring the native datatype , u declare the superclass type . If its a class  u r instantiating by calling a constructor method. U call the constructor method from the subclass, but u use the datatype of the superclass.

When u have done that it become possible to take that object which u declare as a superclass and pass in to any method that is expecting instance of the superclass.


Inheritence relationship


olive(Superclass)
| | | |
Kalamata(Subclasses) Ligurian Gaeta Lugano

A subclass can have 1 super class, but a super class can have many subclasses.

Super class dont need any special code. Any class can be a super class.
All feild and method can be inherited unless they are marked as private.
its common to set feilds as private(only superclass can deal wid the feild) and method as protected(method can be call by superclass or by its subclasses) or public.



SuperClass.

package olives;
public class Olive
{
private double volume;//  the feild or data type is marked as private only superclass can deal wid them directly
private boolean crushed = false;
public double getVolume()// getter method can be called by anybody in the application
{return crushed ? volume:0;
}
protected void setVolume(double volume)// the setter mehod can be called by the class itself ,and the subclass
{this.volume = volume;
}
public void crush()
{this.crushed = true;//it will crush the olives
}
}



Inorder to extend the superclass use extend keyword. and refrence the superclass.


package olives;
public class Kalamata extend Olive
{..class implementation..
}

As the subclass is constructed and its constructor method is called it will be responsible for settig its own volume, or the amt of oil its capable of producing.

package olives;
public class Kalamata extend Olive
{public kalamata(){this.setVolume(2);}// within the contructor method kalamata whic matches the name of clas. it call this.setvolume, which is protected method. So the subclass can call it , but the actual data it is affecting is stored in superclass its hiddeen in the rest of the application
}


public class Liguria extend Olive
{public Liguria ()
{this.setVolume(5);// it give 5 unit of oil
}
}


they are both calling the same method, both are using the same hidden data type  that is in the superclass , but they are determing what the actual value is.


Main Class code

i m declaring an arra of olive

Olive[] olives = {new Kalamata(), new Liguria(), new Kamalata()};// all olives bcoz of the inheritence relationship//
// it loop through the olives and call the methods // get the oil// add to the olive oil// and end result will b correct calculation
OlivePress press = new OlivePress(olives); // create instance of olive press
OliveOil oil = press.getOil();// call the get oil method


Oliveoil  oil = new Oliveoil();
for (Olive olive:_olives)
{
olive.crush();
oil.add(olive);
}




--------------------------------------------------------

When u actually declare the instance  of the object  u use the contructor method of the individual subclasses,


this idea that u can create instance of the class by refering to uniquely created contructor method, but then take the object and fit it into a datatype of its superclass is polymorphism.
U are taking a object that has a native type and and u r going to use it as though it is super type.






-----------------------------------------------------------------------------------------------------------

There is anither way of creating inheritence relationship using an interface
An interface in java lets u defibne the structure of a class , including the name and signature of the classes , method and any final feilds that is class or instance variable  that will always have the same value .

 u can then implement that interface with a class which u can instantate.(eg arraylist)

java.util(collection interface)

the collection interface is the high level definition of objects that are part of java collecyion framewrok.
the collection interface defined name and signature of methods, that are part of all clases in the list of implementing classes.


arraylist class.

the idea of an interface is that u are defining a contratct , if u say that a class implememts an interface, it must implements all of these classes, and it must use exact method name  and the same number and datatype  of argument and same retrun datatye.

this then allow u to use the concept of polymorphism in ur code.

An array list can be seen either as array list or the interface it implements (collection)




















---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Why should I know Java for learning OA Framework?
Though you can develop simple applications with OA Framework without knowing basics of Java, it is highly recommended that you learn at least the basics of Java before proceeding to learn OA Framework. OA Framework is a framework based on J2EE. Oracle has tried its level best to keep the framework simple and achieve the functionality with less coding and to be more declarative. Then the next question arises “How much Java one should know?”

Encapsulation
Encapsulation is hiding information from unwanted outside access and attaching that information to only methods that needs to access it. Java is a ocean and you need not know everything in it. This book will guide you with the Java topics relevant to an OA Framework developer.

Object Oriented Programming
Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. The concepts and rules used in object-oriented programming provide these important benefits:
The concept of a data class makes it possible to define subclasses of data objects that share some or all of the main class characteristics. Called inheritance, this property of OOP forces a more thorough data analysis, reduces development time, and ensures more accurate coding.
Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is run, the code will not be able to accidentally access other program data. This characteristic of data hiding provides greater system security and avoids unintended data corruption.
The definition of a class is re-useable not only by the program for which it is initially created but also by other object-oriented programs (and, for this reason, can be more easily distributed for use in networks).
•The concept of data classes allows a programmer to create any new data type that is not already defined in the language itself.

OOPS Concepts
The main OOPS concepts include Classes, Objects and Methods. However, there are a few more concepts that you will want to become familiar with. These are Inheritance, Abstraction, Polymorphism, Event, and Encapsulation.

Encapsulation
Encapsulation is hiding information from unwanted outside access and attaching that information to only methods that need access to it. This binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally.Encapsulation is achieved by declaring variables as Private in a class. This gives access to data to only member functions of the class. A next level of accessibility is provided by the Protected keyword which gives the derived classes the access to the member variables of the base class. A variable declared as Protected can at most be accessed by the derived classes of the class

Abstraction
Abstraction can be defined as the process in which an application will ignore the characteristics of a sub-group and work on a general level when it is needed.

Inheritance
 As the name inheritance suggests an object is able to inherit characteristics from another object. In more concrete terms, an object is able to pass on its state and behaviors to its children. For inheritance to work the objects need to have characteristics in common with each other.

Polymorphism
Polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL).

What is a class?
A class is simply a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint can be used to build multiple buildings, a class can be used to create multiple copies of an object. It defines the attributes and behaviors of objects. It is the blueprint that defines an object

What is an object?
An object is a component of a program that knows how to perform certain actions and to interact with other pieces of the program. Objects can be thought of as "smart" black boxes. That is, objects can know how to do more than one specific task, and they can store their own set of data. Designing a program with objects allows a programmer to model the program after the real world. A program can be broken down into specific parts, and each of these parts can perform fairly simple tasks. When all of these simple pieces are meshed together into a program, it can produce a very complicated and useful application.

What is a method?
A method is a programmed procedure that is defined as part of a class and included in any object of that class. A class (and thus an object) can have more than one method. A method in an object can only have access to the data known to that object, which ensures data integrity among the set of objects in an application. A method can be re-used in multiple objects.

What is an Interface?
An interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated. They can only be implemented by classes or extended by other interfaces.

What is a Java Bean?
A Java Bean is a reusable software component that can be visually manipulated in builder tools.

What is a constructor?
A constructor is called automatically when an object is created. It is usually declared public. It has the same name as the class. It must not specify a return type. The compiler supplies a no-arg constructor if and only if a constructor is not explicitly provided. If any constructor is explicitly provided, then the compiler does not generate the no-arg constructor.


----------------------------------------------------------------------------------------------------------------------


JAVA INTERVIEW QUESTIONS



What  is Java?
Java is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly.

What does a well-written OO program look like?
A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance.

Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default. This is actually a pseudo trick question because the word "virtual" is not part of the naming convention in Java (as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.

Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change to the map. He decided to make a clone of the map in order to save the original data on side. What do you think of it? ?
If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.

What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?

Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.

What is NullPointerException and how to handle it?
When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

An application needs to load a library before it starts to run, how to code?
One option is to use a static block to load a library before anything is called. For example,
class Test {
static {
System.loadLibrary("path-to-library-file");
}
....
}
When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter.

How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Name the containers which uses Border Layout as their default layout?
Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.
Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

What is Collection API ?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection.

What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:

Neither Abstract classes or Interface can be instantiated.

Java Interview Questions - How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
How to define an Interface in Java ?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
public void functionOne();

public long CONSTANT_ONE = 1000;
}

If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

What is a transient variable in Java?
A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.

How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.

What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.

What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

What is thread?
A thread is an independent path of execution in a system.

What is multi-threading?
Multi-threading means various threads that run in a system.

How does multi-threading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

How to create a thread in a program?
You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.

Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

Can each Java object keep track of all the threads that want to exclusively access to it?
Yes. Use Thread.currentThread() method to track the accessing thread.

Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

What invokes a thread's run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.

What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

What is the difference between Process and Thread?
A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process. For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that's why several threads may access the same object. Typically, even though they share a common heap, threads have their own stack space. This is how one thread's invocation of a method is kept separate from another's. This is all a gross oversimplification, but it's accurate enough at a high level. Lots of details differ between operating systems. Process vs. Thread A program vs. similar to a sequential program an run on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory space vs. Share with others Each process has one or more threads vs. Each thread belongs to one process Expensive, need to context switch vs. Cheap, can use process memory and may not need to context switch More secure. One process cannot corrupt another process vs. Less secure. A thread can write the memory used by another thread

Can an inner class declared inside of a method access local variables of this method?
It's possible if these variables are final.

What can go wrong if you replace &emp;&emp; with &emp; in the following code: String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.

What is the Vector class?
The Vector class provides the capability to implement a growable array of objects

What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What's the main difference between a Vector and an ArrayList?
Java Vector class is internally synchronized and ArrayList is not.

What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Best Blogger TemplatesBest Blogger Tips


----------------------------------------------------------------------------------------------------------------------------------------------


JAVA Important Interview Questions and Answers

1. What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

2. What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

3. Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

4. What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie. you may not call its constructor), abstract class may contain static data.
Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

5. What is the difference between an Interface and an Abstract class?
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
\6. Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance, the only interface can help.

7. What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn.
Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

8. State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
public: Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
What you get by default ie, without any access modifier (ie, public private or protected). It means that it is visible to all within a particular package.

9. What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.
A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

10. What is final class?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

11. What if the main() method is declared as private?
The program compiles properly but at runtime it will give "main() method not public." message.

12. What if the static modifier is removed from the signature of the main() method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

13. What if I write static public void instead of public static void?
Program compiles and runs properly.

14. What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".

15. What is the first argument of the String array in main() method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

16. If I do not provide any arguments on the command line, then the String array of main() method will be empty or null?
It is empty. But not null.

17. How can one prove that the array is not null but empty using one line of code?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

18. What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.

19. Can an application have multiple classes having main() method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned.
Hence there is not conflict amongst the multiple classes having main() method.

20. Can I have multiple main() methods in the same class?
No the program fails to compile. The compiler says that the main() method is already defined in the class.

21. Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.

22. Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

23. What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown.
Example: IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown.
Example: StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

24. What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

25. Are the imports checked for validity at compile time? Example: will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

26. Does importing a package imports the subpackages as well? Example: Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

27. What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
Example: String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

28. What is the default value of an object reference declared as an instance variable?
The default value will be null unless we define it explicitly.

29. Can a top level class be private or protected?
No. A top level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.
If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class cannot be private. Same is the case with protected.

30. What type of parameter passing does Java support?
In Java the arguments are always passed by value.

31. Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.

32. Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

33. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

34. How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

35. Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

36. How can I customize the seralization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal.
You should implement these methods and write the logic for customizing the serialization process.

37. What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

38. What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.
Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

39. When you serialize an object, what happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process.
Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

40. What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

41. What happens to the static fields of a class during serialization?
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.

42. Does Java provide any construct to find out the size of an object?
No, there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.

43. What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes.
They are example: Integer, Character, Double etc.

44. Why do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also.
Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

45. What are checked exceptions?
Checked exception are those which the Java compiler forces you to catch.
Example: IOException are checked exceptions.

46. What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

47. What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.
These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. Example: FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference.
In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

48. How to create custom exceptions?
Your class should extend class Exception, or some more specific type thereof.

49. If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

50. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and  does not provide any exception interface as well.

51. How does an exception permeate through the code?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method.
Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

52. What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

53. Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

54. If I write return at the end of the try block, will the finally block still execute?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

55. If I write System.exit(0); at the end of the try block, will the finally block still execute?
No. In this case the finally block will not execute because when you say System.exit(0); the control immediately goes out of the program, and thus finally never executes.

56. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

57. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

58. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

59. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

60. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.
Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

61. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.

62. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

63. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

64. What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

65. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

66. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

67. What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.setDaemon method is used to create a daemon thread.

68. Can applets communicate with each other?
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.
It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.

69. What are the steps in the JDBC connection?
While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();

70. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

71. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

72. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

73. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class.
Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

74. What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).

75. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

76. What are some alternatives to inheritance?
Delegation is an alternative to inheritance.
Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

77. What does it mean that a method or field is "static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.

78. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks.
The scheduler then determines which task should execute next, based on priority and other factors.

79. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

80. Is Empty .java file a valid source file?
Yes. An empty .java file is a perfectly valid source file.

81. Can a .java file contain more than one java classes?
Yes. A .java file contain more than one java classes, provided at the most one of them is a public class.

82. Is String a primitive data type in Java?
No. String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package.

83. Is main a keyword in Java?
No. main is not a keyword in Java.

84. Is next a keyword in Java?
No. next is not a keyword.

85. Is delete a keyword in Java?
No. delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.

86. Is exit a keyword in Java?
No. To exit a program explicitly you use exit method in System object.

87. What happens if you dont initialize an instance variable of any of the primitive types in Java?
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0(zero), a boolean will be initialized to false.

88. What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.

89. What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.
2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

90. What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized.

91. How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

92. Can a public class MyClass be defined in a source file named YourClass.java?
No. The source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.

93. Can main() method be declared final?
Yes, the main() method can be declared final, in addition to being public static.

94. What is HashMap and Map?
Map is an Interface and Hashmap is the class that implements Map.

95. Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow).
HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

96. Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.

97. Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

98. What will be the default values of all the elements of an array defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.
Example: All the elements of an array of int will be initialized to 0(zero), while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.

Comments

Popular posts from this blog

OAF Registration

Java Excel