You are on page 1of 141

Core Java

Eclipse software

Create new java project and name it. (ketaki)


In package explorer on left your named java project will
be created. Do not create a module.
Right click on src and create a package and name it.
(capgemini)
Now right click on package and create class name
(datatypes) , the name must not have spacing and select
public static…..
Java-Introduction

Java is a programming language created in 1995.


It is used for mobile applications.
It is used for desktop applications (.exe files).
It is used for web applications.
Web servers/application servers.
Database connections.
Object oriented language.
Free and Open Source.
Features of Java

Features Description
Simple Easy like C++, no concept of pointers.
Object Oriented Object, class, inheritance, polymorphism, abstraction.
Portable Works Byte code anywhere..
Platform independent
Secured No concept of pointers, Runs on virtual Machine, class loader.
Robust Exception handling
Architecture neutral Fixed things in java.
Interpreted
High Performance Faster than other interpreted programming languages.
Multi threaded Parallel Execution
Distributed Facilitates users to create distributed applications in Java.
Dynamic Memory
Java is platform independent

The Byte code is platform independent.

Source code(Java) Byte Code(Compile) Machine Code(Interprete)

Eg. The class file getting created while we run java on


cmd.
Evolution of Java

Released in 1995.
Version 1.0 to 1.8(2014) Features almost same.
Version 9 in 2017.
Version 17 released in September 2017.
Developing software in Java

Platform Description
Java SE: Standard Edition Basic/Core
Java EE: Enterprise Edition Web, Servlet, Web Services
Java ME: Micro Edition Mobile Application
Java FX Internet Application

All Java platforms consist of a Java Virtual Machine (VM) and an application
programming interface (API). The Java Virtual Machine is a program, for a particular
hardware and software platform, that runs Java technology applications. An API is a
collection of software components that you can use to create other software components
or applications. Each Java platform provides a virtual machine and an API, and this
allows applications written for that platform to run on any compatible system with all the
advantages of the Java programming language: platform-independence, power, stability,
ease-of-development, and security.
JRE Vs JDK Vs JVM
JRE Vs JDK Vs JVM
JRE Vs JDK Vs JVM

JDK – Java Development Kit is Kit which provides the environment


to develop and execute(run) the Java program. JDK is a kit(or package)
which includes two things
 Development Tools(to provide an environment to develop your java programs)
 JRE (to execute your java program).
Note : JDK is only used by Java Developers.
JRE – Java Runtime Environment is an installation package which
provides environment to only run(not develop) the java program(or
application)onto your machine. JRE is only used by them who only wants to
run the Java Programs i.e. end users of your system.
JVM – Java Virtual machine is a very important part of both JDK and JRE
because it is contained or inbuilt in both. Whatever Java program you run
using JRE or JDK goes into JVM and JVM is responsible for executing the
java program line by line hence it is also known as interpreter.
Best Practice in Java

Class name starts with upper case.


Package name starts with lower case.
Use tabs instead of indentations.
Variable names are very important: camelCase, proper.
Use proper name of variable and classes.
Avoid using default package.
Java-Introduction

Keywords: Reserved by the compiler. Eg. break, switch,


class, static, protected, final etc. Cannot be used as
variables.
Variables: Name given to memory location & is user
defined.
Eg.
10
int num=10; Variable name= num
int=keyword Memory location=5001

ium=variable
64 reserved keyword in java
8 primitive data types in java

Data type Description


int -1,0,1,2, (Up to 10 digit)
char (single character) ‘A’,’a’,’-’ (alphanumeric as well)
float (write F/f in end) 10.89f (Upto 7 decimal places)
double 10.999999999
long (write L/l in end) 10000000L (int value greater than 10 digit)
boolean True/false
byte 1 byte of memory location
short Int value less than 10 digit
Hello world in java

package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println("Hello World");
}
}
Semicolon marks end of the statement.
Datatypes in java:
package capgemini;
public class datatypes {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num=10;
char alpha='A';
double marks=95.5;
float age=22.5f;
long phonenumber=999999999L;
boolean result=true;
System.out.println(num);
System.out.println(alpha);
System.out.println(marks);
System.out.println(age);
System.out.println(phonenumber);
System.out.println(result);

}
}
if….else statement

