SlideShare a Scribd company logo
CORE JAVA
Presented by,
Susmitha George, Project Lead, RM
India to IS Testing Team on 11th
June 2025
2
History
• High level programming language
• Developed by a team leaded by James Gosling
on 1991 at SunMicrosystems
• Previously it was called as Oak, renamed to Java
on 1995
• Current owner of Java Language- Oracle
3
Getting Started
The java Development Kit-JDK .
• In order to get started in java
programming, one needs to get a recent
copy of the java JDK. This can be obtained
for free by downloading it from the Oracle
official website, JDK download Windows
• Once you download and install this JDK
you are ready to get started.
4
• Compiler:
A program that translates
program written in a high level
language into the equivalent machine
language
• Java Virtual machine: A S/W which
make java programs machine
independent
5
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Interpreted
• Java Is Secure
• Java Is Portable
6
Eclipse IDE
• https://www.eclipse.org/downloads/
 Step by step procedure to download
https://www.geeksforgeeks.org/techtips/how-to-dow
nload-and-install-eclipse-on-windows
 Steps to follow to create project, package and class
in eclipse
https://www.geeksforgeeks.org/selenium-with-java-
tutorial/
7
A Simple Java Program
public class HelloWorld {
public static void main(String[] args){
System.out.println(“Hello World!”);
}
}
8
Java Program may contain
• Comments
• Package
• Reserved words
• Blocks
• Classes
• Methods
• The main method
9
Naming Conventions
• Package names: lowercaseforallcomponents
• Class and Interface names:
CaptializedWithInternalWordsCaptialized
• Method names:
firstWordLowercaseButInternalWordsCapitali
zed()
• Variable names:
firstWordLowercaseButInternalWordsCaptiali
zed
10
Identifiers
• Identifiers are the names of variables,
methods, classes, packages and
interfaces.
• It cannot start with a digit.
• An identifier cannot be a reserved
word (public, class, static, void,
method,…)
11
Note
• Java is case sensitive.
• File name has to be the same as class name
in file.
12
Identifiers EXAMPLE
public class Test
{
public static void
main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5
identifiers as follows:
• Test: Class Name
• main: Method Name
• String: Predefined Class Name
• args: Variable Name
• a: Variable Name
13
Variables
• Each variable must be declared before
it is used.
• The declaration allocates a location in
memory to hold values of this type.
14
Variable Declarations
• The syntax of a variable declaration is
data-type variable-name;
• Example:
• Assign values:
int total;
long count, sum;
total = 0;
count = 20, sum=50;
unitPrice = 57.25;
double unitPrice;
15
Variable Declarations, cont.
• Declaring and Initializing in One Step
int total=0;
Long count=20, sum=50;
double unitPrice = 57.25;
16
Variable Declaration
Example
public class DeclarationExample {
public static void main (String[] args) {
int weeks = 14;
long numberOfStudents = 120;
double averageFinalGrade = 78.6;
char ch=‘a’;
System.out.println(weeks);
System.out.println(numberOfStudents);
System.out.println(averageFinalGrade);
System.out.println(ch);
}
}
17
Primitive Data Types
18
Integers
• There are four integer data types, They
differ by the amount of memory used
to store them.
Type Bits Value Range
byte 8 -127 … 128
short 16 -32768 … 32767
int 32 about 9 decimal digits
long 65 about 18 decimal digits
19
Floating Point
• There are two floating point types.
Type Bits Range
(decimal digits)
Precision
(decimal digits)
float 32 38 7
double 64 308 15
20
Characters
• A char value stores a single
character from the Unicode character
set.
• A character set is an ordered list of
characters and symbols.
• ‘A’, ‘B’, ‘C’, … , ‘a’, ‘b’, … ,‘0’, ‘1’, … , ‘$’, …
• The Unicode character set uses 16 bits
(2 bytes) per character.
21
Boolean
• A boolean value represents a
true/false condition.
• The reserved words true and
false are the only valid values for a
boolean type.
• The boolean type uses one bit.
22
Operators
23
Basic Arithmetic Operators
Operator Meaning Type Example
+ Addition Binary total = cost + tax;
- Subtraction Binary cost = total – tax;
* Multiplication Binary tax = cost * rate;
/ Division Binary salePrice = original / 2;
% Modulus Binary remainder = value % 5;
24
Increment and Decrement
Operators
Operator Meaning Example Description
++ preincrement ++var
Increments var by 1 and
evaluates the new value
in var after the
increment.
++ postincrement var++
Evaluates the original
value in var and
increments var by 1.
– – predecrement --var
Decrements var by 1
and evaluates the new
value in var after the
decrement.
– – postdecrement var--
Evaluates the original
value in var and
decrements var by 1.
25
Increment and Decrement
Operators, cont.
int i = 10;
int newNum = 10 * (i++); int newNum = 10 * i;
i = i + 1;
Same effect as
int i = 10;
int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;
Same effect as
26
Comparison Operators
Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
27
Control Statements
28
if Statement
Boolean
Expression
true
Statement(s)
false
(radius >= 0)
true
area = radius * radius * PI;
System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
false
(A) (B)
if (booleanExpression)
{
statement(s);
}
if (radius >= 0)
{
area = radius * radius * PI;
System.out.println("The area"
“ for the circle of radius "
+ "radius is " + area);
}
29
if...else Statement
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
Boolean
Expression
false
true
Statement(s) for the false case
Statement(s) for the true case
30
if...else Statement
Example
if (radius >= 0)
{
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else
{
System.out.println("Negative input");
}
31
Multiple Alternative
if Statements
if (score >= 90.0)
grade = 'A';
else
if (score >= 80.0)
grade = 'B';
else
if (score >= 70.0)
grade = 'C';
else
if (score >= 60.0)
grade = 'D';
else
grade = 'F';
Equivalent
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
32
switch Statements
switch (switch-expression)
{
case value1:
statement(s)1;
break;
case value2:
statement(s)2;
break;
…
case valueN:
statement(s)N;
break;
default:
statement(s)-for-default;
}
The value1, ..., and valueN
must have the same data
type as the value of the
switch-expression.
The switch statement in Java is a
control flow statement that allows a
program to execute different blocks
of code based on the value of a
variable
or expression
33
while Loop
while (loop-continuation-
condition)
{
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100)
{
System.out.println("
Welcome to Java!");
count++;
}
Loop
Continuation
Condition?
true
Statement(s)
(loop body)
false
(count < 100)?
true
System.out.println("Welcome to Java!");
count++;
false
(A) (B)
count = 0;
In Java, a while loop is a control flow statement that repeatedly executes a block of code as long as a
specified condition remains true.
34
do-while Loop
do
{
// Loop body;
Statement(s);
}
while (loop-continuation-
condition);
Loop
Continuation
Condition?
true
Statement(s)
(loop body)
false
35
for Loops
for (initial-action;
loop-continuation-
condition; action-
after-each-iteration)
{
// loop body;
Statement(s);
}
int i;
for (i = 0; i < 100; i++)
{
System.out.println(
"Welcome to Java!");
}
Loop
Continuation
Condition?
true
Statement(s)
(loop body)
false
(A)
Action-After-Each-Iteration
Intial-Action
(i < 100)?
true
System.out.println(
"Welcome to Java");
false
(B)
i++
i = 0
In Java, the for loop is a control flow statement that allows you to repeatedly execute a block of code. It's
particularly useful
when you know in advance how many times you need to iterate.
36
Methods
37
Methods
A method is a collection of statements
that are grouped together to perform
an operation.
public int max(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier return value type method name formal parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
38
Methods
• Modifier is like public, private and protected.
• returnType is the data type of the value the
method returns.
• Some methods perform the desired
operations without returning a value.
• In this case, the returnType is the keyword
void.
39
Methods
• Parameters are Variables which
defined in the method header.
• Method body contains a
collection of statements that
define what the method does.
40
Benefits of Methods
• Write a method once and reuse it
anywhere.
• Information hiding: Hide the
implementation from the user.
• Reduce complexity.
41
Calling a Method
• If the method returns a value
• int larger = max(3, 4);
• If the method returns void, a call to the
method must be a statement.
• System.out.println("Welcome to Java!");
42
Overloading Methods
method with the same name but
different parameters, This is referred
to as method overloading.
43
Overloading Methods,
Cont.
• The Java compiler determines which
method is used based on the method
signature.
44
public class TestMethodOverloading {
/** Main method */
public static void main(String[] args) {
// Invoke the max method with int parameters
System.out.println("The maximum between 3 and 4 is "+ max(3, 4));
// Invoke the max method with the double parameters
System.out.println("The maximum between 3.0 and 5.4 is"+ max(3.0,5.4));
}
/** Return the max between two int values */
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
/** Find the max between two double values */
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
45
Scope of Local Variables
• A local variable: a variable defined inside
a method.
• Scope: the part of the program where
the variable can be referenced.
• The scope of a local variable starts from
its declaration and continues to the end
of the block that contains the variable. A
local variable must be declared before it
can be used.
46
Strings
• Strings are objects that are treated by
the compiler in special ways:
• Can be created directly using “xxxx”
• Can be concatenated using +
String myName = “John Jones”;
String hello;
hello = “Hello World”;
hello = hello + “!!!!”;
int year = 2008;
String s = “See you in China in “ + year;
47
Arrays
48
Arrays
• Array is used to store a collection of
data of the same type.
• Instead of declaring individual
variables, such as number0, number1, ...,
and number99.
• You declare one array variable such as
numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent
individual variables.
49
Arrays
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
double[] myList = new double[10];
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array reference
variable
Array element at
index 5
50
Arrays
• Declaring Array
• dataType [] arrayRefVar;
• Example:
• int[] arrayName;
• Creating Arrays
− arrayRefVar = new dataType[arraySize];
• Example:
− arrayName = new int[5];
51
Arrays
• When we need to access the array we
can do so directly as in:
for (int i=0; i<5; i++)
{
System.out.println( arrayName[i] );
} // end for
52
Example
double[] myList = new double[10];
for (int i = 1; i < myList.length; i++)
{
myList[i]=i;
}
for (int i = 1; i < myList.length; i++)
{
System.out.println(i);
}
53
Array Initializers
• Declaring, creating, initializing in one step:
double [] myList = {1.9, 2.9, 3.4, 3.5};
• This shorthand syntax must be in one
statement and it’s equivalent to the
following statements:
double [] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
54
Objects and Classes
55
Objects
data field 1
method n
data field m
method 1
(A) A generic object
...
...
State
(Properties)
Behavior
radius = 5
findArea()
Data field, State
Properties
Method,
Behavior
(B) An example of circle object
•An object has both a state and
behavior.
•The state defines the object, and the
behavior defines what the object
does.
56
Classes
• Classes are constructs that define
objects of the same type.
• A Java class uses variables to define
data fields and methods to define
behaviors.
• Additionally, a class provides a special
type of methods, known as
constructors, which are invoked to
construct objects from the class.
57
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double findArea() {
return radius * radius * 3.14159;
}
}
Data field
Method
Constructors
58
Constructors
Circle()
{
}
Circle(double newRadius)
{
radius = newRadius;
}
Constructors are a special kind of
methods that are invoked to
construct objects.
59
Constructors, cont.
•Constructor name is the same as the
class name.
•Constructors do not have a return type
—not even void.
•Constructors are differentiated by the
number and types of their arguments.
• An example of overloading
•If you don’t define a constructor, a
default one will be created.
60
Constructors, cont.
•A constructor with no parameters is
referred to as a no-arg constructor.
•Constructors are invoked using the
new operator when an object is
created.
• Constructors play the role of
initializing objects.
61
Example
public class Circle
{
public static final double PI = 3.14159; // A constant
public double r;// instance field holds circle’s radius
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// Constructor to use if no arguments
public Circle() { r = 1.0; }
// The instance methods: compute values based on radius
public double circumference() { return 2 * PI * r; }
public double area() { return PI * r*r; }
}
62
Declaring Object Reference
Variables
To reference an object, assign the
object to a reference variable.
To declare a reference variable, use
the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
63
Creating Objects Using
Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
64
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Example:
Circle myCircle = new Circle();
65
Accessing Objects
• Referencing the object’s data:
objectRefVar.data
myCircle.radius
• Invoking the object’s method:
objectRefVar.methodName(arguments)
myCircle.findArea()
66
Visibility Modifiers and
Accessor/Mutator Methods
• By default, the class, variable, or
method can be accessed by any class
in the same package.
• public: The class, data, or method is
visible to any class in any package.
• private: The data or methods can be
accessed only by the declaring class.
The get and set methods are used to read
and modify private properties.
67
Why Data Fields Should Be
private?
• To protect data.
• To make class easy to maintain.
68
Example
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn, int year, int
month, int
day) {
id = ssn;
birthDate = new BirthDate(year,
month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int
newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int
newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is
changed!
}
}
69
Instance
Variables, and Methods
• Instance variables belong to a specific
instance.
• Instance methods are invoked by an
instance of the class.
70
Scope of Variables
• The scope of instance and class
variables is the entire class. They can be
declared anywhere inside a class.
• The scope of a local variable starts from
its declaration and continues to the end
of the block that contains the variable. A
local variable must be initialized
explicitly before it can be used.
71
The this Keyword
• Use this to refer to the object that
invokes the instance method.
• Use this to refer to an instance data
field.
• Use this to invoke an overloaded
constructor of the same class.
72
Example
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public Circle() {
this(1.0);
}
public double findArea() {
return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted
this must be explicitly used to reference the data
field radius of the object being constructed
this is used to invoke another constructor
73
Questions

More Related Content

Similar to Java basics-includes java classes, methods ,OOPs concepts (20)

PPTX
JAVA programming language made easy.pptx
Sunila31
 
PPT
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPT
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
PPT
Programming with Java - Essentials to program
leaderHilali1
 
PPT
Java Concepts with object oriented programming
KalpeshM7
 
PPT
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
PPT
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
PPT
Introduction to java programming with Fundamentals
rajipe1
 
PPT
Presentation on programming language on java.ppt
HimambashaShaik
 
PPTX
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 
PPTX
Java Programming
RubaNagarajan
 
PPSX
DITEC - Programming with Java
Rasan Samarasinghe
 
PPTX
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
PDF
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
PPT
Basic elements of java
Ahmad Idrees
 
PDF
Java Basics.pdf
EdFeranil
 
PPTX
Learning core java
Abhay Bharti
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
PPTX
Java fundamentals
HCMUTE
 
JAVA programming language made easy.pptx
Sunila31
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
Core java complete ppt(note)
arvind pandey
 
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
Programming with Java - Essentials to program
leaderHilali1
 
Java Concepts with object oriented programming
KalpeshM7
 
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
Introduction to java programming with Fundamentals
rajipe1
 
Presentation on programming language on java.ppt
HimambashaShaik
 
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 
Java Programming
RubaNagarajan
 
DITEC - Programming with Java
Rasan Samarasinghe
 
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
RahulKumar342376
 
Basic elements of java
Ahmad Idrees
 
Java Basics.pdf
EdFeranil
 
Learning core java
Abhay Bharti
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Java fundamentals
HCMUTE
 

Recently uploaded (20)

PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Ad

Java basics-includes java classes, methods ,OOPs concepts

  • 1. CORE JAVA Presented by, Susmitha George, Project Lead, RM India to IS Testing Team on 11th June 2025
  • 2. 2 History • High level programming language • Developed by a team leaded by James Gosling on 1991 at SunMicrosystems • Previously it was called as Oak, renamed to Java on 1995 • Current owner of Java Language- Oracle
  • 3. 3 Getting Started The java Development Kit-JDK . • In order to get started in java programming, one needs to get a recent copy of the java JDK. This can be obtained for free by downloading it from the Oracle official website, JDK download Windows • Once you download and install this JDK you are ready to get started.
  • 4. 4 • Compiler: A program that translates program written in a high level language into the equivalent machine language • Java Virtual machine: A S/W which make java programs machine independent
  • 5. 5 Characteristics of Java • Java Is Simple • Java Is Object-Oriented • Java Is Interpreted • Java Is Secure • Java Is Portable
  • 6. 6 Eclipse IDE • https://www.eclipse.org/downloads/  Step by step procedure to download https://www.geeksforgeeks.org/techtips/how-to-dow nload-and-install-eclipse-on-windows  Steps to follow to create project, package and class in eclipse https://www.geeksforgeeks.org/selenium-with-java- tutorial/
  • 7. 7 A Simple Java Program public class HelloWorld { public static void main(String[] args){ System.out.println(“Hello World!”); } }
  • 8. 8 Java Program may contain • Comments • Package • Reserved words • Blocks • Classes • Methods • The main method
  • 9. 9 Naming Conventions • Package names: lowercaseforallcomponents • Class and Interface names: CaptializedWithInternalWordsCaptialized • Method names: firstWordLowercaseButInternalWordsCapitali zed() • Variable names: firstWordLowercaseButInternalWordsCaptiali zed
  • 10. 10 Identifiers • Identifiers are the names of variables, methods, classes, packages and interfaces. • It cannot start with a digit. • An identifier cannot be a reserved word (public, class, static, void, method,…)
  • 11. 11 Note • Java is case sensitive. • File name has to be the same as class name in file.
  • 12. 12 Identifiers EXAMPLE public class Test { public static void main(String[] args) { int a = 20; } } In the above Java code, we have 5 identifiers as follows: • Test: Class Name • main: Method Name • String: Predefined Class Name • args: Variable Name • a: Variable Name
  • 13. 13 Variables • Each variable must be declared before it is used. • The declaration allocates a location in memory to hold values of this type.
  • 14. 14 Variable Declarations • The syntax of a variable declaration is data-type variable-name; • Example: • Assign values: int total; long count, sum; total = 0; count = 20, sum=50; unitPrice = 57.25; double unitPrice;
  • 15. 15 Variable Declarations, cont. • Declaring and Initializing in One Step int total=0; Long count=20, sum=50; double unitPrice = 57.25;
  • 16. 16 Variable Declaration Example public class DeclarationExample { public static void main (String[] args) { int weeks = 14; long numberOfStudents = 120; double averageFinalGrade = 78.6; char ch=‘a’; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); System.out.println(ch); } }
  • 18. 18 Integers • There are four integer data types, They differ by the amount of memory used to store them. Type Bits Value Range byte 8 -127 … 128 short 16 -32768 … 32767 int 32 about 9 decimal digits long 65 about 18 decimal digits
  • 19. 19 Floating Point • There are two floating point types. Type Bits Range (decimal digits) Precision (decimal digits) float 32 38 7 double 64 308 15
  • 20. 20 Characters • A char value stores a single character from the Unicode character set. • A character set is an ordered list of characters and symbols. • ‘A’, ‘B’, ‘C’, … , ‘a’, ‘b’, … ,‘0’, ‘1’, … , ‘$’, … • The Unicode character set uses 16 bits (2 bytes) per character.
  • 21. 21 Boolean • A boolean value represents a true/false condition. • The reserved words true and false are the only valid values for a boolean type. • The boolean type uses one bit.
  • 23. 23 Basic Arithmetic Operators Operator Meaning Type Example + Addition Binary total = cost + tax; - Subtraction Binary cost = total – tax; * Multiplication Binary tax = cost * rate; / Division Binary salePrice = original / 2; % Modulus Binary remainder = value % 5;
  • 24. 24 Increment and Decrement Operators Operator Meaning Example Description ++ preincrement ++var Increments var by 1 and evaluates the new value in var after the increment. ++ postincrement var++ Evaluates the original value in var and increments var by 1. – – predecrement --var Decrements var by 1 and evaluates the new value in var after the decrement. – – postdecrement var-- Evaluates the original value in var and decrements var by 1.
  • 25. 25 Increment and Decrement Operators, cont. int i = 10; int newNum = 10 * (i++); int newNum = 10 * i; i = i + 1; Same effect as int i = 10; int newNum = 10 * (++i); i = i + 1; int newNum = 10 * i; Same effect as
  • 26. 26 Comparison Operators Operator Meaning < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to
  • 28. 28 if Statement Boolean Expression true Statement(s) false (radius >= 0) true area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); false (A) (B) if (booleanExpression) { statement(s); } if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" “ for the circle of radius " + "radius is " + area); }
  • 30. 30 if...else Statement Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); }
  • 31. 31 Multiple Alternative if Statements if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
  • 32. 32 switch Statements switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The value1, ..., and valueN must have the same data type as the value of the switch-expression. The switch statement in Java is a control flow statement that allows a program to execute different blocks of code based on the value of a variable or expression
  • 33. 33 while Loop while (loop-continuation- condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { System.out.println(" Welcome to Java!"); count++; } Loop Continuation Condition? true Statement(s) (loop body) false (count < 100)? true System.out.println("Welcome to Java!"); count++; false (A) (B) count = 0; In Java, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition remains true.
  • 34. 34 do-while Loop do { // Loop body; Statement(s); } while (loop-continuation- condition); Loop Continuation Condition? true Statement(s) (loop body) false
  • 35. 35 for Loops for (initial-action; loop-continuation- condition; action- after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); } Loop Continuation Condition? true Statement(s) (loop body) false (A) Action-After-Each-Iteration Intial-Action (i < 100)? true System.out.println( "Welcome to Java"); false (B) i++ i = 0 In Java, the for loop is a control flow statement that allows you to repeatedly execute a block of code. It's particularly useful when you know in advance how many times you need to iterate.
  • 37. 37 Methods A method is a collection of statements that are grouped together to perform an operation. public int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments)
  • 38. 38 Methods • Modifier is like public, private and protected. • returnType is the data type of the value the method returns. • Some methods perform the desired operations without returning a value. • In this case, the returnType is the keyword void.
  • 39. 39 Methods • Parameters are Variables which defined in the method header. • Method body contains a collection of statements that define what the method does.
  • 40. 40 Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding: Hide the implementation from the user. • Reduce complexity.
  • 41. 41 Calling a Method • If the method returns a value • int larger = max(3, 4); • If the method returns void, a call to the method must be a statement. • System.out.println("Welcome to Java!");
  • 42. 42 Overloading Methods method with the same name but different parameters, This is referred to as method overloading.
  • 43. 43 Overloading Methods, Cont. • The Java compiler determines which method is used based on the method signature.
  • 44. 44 public class TestMethodOverloading { /** Main method */ public static void main(String[] args) { // Invoke the max method with int parameters System.out.println("The maximum between 3 and 4 is "+ max(3, 4)); // Invoke the max method with the double parameters System.out.println("The maximum between 3.0 and 5.4 is"+ max(3.0,5.4)); } /** Return the max between two int values */ public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } /** Find the max between two double values */ public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } }
  • 45. 45 Scope of Local Variables • A local variable: a variable defined inside a method. • Scope: the part of the program where the variable can be referenced. • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
  • 46. 46 Strings • Strings are objects that are treated by the compiler in special ways: • Can be created directly using “xxxx” • Can be concatenated using + String myName = “John Jones”; String hello; hello = “Hello World”; hello = hello + “!!!!”; int year = 2008; String s = “See you in China in “ + year;
  • 48. 48 Arrays • Array is used to store a collection of data of the same type. • Instead of declaring individual variables, such as number0, number1, ..., and number99. • You declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
  • 49. 49 Arrays 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 double[] myList = new double[10]; myList reference myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] Element value Array reference variable Array element at index 5
  • 50. 50 Arrays • Declaring Array • dataType [] arrayRefVar; • Example: • int[] arrayName; • Creating Arrays − arrayRefVar = new dataType[arraySize]; • Example: − arrayName = new int[5];
  • 51. 51 Arrays • When we need to access the array we can do so directly as in: for (int i=0; i<5; i++) { System.out.println( arrayName[i] ); } // end for
  • 52. 52 Example double[] myList = new double[10]; for (int i = 1; i < myList.length; i++) { myList[i]=i; } for (int i = 1; i < myList.length; i++) { System.out.println(i); }
  • 53. 53 Array Initializers • Declaring, creating, initializing in one step: double [] myList = {1.9, 2.9, 3.4, 3.5}; • This shorthand syntax must be in one statement and it’s equivalent to the following statements: double [] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 55. 55 Objects data field 1 method n data field m method 1 (A) A generic object ... ... State (Properties) Behavior radius = 5 findArea() Data field, State Properties Method, Behavior (B) An example of circle object •An object has both a state and behavior. •The state defines the object, and the behavior defines what the object does.
  • 56. 56 Classes • Classes are constructs that define objects of the same type. • A Java class uses variables to define data fields and methods to define behaviors. • Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
  • 57. 57 Classes class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double findArea() { return radius * radius * 3.14159; } } Data field Method Constructors
  • 58. 58 Constructors Circle() { } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.
  • 59. 59 Constructors, cont. •Constructor name is the same as the class name. •Constructors do not have a return type —not even void. •Constructors are differentiated by the number and types of their arguments. • An example of overloading •If you don’t define a constructor, a default one will be created.
  • 60. 60 Constructors, cont. •A constructor with no parameters is referred to as a no-arg constructor. •Constructors are invoked using the new operator when an object is created. • Constructors play the role of initializing objects.
  • 61. 61 Example public class Circle { public static final double PI = 3.14159; // A constant public double r;// instance field holds circle’s radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // Constructor to use if no arguments public Circle() { r = 1.0; } // The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } }
  • 62. 62 Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;
  • 63. 63 Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);
  • 64. 64 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle();
  • 65. 65 Accessing Objects • Referencing the object’s data: objectRefVar.data myCircle.radius • Invoking the object’s method: objectRefVar.methodName(arguments) myCircle.findArea()
  • 66. 66 Visibility Modifiers and Accessor/Mutator Methods • By default, the class, variable, or method can be accessed by any class in the same package. • public: The class, data, or method is visible to any class in any package. • private: The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.
  • 67. 67 Why Data Fields Should Be private? • To protect data. • To make class easy to maintain.
  • 68. 68 Example public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }
  • 69. 69 Instance Variables, and Methods • Instance variables belong to a specific instance. • Instance methods are invoked by an instance of the class.
  • 70. 70 Scope of Variables • The scope of instance and class variables is the entire class. They can be declared anywhere inside a class. • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.
  • 71. 71 The this Keyword • Use this to refer to the object that invokes the instance method. • Use this to refer to an instance data field. • Use this to invoke an overloaded constructor of the same class.
  • 72. 72 Example public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public Circle() { this(1.0); } public double findArea() { return this.radius * this.radius * Math.PI; } } Every instance variable belongs to an instance represented by this, which is normally omitted this must be explicitly used to reference the data field radius of the object being constructed this is used to invoke another constructor