Java Basics

Java Basics

Java is a programming language owned by oracle.
Java has been developed by a person named James Gosling in the year 1995.
Java is an open source.
Java supports object oriented programming concepts.
Object is an real world entity. Ex: Car,Bike,Animal,Pen,Pencil
Java is platform independent.
Platform means operating systems: windows,linux,mac,AIX,Solaris,Zlinux
Java is case sensitive. The uppercase and lowercase both are different.
Example: helloworld is different from HelloWorld

{} – Curly braces
[]- Square Brackets
()- paranthesis
;- Semi colon
“- Double Quotation
//- Comments

Points to be Noted:
1. The Program name should be given as same name as class Name.
ex: HelloWorld.java
2. Java Execution Flow->It has two steps
a. Compilation-> Checks the syntax errors
Goto the command line and navigate to the location where the file is located and type->
javac HelloWorld.java
(or)
“c:\Program Files\Java\jdk1.8.0_25\bin\javac” HelloWorld.java
Ouput -> HelloWorld.class(Contains bytecode)
Java Bytecode->Java bytecode is the instruction set of the Java virtual machine.A Java programmer
does not need to be aware of or understand Java bytecode at all.
b. Execution-> JVM (Java virtual machine)is an interpreter(executes the code line-by-line)
JVM converts the .class file generated during compilation phase into machine level language.
pre-requisite-> HelloWorld.class
java HelloWorld
output->Prints “Hello World” in the console.
3. Java is platform independent–>”.class” generated during compilation phase
works on all the platforms without any modifications. So, java is platform independent.
Example: Compile a program on windows, and copy the .class to linux and execute the program on linux using jvm.
JDK-Java Development kit
JRE-Java runtime environment
JVM-Java Virtual machine
Compile once and execute on any platform with specific jvm for the operating system.

Eclipse is an IDE(Integrated dev Env) useful to create Java Project,Write Java Programs
and Execute Java Programs.
Eclipse -> when we create a project two folders are created.
src -> to store the java programs Ex:HelloWorld.java
bin -> to store the class files. Ex: HelloWorld.class
Eclipse Downloads: http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/oxygen2
Eclipse shortcuts
syso ctrl+space-> System.out.println
main ctrl+space->public static void main(String args[]){}
Execute ctrl+F11 ->Execute
Opening shortcut editor in eclipse -> ctrl+shift+l
Quick outline -> ctrl+o
Opening a resource -> ctrl+shift+r
Organizing imports -> ctrl+shift+o

Datatype:
Datatypes helps to store values in a variable. They are total 8 datatypes in java.

byte 1byte 8bits
short 2 bytes
int 4 bytes
long 8 bytes for storing time in milliseconds. 10 *60*60*1000
———–Integers

float 4 bytes float f = 2.5f;
double 8 bytes double d = 2.5;

———-Decimal numbers

char 2 byte Character code char c = ‘a’;
boolean true or false boolean b = true;

————————————————————————————————————————————–
String is a class not a datatype. String is useful to store group of characters..
String s =”selenium”;
String s =”Hello World”;
Variable:
Variables helps to store the values. Also the name implies which varies the value
is called an variable.
int i =10; // i is declared as int datatype and assigned a value ’10’
Declaration happens only once. But Assignment happens ‘n’ number of times
Rules for Creating Variable Names:
1. Single Character is allowed for vnames. Ex int i =10; ‘i’ is single character
2. Group of characters are allowed for vnames.Ex: boolean result = true; ‘ result’
3. Alphanumeric characters are allowed for vnames. Ex: int a1 = 10;
(Combination of characters and numbers) a1,b1,student1
4. Variable names should start with character but not numbers int 1a=10; // wrong
5. Keywords which are reserved/predefined cannot be used for vnames.
int public =10;// its not valid becoz public is an predefined keyword

Arrays
Array is an data structure in java mainly useful to store similar data type values.
int i1=10;
int i2=20;
int i3=30;
int i10=100;
Store 10 int values.Solution: create an array
Syntax of an Array:
Datatype arrayname[] = new Datatype[size];
int rollno[] = new int[5];
rollno[0] =1; //[] – square brackets, 0 is index ,value is 1
rollno[1] =2; // ** index starts from zero
rollno[2] =3;
rollno[3] =4;
rollno[4] =5;
rollno[5] =6;
rollno[9]=10;
Points to be noted:
The first line of the statement in any java program, if it is created under a package then
we have to mention as ‘package packagename’.
packages are mainly useful for resolving naming conflicts and for more readability purpose.

Ex: package javaprograms;
int a[] = new int[5];
size = 5;
rnage -> 0 – 4

2. java.lang.ArrayIndexOutOfBoundsException: 6
When the user is trying to access the value outside the range.
These Exceptions are run time exceptions.
These are mainly due to programmatical mistakes.
————————————————————————————————–
Loops:for,while,do-while
loops will helps us to perform acitivity for specified number of times.

Printing Selenium 10 times
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);
syso(“selenium”);

Syntax:

Syntax of for-each loop:Enhanced for-loop

Syntax for while loop:

for loop used when we are sure about how many times to iterate the loop
for(intialization;conditon;increment/decrement)
{
//block of statement

}
while loop execute till the condition is false

while(condition)
{
//block of statements

increment/decrement;
}

Syntax of do-while loop:
intialization;