package capgemini;
public class datatypes {

public static void main(String[] args) {


// TODO Auto-generated method stub
int age=10;
if(age>=18)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please wait for a few years");
}
}
}
Else block is not mandatory.
Multiple if’s true:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int age=18;
if(age==18)
{
System.out.println("Congratulations on your first vote");
}
if(age>=18)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please wait for a few years");
}
}
}
Else comes with prior if attached:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int age=10;
if(age==10)
{
System.out.println("Congratulations on your first vote");
}
if(age>=18)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please wait for a few years");
}
}
}
Else if ladder:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int age=18;
if(age==18)
{
System.out.println("Congratulations on your first vote");
}
else if(age>=18)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please wait for a few years");
}
}
}
Nesting if..else:
package capgemini; public class datatypes {
public static void main(String[] args) {
int age=10; char gender='F';
if(age==10){
System.out.println("Congratulations on your first vote");
if(gender=='F'){
System.out.println("Congratulations girl");
}
else {
System.out.println("Congratulations boy");
}
}
else if(age>18){
System.out.println("You can vote");
}
else{
System.out.println("Please wait for a few years");
}
}
}
Pre/post increment

System.out.println(num++)---actual num is printed first


and then increment happen. This is post increment.

System.out.println(++num)---num is incremented first


and then incremented num is printed. This is pre
increment.
for loop

for (initialization; condition; increment/decrement)


package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int num=1;num<=10;num++)
{
System.out.println(num*5);
}
}
}
Print table of 5 for odd numbers with hello:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int num=1;num<=10;num=num+2)
{
System.out.println(num*5);
System.out.println("Hello");
}
}
}
while loop

package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=1;
while(num<=10)
{
System.out.println(num*2);
num++;
}
}
}
Print table of 2 in reverse manner:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=10;
while(num>=1)
{
System.out.println(num*2);
num--;
}
}
}
break statement-breaks the loop

package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=1;
while(num<=10)
{
if(num%5==0)
{
System.out.println("Multiple of 5");
break;
}
num++;
}
System.out.println("congratulations multiple of 5 found");
}
}
do-while loop

package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=1;
do
{
System.out.println(num);
num++;
}
while(num<=10);
}
}
 It atleast runs once even if the condition is not satisfied.
Switch case

package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int day=3;String today;
switch(day) {
case 0: today="Sunday"; break;
case 1: today="Monday"; break;
case 2: today="Tuesday"; break;
case 3: today="Wednesday"; break;
case 4: today="Thursday"; break;
case 5: today="Friday"; break;
case 6: today="Saturday"; break;
default: today="Invalid";
}
System.out.println(today);
}
}
Comments and Identation

Single line comment //


Multiline comment /8abcdefghijklmnopqrstuvwxyz*/
Shortcut to comment=Ctrl+shift+/
Shortcut to uncomment=Ctrl+shift+\
Shortcut to Identation=Ctrl+shift+f
Print and Println

Print: print first.


Println: print first and then breaks the line.
package capgemini;

public class datatypes {


public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.print("Hello");
System.out.println("My name is");
System.out.print("Ketaki");
}
}
Debugging

Add breakpoint by simply right clicking on the line


number and toggle the breakpoint.
Right click and click debug as. Variable, expression and
breakpoint window will appear.
Then press F8 to see changes.
Method/Functions-I

package capgemini;

public class datatypes {


static void loop(int start,int end)
{
for(int i=start;i<=end;i++)
{
System.out.println(i);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loop(10,20);

}
}
Method/Functions-II

package capgemini;

public class datatypes {


static String introduction(String name)
{
String welcome="Hello"+name;
return welcome;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String result=introduction("Selenium");
System.out.println(result);

}
}
Method/Functions-III

package capgemini;

public class datatypes {


static double cube(double num) {
double number= num*num*num;
return number;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
double result = cube(3.99999999);
System.out.println(result);

}
}
Class

An object in Java is the physical as well as a logical entity


or a real world entity, whereas, a class in Java is a logical
entity only.
Class is an umbrella.
It is a template or blueprint from which objects are
created.
Objects

Object is a real world entity.


new keyword is used to give memory to any object.
student s1=new student();
LHS student is constructor
RHS student is class
Access modifier

The access modifiers in Java specifies the accessibility or


scope of a field, method, constructor, or class.
Private Variable= In same class
Public Variable= Anywhere
Default Variable= In same package
Protected Variable= In same package, outside the package
using child class i.e child extends parent.
Creating class and objects in java:
package capgemini;
class student{
int rollno;
String name;
double marks;
char grade;
void hello(){System.out.println("Hello");}
void bye() {System.out.println("Bye");}
}
public class datatypes {
public static void main(String[] args) {
student s1=new student(); student s2=new student();
s1.rollno=10;
s1.name="Ketaki";
s1.marks=95.5;
s1.grade='A';
System.out.println(s1.rollno);System.out.println(s1.name);
System.out.println(s1.marks);System.out.println(s1.grade);
}}
Creating class and objects in java:
package capgemini;
class Employee
{
int employeeId;
String name;
long phonenumber;
void hello(){System.out.println("Hello");}
}
public class datatypes {
public static void main(String[] args) {
Employee Emp1=new Employee();
Emp1.employeeId=101;
Emp1.name="Employee101";
Emp1.phonenumber=99999999;
System.out.println(Emp1.employeeId);
System.out.println(Emp1.name);
System.out.println(Emp1.phonenumber);
}}
Creating class and objects in java:
package capgemini;
class Employee
{
int employeeId;
String name;
long phonenumber;
void hello(){System.out.println("Hello");}
}
public class datatypes {
public static void main(String[] args) {
Employee Emp1=new Employee();
Emp1.employeeId=101;
Emp1.name="Employee101";
Emp1.phonenumber=99999999;
System.out.println(Emp1.employeeId);
System.out.println(Emp1.name);
System.out.println(Emp1.phonenumber);
}}
Get and set:
package capgemini;
class Employee {
int employeeId;
String name;
long phonenumber;
void hello() {
System.out.println("Hello");}
String getName(){
return name;
}
void setName(String n){
name=n;
}}
public class datatypes {
public static void main(String[] args) {
Employee Emp1 = new Employee();Emp1.employeeId = 101;Emp1.name ="Employee101";
Emp1.phonenumber = 99999999;
System.out.println(Emp1.getName());
}}
Swapping in java using 3rd variable:
package capgemini;

public class datatypes {


public static void main(String[] args) {
// TODO Auto-generated method stub
int a=0;
int b=1;
int c;
System.out.println("A:"+a);
System.out.println("B:"+b);
c=a;
a=b;
b=c;
System.out.println("A:"+a);
System.out.println("B:"+b);
}
}
Swapping in java withput using third variable:
package capgemini;

public class datatypes {


public static void main(String[] args) {
// TODO Auto-generated method stub
int a=0;
int b=1;
System.out.println("A:"+a);
System.out.println("B:"+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("A:"+a);
System.out.println("B:"+b);
}
}
Fibonacci series in java:
package capgemini;

public class datatypes {


public static void main(String[] args) {
// TODO Auto-generated method stub
int a=0;
int b=1;
System.out.println("0");
System.out.println("1");
for(int i=1;i<=8;i++)
{
int c=a+b;
System.out.println(c);
a=b;
b=c;
}
}
}
Prime number in java:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=75;int f=0;
for(int i=2;i<num;i++){
if(num%i==0) {
f=1;
break; }}
if(f==1)
System.out.println("Composite number");
else if(num==2)
System.out.println("Prime number");
else if(num==1)
System.out.println("Neither Prime nor composite");
else
System.out.println("Prime number");
}
}
Prime number sequence in java:
package capgemini;
public class datatypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=2;i<=50;i++)
{
int f=0;
for(int j=2;j<=i;j++)
{
if(i%j==0)
{
f=f+1;
}
}
if(f==1)
System.out.println(i);
}
}
}
Polymorphism

Polymorphism/ method overloading/ function overloading.


Poly=many, morphism=forms.
In Java one can create same methods just the parameters needs to be different.
static int area(int side) {
return side*side;
}
static int area(int a, int b) {
return a*b;
}
static double area(double b, double h) {
return 0.5*b*h;
}
Polymorphism in java:
package capgemini;
public class datatypes {
static int area(int side) {
return side*side;
}
static int area(int a, int b) {
return a*b;
}
static double area(double b, double h) {
return 0.5*b*h;
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("The area of square="+area(10));
System.out.println("The area of rectangle="+area(10,5));
System.out.println("The area of Triangle="+area(10,5));
}
}
Constructor

It is a method and has same name as of class with no return type.
It is used to initialize variables of the class.
student(int r, String n, double m, char g)
{
rollno=r;
name=n;
marks=m;
grade=g;
}
public class datatypes {
public static void main(String[] args) {
student s1 = new student(10,"Ketaki",96.75,'A');
Constructor in java:
package capgemini;
class student {
int rollno;
String name;
double marks;
char grade;
student(int r, String n, double m, char g){
rollno=r;
name=n;
marks=m;
grade=g;
}}
public class datatypes {
public static void main(String[] args) {
student s1 = new student(10,"Ketaki",96.75,'A');
System.out.println(s1.rollno);
System.out.println(s1.name);
System.out.println(s1.marks);
System.out.println(s1.grade);
}}
Constructor overloading in java:
package capgemini;
class student {
int rollno;
String name;
double marks;
char grade;
student(int r, String n, double m, char g)
{
rollno=r;
name=n;
marks=m;
grade=g;
}
student(int r, String n, double m)
{
rollno=r;
name=n;
marks=m;
grade='B';
}
Constructor overloading in java cntd:
student(double m, char g){
rollno=51;
name="Nobody";
marks=m;
grade=g;
}
void print() {
System.out.println(rollno+" "+name+" "+marks+" "+grade);
}
}
public class datatypes {
public static void main(String[] args) {
student s1 = new student(10,"Ketaki",96.75,'A');
student s2 = new student(10,"Ketaki",96.75);
student s3 = new student(96.75,'A');
s1.print();
s2.print();
s3.print();
}
}
Memory allocation is java

Source code to Machine language=Compilation(.java)


First code is compiled then only memory is given to it.
Memory is given at run time and some is given at compile
time.
Everything in main, using new keyword memory is given
at run time.
static

Static resolves at compile time.


One can invoke static variables and methods without
creating objects.
Static variables/methods belongs to class not the object.
Static helps to avoid wastage of memory.
static

 Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All
students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of all 
objects. If we make it static, this field will get the memory only once.
static:
package capgemini;
class student {
static void print(){
System.out.println("Hello");
}
}
public class datatypes {
static{
System.out.println("Hello there I'm static");
}
static void prints()
{
System.out.println("Hello flocks");
}
public static void main(String[] args) {
prints();
student.print();
}
}
final

It is a keyword whose value cannot change.


One has to initialize final variable at the time of declaration.
package capgemini;
class student {
final String schoolname="ABD";
}
public class datatypes {
public static void main(String[] args) {
student s1=new student();
System.out.println(s1.schoolname);
}
}
this

Used in class to list all methods or variables of class.


Inheritance

Child extends parent class would inherit all methods and


variables from parent class.
Parent=house
Child=house+car
Grandchild=house+car
Inheritance promotes code reusability.
No multiple(2/more) inheritance.
Inheritance allowed
Overriding

 Here print().void-parent is
not present as child is over
riding parent method.
 This is overriding.
 The method must have the
same name as in the parent
class.
 The method must have the
same parameter as in the
parent class.
Static and dynamic Polymorphism

 Parent p2=new child();


 We are creating object of child but only referring properties from
parent class.
Here in 1st overriding is
happening as it is
printing child even
though it should print
parent. To avoid this
overriding we make the
overriding methods
static as static will
resolve only at runtime
avoiding overriding.
1. Dynamic
2. Static
super

 The super keyword in Java is
a reference variable which is
used to refer immediate
parent class object.
Encapsulation

Encapsulation means wrapping up of variables and


methods in a single unit.
Example. Class
public static void main(String[] args)

 JVM is looking for main method to start execution.


 Public is an access modifier which specifies who can access the
method.
 Static is keyword associated with method.
 Void means it does not return anything.
 Static[]args stores java cmd line arguments and is an array of type
java.lang.String class.
public: It is an access specifier. We should use a public keyword before the main() method so that JVM
can identify the execution point of the program. If we use private, protected, and default before the
main() method, it will not be visible to JVM.

static: You can make a method static by using the keyword static. We should call the main() method
without creating an object. Static methods are the method which invokes without creating the
objects, so we do not need any object to call the main() method.

void: In Java, every method has the return type. Void keyword acknowledges the compiler that main()
method does not return any value.

main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute a
program line by line and end the execution after completion of this method. We can also overload the
main() method.

String args[]: The main() method also accepts some data from the user. It accepts a group of strings,
which is called a string array. It is used to hold the command line arguments in the form of string
values.
Array

 To declare an array, define the variable type with square brackets.


 To insert values to it, we can use an array literal - place the values in
a comma-separated list, inside curly braces.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
Declararing Array

package capgemini;

public class datatypes {


public static void main(String[] args) {
int[] arr1= {10,20,30,40,50,60};
int arr2[]= {1,2,3,4,5,6};
int[] arr3= new int[5];
arr3[0]=100;
arr3[1]=200;
arr3[2]=300;
arr3[3]=400;
arr3[4]=500;
}
}
Printing Array

package capgemini;
public class datatypes {
public static void main(String[] args) {
int[] arr1= {10,20,30,40,50,60};
int arr2[]= {10,20,30,40,50,60};
int[] arr3= new int[5];
arr3[0]=100;arr3[1]=200;arr3[2]=300;arr3[3]=400;arr3[4]=500;
System.out.println("Array1:");
for(int i=0;i<6;i++) {
System.out.println(arr1[i]);}
System.out.println("Array2:");
for(int i=0;i<6;i++) {
System.out.println(arr2[i]);}
System.out.println("Array3:");
for(int i=0;i<5;i++) {
System.out.println(arr3[i]);
}}}
Printing reverse array

package capgemini;
public class datatypes {
public static void main(String[] args) {
int[] arr1= {10,20,30,40,50,60};
int arr2[]= {10,20,30,40,50,60};
int[] arr3= new int[5];
arr3[0]=100;
arr3[1]=200;
arr3[2]=300;
arr3[3]=400;
arr3[4]=500;
System.out.println("Array1 Reverse:");
for(int i=5;i>=0;i--) {
System.out.println(arr1[i]);
}}}
Enhanced for loop

for(int num:arr1)
Initialization, condition and increment or decrement are
done internally.
This will only print array from start to end i.e arr[0] to
arr[n-1] fro n-length array.
No other condition can be given fort his loop like reverse,
a[1] to a[7] etc.
Enhanced for loop:
package capgemini;

public class datatypes {


public static void main(String[] args) {
int[] arr1 = { 10, 20, 30, 40, 50, 60 };
int arr2[] = { 10, 20, 30, 40, 50, 60 };
int[] arr3 = new int[5];
arr3[0] = 100;
arr3[1] = 200;
arr3[2] = 300;
arr3[3] = 400;
arr3[4] = 500;
for(int num:arr1)
{
System.out.println(num);
}
}
}
String Array

package capgemini;
public class datatypes
{
public static void main(String[] args) {
String[] arr1 = {"Sunday","Monday","Tuesday"};

System.out.println("Array1");
for(String num :arr1)
{
System.out.println(num);
}
}
}
Bubble sort:
package capgemini;
public class datatypes {
public static void main(String[] args) {
int[] arr1 = {50,54,698,48,1,55,5 };
int temp = 0;
for (int i = 0; i <= arr1.length-1; i++) {
for (int j = 0; j <= arr1.length-i-2; j++) {
if (arr1[j] > arr1[j + 1]) {
temp = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = temp;
}
}
}
System.out.println("Bubble Sort:");
for (int i = 0; i < 6; i++) {
System.out.println(arr1[i]);
}
}}
Two Dimensional Array [rows][cols]
Two Dimensional Array

package capgemini;
public class datatypes {
public static void main(String[] args)
{
int[][] arr1 = {{10,20,30},{30,40,40},{50,70,60}};
for (int i = 0;i <= 2;i++)
{
for (int j= 0; j<= 2; j++)
{
System.out.print(arr1[i][j]+" ");
}
System.out.println();
}
}
}
Addition of two matrices:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
int[][] arr1 = {{10,20,30},{40,50,60},{70,80,90}};
int[][] arr2 = {{10,20,30},{40,50,60},{70,80,90}};
int arr3[][]=new int[3][3];
for (int i = 0;i <= 2;i++)
{
for (int j= 0; j<= 2; j++)
{
arr3[i][j]=arr1[i][j]+arr2[i][j];
System.out.print(arr3[i][j]+" ");
}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print("*");

}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j);

}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
int k=1;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(k++);
System.out.print(" ");

}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
for (int i = 5; i>= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print("*");

}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main (String args [])
{
for(int i=1;i <= 5;i++){
for(int j=1;j <= 5-i;j++){
System.out.print(" ");
}

for(int k=1;k<=i; k++){


System.out.print("*");
}

System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
for (int i = 0; i < 6; i++) {
for (int j = (6 - i); j >= 0; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print("*");
System.out.print(" ");
}
System.out.println();
}
}
}
Star pattern:
package capgemini;

public class datatypes {


public static void main(String[] args)
{
for (int i = 0; i < 6; i++) {
for (int j = (6 - i); j >= 0; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print(i+" ");
}
System.out.println();
}
}
}
Strings

String is a class in java.lang and is a sequence of


characters.
Strings are immutable i.e one cannot change the value of
string in java. Fig.1
New string is created to concat the string i.e s
Strings are inmmutable

 Here Sachin is not changed but


a new object is created with
Sachin Tendulkar. That is why
String is known as immutable.
 As you can see in the above
figure that two objects are
created but s reference variable
still refers to "Sachin" not to
"Sachin Tendulkar".
 But if we explicitly assign it to
the reference variable, it will
refer to "Sachin Tendulkar"
object.
String methods

package capgemini;
public class datatypes {
public static void main(String[] args) {
String s="Selenium123";
String str1=" Selenium ";
String str="Selenium-Java-training";
System.out.println(s.charAt(0));
System.out.println(s.concat("456"));
System.out.println(s.indexOf('e'));
System.out.println(s.replace('e', 'E'));
System.out.println(s.length());
System.out.println(s.substring(2));
System.out.println(s.toLowerCase());
System.out.println(s.toCharArray()[0]);
System.out.println(str.split("-")[1]);
System.out.println(str1.trim());
}}
ASCII Code

ASCII acronym for American Standard Code for


Information Interchange.
It is a 7-bit character set contains 128 (0 to 127)
characters.
It represents the numerical value of a character.
A=65 and a=97 that’s all you need to remember.
Import Package

There are many packages to choose from. In the previous


example, we used the Scanner class from
the java.util package. This package also contains date and
time facilities, random-number generator and other utility
classes.
To import a whole package, end the sentence with an
asterisk sign (*). 
import java.util.Scanner;
import java.util.*;
Object class

It is present in java.lang and every class is derived from the


object class.
package capgemini;
public class scanner_class {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="Hello";
System.out.println(s.toString());
System.out.println(s.hashCode());
System.out.println(s.equals("Hello"));
}
}
Wrapper Class

Data type Wrapper Class


int Integer
char (single character) Character
float (write F/f in end) Float
double Double
long (write L/l in end) Long
boolean Boolean
byte Byte
short Short
Autoboxing

Unboxing
Type casting

double myDouble = myInt;


int integer1= (int)myDouble;
Type casting:
package capgemini;
public class scanner_class {

public static void main(String[] args) {


// TODO Auto-generated method stub
int myInt = 9;
double myDouble = myInt;
float myshort= (float)myDouble;
int integer1= (int)myDouble;

System.out.println(myInt);
System.out.println(myDouble);
System.out.println(integer1);
}

}
Scanner class

It is present in Java.util package and is used to take input


from user.
import java.util.Scanner;
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
sc.close();
Scanner Class:
package capgemini;
import java.util.Scanner;
public class scanner_class {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String src=sc.next();
double d=sc.nextDouble();
char alpha=sc.next().charAt(0);
System.out.println(num);
System.out.println(src);
System.out.println(d);
System.out.println(alpha);
sc.close();
}

}
String Handling
String literal vs String Object

package capgemini;
public class scanner_class {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s="Hello"; //literal
String s1="Hello"; //literal
String s2=new String("Hello"); //object
String s3=new String("Hello"); //object
}
}
String literal vs String Object
== vs .equals()

== compares memory addresses.


.equals() compares values.
String literal vs String Object Class:
package capgemini;
public class scanner_class {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s="Hello"; //literal
String s1="Hello"; //literal
String s2=new String("Hello"); //object
String s3=new String("Hello"); //object
if(s==s1)
{
System.out.println("Literals are equal");
}
if(s2.equals(s3))
{
System.out.println("Objects are equal");
}
}
}
StringBuilder

Strings in java are immutable.


StringBuilder are mutable.
No reverse method in string but present in StringBuilder.

package capgemini;
public class scanner_class {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuilder sb=new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
System.out.println(sb.reverse());
}
}
Count number of words in String:
package capgemini;
public class count_words {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="Today is Tuesday";
int spaces=0;
for(int i=0;i<s.length();i++) //Method 1
{
if(s.charAt(i)==' ') {
spaces++;
} }
System.out.println(spaces+1);
String words[]=s.split(" "); //Method 2
for(int j=0;j<words.length;j++)
{
System.out.println(words[j]);
}
System.out.println(words.length);
}
}
Add digits present in String:
package capgemini;
public class count_words {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s = "Hello123World3";
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
char character = s.charAt(i);
if(Character.isDigit(character))
{
sum = sum + Character.getNumericValue(character);
}
}
System.out.println(sum);
}
}
Date and time

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date
Date and time in Java:
package capgemini;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class date_time {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
Date date=new Date();
Date date1=new Date();
Date date2=new Date();
SimpleDateFormat SDF=new SimpleDateFormat("dd-MM-yyyy");
date=SDF.parse("22-11-2021");
System.out.println(date);
SimpleDateFormat STF=new SimpleDateFormat("HH:mm:SS");
date1=STF.parse("23:43:45");
System.out.println(date1);
SimpleDateFormat SDTF=new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:SS'Z'");
date2=SDTF.parse("22-11-2021T23:43:45Z");
System.out.println(date2);
}}
InstanceOf

This keyword checks whether object is an instance of the specified type (class
or subclass or interface).
package capgemini;
class Student{
}
class Child extends Student{
}
public class scanner_class {
public static void main(String[] args){
// TODO Auto-generated method stub
Child s1=new Child();
System.out.println(s1 instanceof Object);
}
}
@overiding-Just an annotation

package capgemini;
class Student{
void print(){System.out.println(“Studnet");}}
class Child extends Student{
@Override
void print(){System.out.println("Child");}}
public class scanner_class {
public static void main(String[] args){
// TODO Auto-generated method stub
Child s1=new Child();
s1.print();
}}
Abstract Class

It is a class
It cannot be instantiated ie you cannot create an object of
abstract class
Abstract is a keyword hence can be used with a method
also
A method is abstract if it has no body to it
Abstract class could have both abstract and non-abstract
methods
Class inheriting abstract class must provide body to the
abstract method
Interface

Interface is a keyword
Interface is not a class
Interface only have abstract and public methods and
variables are final here
Class implements an interface
Interface helps to achieve multiple inheritance in Java
Interface cannot be instantiated
Interface achieves 100% abstraction
Interface tells you what to do, and not how to do
Exception handling

Try
Catch
Multiple catch
Finally
Throw
Throws
Try

With try it is mandatory to write catch() or finally{}


Try is a block where we write code
Try and catch:
try
{
System.out.println("one");
System.out.println("two");
System.out.println("three");
int a3=10/0;
System.out.println("five1");
}
catch(Exception ex)
{
//System.out.println(ex);
System.out.println("five2");
}
In multiple catch(), we write specific exception first and then generic one in the end
try
{
System.out.println("one");
System.out.println("two");
System.out.println("three");
int a3[]= {1,2};
a3[10]=100;
System.out.println("five1");
}
catch(ArithmeticException ex)
{
System.out.println(ex);
System.out.println("Specific Exception");
}
catch(Exception ex)
{
System.out.println(ex);
System.out.println("Generic Exception");
}
finally

Finally is block which would always get executed even if


there is an exception or not.
finally
{
System.out.println("I will always get executed");
}
Throw vs throws

Throw is a keyword which is used to create our own


exception
Throws keyword is declare that this method can throw an
exception
Exception hierarchy
Exception types

Checked exception: Compile time. I/O, sqlexception.


Unchecked exception: Runtime . Eg: arithmetic
exception, arrayoutofboundsexception.
Throw vs throws

Throw is a keyword which is used to create our own


exception
Throws keyword is declare that this method can throw an
exception
RegeX

package capgemini;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class scanner_class {


public static void main(String[] args){
// TODO Auto-generated method stub
Pattern p = Pattern.compile("b*a");
Matcher m = p.matcher("bbbbba");
boolean b = m.matches();
System.out.println(b);
System.out.println(Pattern.matches(".e","he"));
System.out.println(Pattern.matches(".s","as"));
System.out.println(Pattern.matches(".s","As"));
}
}
Variable arguments

package capgemini;
public class solve
{
static void add(char b,int... a)
{
int sum = 0;
for (int num : a)
{
sum = sum + num;
}
System.out.println(sum);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
add('A');
add('B',1, 2);
}
}
Arrays Class

package capgemini;
import java.util.Arrays;
public class vararr {

public static void main(String[] args) {


// TODO Auto-generated method stub
int arr[]= {20,13,14,16};
int arrr[]={13,14,16,20};
System.out.println(Arrays.binarySearch(arr, 16));
Arrays.sort(arr);
for(int num:arr)
{
System.out.print(num+" ");
}
System.out.println(Arrays.equals(arr,arrr));

}
Collection framework

Collection is a part of java.util.


Collection framework=Interface+classes
Collection=interface
Collections=classes
Collection framework
ArrayList

package capgemini;

import java.util.*;

public class litstseg {

public static void main(String[] args) {


// TODO Auto-generated method stub
List<Integer> num=new ArrayList<Integer>();
num.add(10);
num.add(20);
num.add(30);
num.add(40);
System.out.println(num.get(0));
System.out.println(num);

}
Array list:
package capgemini;
import java.util.*;
class student{
int rollno;
String name;}
public class studentinfo {
public static void main(String[] args) {
student s1=new student();
s1.rollno=1;s1.name="A";
student s2=new student();
s2.rollno=2;s2.name="B";
student s3=new student();
s3.rollno=3;s3.name="C";
List<student> num=new ArrayList<student>();
num.add(s1);num.add(s2);num.add(s3);
for(student i:num)
System.out.println(i.rollno+" "+i.name);
}
}
Set and Map

Set is unordered and hence iterator is used to know index.


Map is unordered.
Set eg:
package capgemini;
import java.util.*t;
public class seteg {
public static void main(String[] args) {
Set<Integer> num=new HashSet<Integer>();
num.add(10);num.add(20);num.add(30);num.add(40);System.out.println(num);
Set<Integer> nums=new HashSet<Integer>();
nums.add(100);nums.add(200);nums.add(30);nums.add(40);System.out.println(nums);
Set<Integer> union=new HashSet<Integer>(num);
union.addAll(nums);System.out.println(union);
Set<Integer> intersection=new HashSet<Integer>(num);
intersection.retainAll(nums);System.out.println(intersection);
Set<Integer> difference=new HashSet<Integer>(num);
difference.removeAll(nums);
System.out.println(difference);
Iterator<Integer> it=union.iterator();
while(it.hasNext()){
System.out.println(it.next()+" ");
}}
}
Map eg:
package capgemini;
import java.util.*;
public class mapkeyvalue {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(10,"A");
map.put(20,"B");
System.out.println(map);
System.out.println(map.get(10));
map.put(20,"C");
System.out.println(map);
map.remove(20);
System.out.println(map);
map.put(20,"B");
for(Map.Entry<Integer, String>s:map.entrySet()){
System.out.println(s.getKey()+":"+s.getValue());
}
}
}
Collections eg:
package capgemini;
import java.util.*;
public class collectionseg {

public static void main(String[] args) {


// TODO Auto-generated method stub
List<Integer> num=new ArrayList<Integer>();
num.add(10);
num.add(20);
num.add(30);
num.add(40);
Collections.addAll(num,50);
System.out.println(num);
System.out.println(Collections.max(num));
Collections.sort(num,Collections.reverseOrder());
System.out.println(num);
}

}
I/O Stream
I/O Stream Types
Buffered Stream(Reader)

package capgemini;
import java.io.*;
public class readfile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("C:\\Users\\Comp\\Desktop\\test1.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null)
{
System.out.println(st);
}
br.close();
}
}
Buffered Stream(Writer)

package capgemini;
import java.io.*;
public class writefile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("C:\\Users\\Comp\\Desktop\\test1.txt");
BufferedWriter wr=new BufferedWriter(new FileWriter(file));
wr.write("Hello Ketaki");
wr.close();
}
}
File handling
Junit/Testng

Junit is a java unit testing framework.


Testng-ng strand for next generation
Junit/Testng

Crete java project and click on properties.


Go to java build path and then libraries.
Then add libraries and select Junit.
Apply close.
Donot add main class in this.
Junit/Testng

package testcases;
import org.junit.Test;
public class MobileTest {
@Test
public void test1()
{
System.out.println("Test1");
}
@Test
public void test2()
{
System.out.println("Test2");
}
}
Map eg:
package testcases;

import org.junit.Test;

public class MobileTest {

@Test
public void test1()
{
System.out.println("Test1");
}

@Test
public void test2()
{
int i=10/0;
}
}
Map eg:
package testcases;
import org.junit.Assert;
import org.junit.Test;

public class MobileTest {

@Test
public void test1()
{
System.out.println("Test1");
}

@Test
public void test2()
{
Assert.assertFalse(false);
Assert.assertEquals(0,0);
}
}

You might also like