Diff between while and do- while is even if the condition is false it executes the do-while loop once.
————————————————————————————————–
if-else condition
if(condition) // condition is true
{

do this action
}
else //Condition is false
{
do this action

}
Ternary Operator:
In a single line of code, the Java ternary operator let’s you assign a value to a variable based on a boolean expression (either a boolean field, or a statement that evaluates to a boolean result).
variable = condition ? value_if_true : value_if_false
minVal = (a < b) ? a : b;
Swtich Case:
Syntax:

switch ( variable_to_test ) {
case value:
code_here;
break;
case value:
code_here;
break;
default:
values_not_caught_above;

}

Example:

Debugging:
Insert Break point at a particular line
The Execution stops at a particular break point..
From that step we will take the control and execute Step by Step..
Methods or Functions:
Methods or Functions are mainly useful to perform functionality.
Methods have paranthesis ()
main() is a method. We cannot a write a method in another method.
public static void main(string args[])
{

System.out.println(“hello”);

}

But we can invoke a method with in another method.
In main() we invoked static and non static methods.

public static void main(String args[])
{
ClassName a = new ClassName();
int result = a.add(3,5); // method invocation we invoked add method
}

public int add(int a,int b)// method implementation
{
int c =a+b;
return c;
}

Syntax of methods:
modifier returntype methodname(arg1,arg2,arg3,….)
{

//block of statements

return value;

}

Type1 Ex: Methods which are returning value

Method Implementation:

1. Modifier – public.. 4 modifiers in java public,private,protected,default
2. returntype – int( Can be anyone of 8 datatypes)
3. methodname-add
4. arguments/parameters -int a ,int b
5. returnvalue is c

Imp: return value type should be matching with returntype

public String getTitle()-Selenium WebDriver API
{
String s;
return s;
}

1. Modifier public
2. return type -String
3. methodname-getTitle
4. arguments – no
5. return value -s

API – application programming interface.

Type2:void methods-Methods which are not returning any value

public void display()
{

//block of statements
//return statement is not valid for void methods.

}
modifer – public
returntype – void means nothing
void methods doesnt return any value.
methodname-display

public void get(String url)
{

}
Advantage:

reusability
maintenance of code is easy

Syntax for creating an object:

Classname refVar = new ClassName();
If we want to invoke methods and variables available in the class we have to use Object.

Class Members

They are two types of class Members(Variables & Methods):

1. static class members:

public static int divison(int a,int b)
{

int c =a+b;
return c;// c is a datatype of type int.
}

We have to invoke static members using classname.methodname

2. non-static class members:

public int add(int a,int b)
{

int c =a+b;
return c;// c is a datatype of type int.
}

are invoked using object.

Diff Combinations:
Using Object we can invoke static and non Static variables and methods in a lass.
Using ClassName we can invoke static variables and methods in a class
Using ClassName we cannot invoke nonstatic variables and methods in a class.
———————————————————————————————–
Object:
Object is an real world entity which has state(Variables) and behaviour(Methods).
Example:Car,Bike,cycle,Animal,Cat,Bird,Humanbeings

State : color of the car,model of the car,make of the car these
we call as variables
String color=”white”;
String model=”abc”;
int make = 2015;

Student :
State: name,rollno,sex,age(variables/ properties)
Behaviour: Engine of the car,Speed of the Car,Accerlation of the car
we call as methods

Student :
study(),play,run(),walk()

Class is a template useful for the creation of objects.
———————————————————————————————–

ClassName obj = new ClassName();

public void Calculator(int a,int b) /// treated as a normal java method
{
int c = a+b;

}

Constructor:
Constructor is a method which is having same name as classname and it doesnt have return type and return value

public Calculator()
{

}

public Class Car
{

//Constructor
public Car()
{

}
}

1. Constructors are invoked automatically whenever we create an object.
How to create objects using classname.
ClassName object = new ClassName();

2. What happens if we dont write constructor. Compiler automatically invokes a constructor which is internally invoked not seen by the user.

3. Constructors are useful to intialize the variables in the class.

4. They are two types of constructors in java.

a. Default Constrcutor
b. parameterized Constructor.

In order to invoke the parameterized constructor we have to pass the arg while creating the object

Ex: ClassName Object = new ClassName(arg); this invokes the parameterized constructor.
File f =new File(“inputfile.txt”);

this keyword is useful to distinguish between global and local variables
Ex: this.rollno = rollno;
this.element = element;

———————————————————————————————–
Coding Conventions:
Classes – Mixed Case. First letter of each word is capitalized.
Inbuilt Java Classes-> File,FileInputStream,StringBuffer,String,StringBuilder,Thread,Object
Inbuilt Selenium Classes->FirefoxDriver,InternetExplorerDriver,ChromeDriver,Select,WebDriverWait

Interfaces – Mixed Case. First letter each word capitalized.
Inbuilt Java Interfaces->Runnable,Marker
Inbuild Selenium Interfaces->WebDriver,TakesScreenshot,JavascriptExecutor

Methods – First word is lowerCase. From second word onwards the first letter is caplitalized
Inbuilt Java Methods: createNewFile(),delete(),sleep(long milliseconds)
Inbuilt Selenium Methods: getTitle(),get(),getCurrentUrl(),getPageSource()

3 comments on “Java Basics

  1. siva sundari

    This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.
    Thank you for this blog. This for very interesting and useful.

    Reply
  2. Sirisha

    Very Good Info and easy to understand too.
    please provide more quizzes in core Java and selenium including Testng.
    Thank you for giving this blog which is very useful for everyone.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *