Core Java Tutorial
In Core Java Tutorial, we will learn about Java Basics. Core Java Tutorial has below topics and it is very essential fundamentals of the programming language and it is more than enough for writing Selenium script.
Core Java Topics:
1. Java Introduction
2. Classes and Objects
3. Data types and Operators
4. Variables
5. Conditional Statements
6. Loop Statements (or) Iterative Statements
7. Methods
8. String Class methods
9. Constructors
10.Object-Oriented Programming
i. Encapsulation
ii. Abstraction
iii. Inheritance
iv. Polymorphism
11. Interfaces and packages
12. Inner Class
1. Java Introduction
Java is a license free (open source) programming language. It is one of the most used computer programming language using in the current market.
In 1995 java was developed by James Gosling, Patrick, ed Frank and Mike at Sun Micro Systems.
Now Java is owned by Oracle Corporation.
Java is a platform independent language. Write a program and compile a program it will give you bytecode. This bytecode you can run anywhere.
Java Slogan: “Write once, Run Anywhere”(WORA)
Java Editions:
There are 4 editions in java. You can choose whichever you want based on your requirements. Selenium requires basic core java for that we need JSE(Java Standard Edition).
1. JSE ( Java Standard Edition)
2. JEE ( Java Enterprise Edition)
3. JME (Java Micro Edition)
4. JFX ( Java FX)
Note: Core java -> JSE and Adv java –>JSE & JEE
1. Java Standard Edition:
It is used to developing Console application, windows applications, and static web applications.
2. Java Enterprise Edition:
It is used to developing Dynamic Web applications, Services.
3. Java Micro Edition:
It is used to developing Microdevices applications like Communicator, Mobile phones, TV set-top boxes.
4. Java FX:
It is used to developing rich internet applications.
Note: The internet applications which contains more graphics features is known as rich internet applications
Note: To work with Java we require JDK download – install and eclipse download software.
Download and setup java:
To Work on Selenium, you need one programming language. You can write selenium scripts for any programming language. For best practice and most powerful open source programming language is java. So, let’s see how to download and set up java.
Step 1:
First, you need to download and setup java from java official website Click here and you will navigate to the downloads section and click new version or java 8 version to download JDK development kit(JDK).
Just click on “Java SE 8u171/8u172” from the below screen
Step 2:
Once you click on the above-mentioned link then you will navigate to below screen. Click on accept Licence Agreement radio button and then click on download link based on your system environment.
Step 3:
Suppose if your system is windows operating system and you have 32 bit then you need to click on windows X86 and if your system is 64 bit then you need to click on windows x64.
Once it is downloaded a just open setup file and run and complete the installation until finish button.
Step 4:
Once the installation is done you can confirm whether java is installed in your machine.
Open command prompt Windows+R and type cmd and hit Enter then command prompt will be open.
Now in command prompt type “java -version” and hit Enter then you can able to see java version. Please check below screenshot for reference.
Download and setup Eclipse:
Once Java is installed successfully in the system you need to write a java program to run selenium script.
So you need an editor where you can write, store and run java programs. Eclipse is an IDE and its open source tool and it is used to write Java programs.
Download Eclipse:
There are a lot of Eclipse flavors are available to download you can choose any one of the flavors, for example, you can try below flavor named mars.
http://www.eclipse.org/downloads/packages/release/Mars/2
In this package select the first option and select 32 or 64 bit based on your operating system.
Once you click it will get downloaded to your machine and here you no need to install anything as it has application exe file. You can open directly and able to work.
How to start eclipse and what is workspace?
Open the eclipse folder where you have downloaded and double click on eclipse application.exe file like below screenshot.
and it will get launched successfully and it will ask for workspace.
Workspace:
Here you will get the question what is workspace? Workspace is nothing but folder where you want to save your projects.
You can give any name for workspace and click OK then it will get saved. Henceforth whatever projects you do it will get saved in the specified workspace. Later you can create multiple workspaces if you need.
As of now let us create a new workspace named as “AutomationTesting”. Please verify below screenshot.
When you click OK button workspace will be created in the name of “AutomationTesting” and eclipse will be launched and it will display welcome screen for the first time.
You can close the welcome screen as of now because it will give overview and sample details about an eclipse.
Chapter 2 – Introduction of Classes and Objects
Class: In Java, Class is a collection of variables and methods in other words you can say that it’s blueprint/template to work on a certain task by manipulating variables and methods by using an object.
To create a Class, we need a project first so let’s see.
How to create a project in eclipse?
A project is a collection of artifacts like source code and related files to accomplish a task.
As a tester, you need to create a new java project such that you can work and save your scripts under this project.
To create new java project just click on File–>New–>Java Project. Please verify below screenshot.
When you click on java project you will be prompted with below screenshot where you can give project name and you can give project name as per your wish. Project name sample is given as “DemoTour”. Please verify below screenshot
Once a user clicks Finish button you can see the project is created and displayed at project explorer section at left panel and if you expand it will show src and Java Library by default. Please verify below snapshot.
How to create new packages and why you need a package?
Package: Package is a collection of similar classes or nothing but a group.
You can create a package by right-clicking on src –>New–>Package
When you click on “Package” you will be prompted with below screen where you need to enter a package name and click Finish button. Please verify below screenshot.
Once you click Finish button you can see the new package is created under src folder.
Note: Package name should start with small letters.
Java Notation for package:
Package and sub packages should declare in small letters and sub-packages are separated with (. ) Dot Symbol.
Example:
java.lang.*;
java.util.*
How to create a class and what I need to take care when creating a class?
A class is a collection of variables and methods, in other words, you can say that it’s blueprint/template to work on a certain task by manipulating variables and methods by using an object.
You can create a class by right-clicking on package name packagename–>New–>Class.
Verify below screenshot.
Once you click on a class name you will be prompted below popup and enter the class name and select public static void main method and click finish button. Please verify below snapshot.
Once you click Finish button class will be created and displayed under the package. Please verify below snapshot.
Java Notation for class:
When creating a class name make sure each word first letter is capital and no space in between words.
Example:
String
First (In above example)
ChromeDriver
First Java program:
Let’s take a quick look so far what we have done. First, we have downloaded Java and installed and then we have downloaded Eclipse to write Java programs and then we have created a project and then package and then class.
Let’s try to print a message and verify the same in a console (Console section will display output).
Printing a message in Java we have one Statement “System.out.println”.
System.out.println(“Hello ! this is my first java program”);
In the above statement System keyword is Class in the java.lang package.
out is a static member of the System class, and is an instance of java.io.PrintStream.
println is a method of java.io.PrintStream. This method is overloaded to print a message to an output destination, which is typically a console or file.
Got confused? Hold on forget about all the stuff. We will go one by one because it’s too early to talk about all those things. As of now First, try to print a message and verify in a console.
In the above program just add statement System.out.println(“Hello ! this is my first java program”);
and save and right click and select option “Run as” and click “Java application” and verify console.
Please verify below screenshot.
Hurray, ? You have created one java program successfully.
Note: Java is case sensitive language this means you need to take care while writing keywords whether it is uppercase and lowercase letters.
Java notations:
In this section, we will learn when to use small and uppercase letters in the Java programming language.
- Package and sub packages:
When creating packages and sub packages make sure that all have small letters and sub-packages are separated with Dot (.) Symbol
Example:
java.lang.*;
java.util.*
- Classes and Interfaces:
Each word first letter is capital and no space in between words for Classes and Interfaces.
Example:
String
StringBuilder
WebDriver
- Variables
Variables should start with lower case letters and if it contains multiple words then second word onwards first letter is capital.
Example:
empName;
empSal;
- Methods:
Methods name start with lower case.
if it contains multiple words then second word onwards fist letter is capital and It should not have any spaces between words and always ends with ().
Ex:
sendKeys();
compareTo();
Class: In java class stands for a collection of variables and methods which will do some task. Technically speaking we can say that it’s a blueprint to create objects.
Syntax for Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class ClassName { datatype var1; datatype var2; returntype methodName(arg1,arg2) { } } |
Ex: Create a class for employee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class EmpInfo { int empNo; float empSal; String empName; void display() { } } |
Object: An object is an instance of a class.
Syntax:
ClassName objectRef=new ClassName();
Ex:
EmpInfo emp=new EmpInfo();
(or)
new EmpInfo()
Note: here new is an operator which is used to create an object.
Declaration rules to a java program:
- A source file can have only one public class
Ex:
1 2 3 4 5 6 7 8 9 10 11 |
public class Demo1 { } public class Demo2 { } |
here error for Demo2 in above example having 2 public classes.
-
- A source file can have any number of non-pubic classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Demo1 { } class Demo2 { } class Demo3 { } |
- If the source file contains public class then file name must match with the public class name
- If the source file does not contain the public class then no naming restrictions to file name
- A source file can contain any number of main methods
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Demo { public static void main(String[] args) { System.out.println("hello"); } } class Demo1 { public static void main(String[] args) { System.out.println("bye"); } } |
In the above program, it executes first class Demo only
- If a class contains programming statements and does not contain the main method then error while execution
Ex:
1 2 3 4 5 6 7 |
class Demo { System.out.println("hello"); } |
here we will get an error because there is no main method.
- We can create a class without main method and without statements
Ex:
1 2 3 4 5 |
class Demo { } |
Note: As we don’t have the main method we will get an error while executing.
Chapter 3 – Data types
Data type: A data type that determines what type of value a variable can hold.
In java we have two types of Data types:
- Primitive data type
- Reference data type
- Primitive data type:
These are predefined data types and those are named by keywords.
These are 8 primitive data types and those are divided into 4 sub categories.
- Integers
- float
- character
- boolean
- integers : this data type is used to store integers.
in integer data type we have 4 categories.
Data type | Memory size | Range |
byte | 1 byte ( 8 bits ) | -2^8 to 2^8 ( -256 to 256) |
short | 2 bytes ( 16 bits ) | -2^16 to 2^16 |
Int | 4 bytes (32 bits ) | -2^32 to 2^32 |
long | 8 bytes ( 64 bits) | -2^64 to 2^64 |
2.floating: this data type is used to store decimal numbers
Data type | Memory size | Range |
float | 4 bytes ( 32 bits) | -2^32 to 2^32 |
double | 8 bytes ( 64 bits) | -2^64 to 2 ^64 |
- character : this data type is used to store a single character.
- boolean : this data type is used to store boolean values like true / false.
Ex: program demo for data types:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package Admin; public class DataTypesDemo { public static void main(String[] args) { //declaring variables int empNo; float empSalary; char empRole; boolean empStatus; //assinging values to variables empNo=100; empSalary=20000.00f; empRole='A'; empStatus=true; //using the variables System.out.println("Employee name is " + empNo); System.out.println("Employee salary is " + empSalary); System.out.println("Employee role is " + empRole); System.out.println("Employee status is " + empStatus); } } |
- Reference data type:
Ex: Arrays, String, Classes, Interfaces……………..
the data types which we are accessing by object creation are called as Reference data types.
Operators in java:
Operators are using for perform operations on given operands ( values ).
in Java we have 3 types of operators:
- Unary
- Binary
- Ternary
- Unary: These are used to perform operations on a single value.
we have -, ++ and — as unary operator in java.
- – : it is used to assign a negative value for a given value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Ex: int a=10; System.out.println(a); //10 System.out.println(-a); //-10 int a=-10 System.out.println(a); //-10 System.our.println(-a); //10 |
- ++ : it is used to increment by 1 for a given value
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int a=10; System.out.println(a); //10 System.out.println(++a); //11 int b=10; System.out.println(b); //10 System.out.println(b++); //10 System.out.println(b); //11 |
3.– : it is used to decrement by 1 for a given value
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a=10 System.out.println(a);//10 System.out.println(--a); //9 b=10 System.out.println(b); //10 System.out.println(b--); //10 System.out.println(b); 9 |
- Binary operators: These are used to perform operations on a one or more given values
- Arithmetic Operators: These are used to perform mathematical operations on given values.
In java we have below arithmetic operators:
+ – * / %
- Assignment operator (=) : It is used to assign a required to value for a given variable
1 2 3 |
Ex: a =10 |
iii. Relational (or) Conditional operators: These are used to compare two given values.
It returns boolean value
<
>
<=
>=
!=
==
- Logical operators:
&&, ||, !
Condition1 | Condition2 | Condition1 && Condition2 | Condition1 || Condition2 |
TRUE | TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE | TRUE |
FALSE | TRUE | FALSE | TRUE |
FALSE | FALSE | FALSE | FALSE |
- Ternary operators:
These are used for a single condition
Syntax:
<cond>?stmt1:stmt2;
Ex:
1 2 3 4 5 6 7 |
int a=30; int b=20; int c=(a<b)?a:b; System.out.println(c); //10 |
Chapter 4 – Variables
Variable is used to store the data and this data we may change or update anytime when we required.
In java, we have 5 types of variables
- Global Variables
- Non-static (or) Instance variables
- Static (or) Class Variables
- Local Variable
- Block Variables
- Global Variables:
The variables which we declare outside of a class are called as Global Variables;
In java, Global Variables concept is not available.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
int x=10; static int y=20; package Admin; public class VariableDemo { public static void main(String[] args) { } } |
In the above program, we declare x and y variables outside of a class and we will get an error, as java is not supporting global variable concept.
- Non-Static (or) Instance Variables:
The variables which we declare inside the class and outside method without static keyword are
called as Non-Static or Instance variables
Accessing Non-Static variables in methods:
we have two ways:
- By using object Reference
Syntax:
ClassName objectName=new ClassName();
objectName is a variable which has reference to the class
- By using object
Syntax:
new ClassName().VariableName;
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package Admin; public class VariableDemo { int x=10; int y=20; public static void main(String[] args) { //by using object Reference //Syntax: // ClassName objectName=new ClassName(); VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); System.out.println(obj1.x); //10 System.out.println(obj1.y); //20 System.out.println(obj2.x); //10 System.out.println(obj2.y); //20 obj1.x=30; System.out.println(obj1.x); //30 System.out.println(obj2.x); //10 obj2.x=obj1.x; System.out.println(obj2.x);//30 System.out.println(obj1.x - obj2.x); //0 } } |
Ex: Accessing instance variable values in a method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package Admin; public class VariableDemo { int x=10; int y=20; public static void main(String[] args) { //by using object Reference //Syntax: // ClassName objectName=new ClassName(); VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); System.out.println(obj1.x); //10 System.out.println(obj1.y); //20 System.out.println(obj2.x); //10 System.out.println(obj2.y); //20 obj1.x=30; System.out.println(obj1.x); //30 System.out.println(obj2.x); //10 obj2.x=obj1.x; System.out.println(obj2.x);//30 System.out.println(obj1.x - obj2.x); //0 } } |
Note: The default instance integer variable values is 0
Note: The default instance float variable value is 0.0
Note: The default instance boolean variable value is false
Note: The default instance String variable value is null
Ex 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package Admin; public class VariableDemo { int x; float y; boolean z; public static void main(String[] args) { //Accessing by using object Reference VariableDemo obj=new VariableDemo(); System.out.println(obj.x); //0 System.out.println(obj.y); //0.0 System.out.println(obj.z); //false //accesing by using object System.out.println(new VariableDemo().x); //0 System.out.println(new VariableDemo().y); //0.0 System.out.println(new VariableDemo().z); //false } } |
3. Static Variables (or) class variables:
The variables which we declare in a class and outside of a method with a static keyword is called as Static variables or class variables;
Note: We can access static variables in below 4 ways;
1. Directly
2. By using a class name
3. By using object Reference
4. By using object
1. Directly
System.out.println(x);
2. By using a class name
Syntax:
ClassName.Variablename
Ex:
VariableDemo.x;
3. by using object Reference
ClassName obj=new ClassName();
obj.variablename
4. By using object
new ClassName().variableName;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
Ex: package Admin; public class VariableDemo { static int x=10; public static void main(String[] args) { //Directly System.out.println(x); //10 //by using class name System.out.println(VariableDemo.x); //10 //by using object Reference VariableDemo obj=new VariableDemo(); System.out.println(obj.x);//10 //by using object System.out.println(new VariableDemo().x);//10 } } |
Note: If we declare a static variable in one class and wants to access in another class by directly then we will get an error message. we can access these variables by using classname.variable name, or by using object Reference, or by using an object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Ex: package Admin; class Demo1 { static int y=20; } public class VariableDemo { static int x=10; public static void main(String[] args) { System.out.println(y); //error message why because static variable y is defined in Demo1 class and accessing directly in VariableDemo class. } } |
Note: If we use common values for objects use static else use non-static.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package Admin; public class Employee { int empId; String empName; static String companyName; public static void main(String[] args) { Employee.companyName="Test"; //for first new employee Employee emp1=new Employee(); emp1.empId=100; emp1.empName="Azgar"; System.out.println("first employee information"); System.out.println("employee id is : " + emp1.empId); System.out.println("employee name is : " + emp1.empName); System.out.println("employee company name is : " + Employee.companyName); //for second new employee Employee emp2=new Employee(); emp2.empId=101; emp2.empName="Hari"; System.out.println("second employee information"); System.out.println("employee id is : " + emp2.empId); System.out.println("employee name is : " + emp2.empName); System.out.println("employee company name is : " + Employee.companyName); //for third new employee Employee emp3=new Employee(); emp3.empId=102; emp3.empName="sudha"; System.out.println("third employee information"); System.out.println("employee id is : " + emp3.empId); System.out.println("employee name is : " + emp3.empName); System.out.println("employee company name is : " + Employee.companyName); } } |
Note : The default static integer variable values is 0
Note : The default static float variable value is 0.0
Note : The default static boolean variable value is false
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package Admin; public class Employee { static int x; static float y; static boolean z; public static void main(String[] args) { System.out.println(x); //0 System.out.println(y); //0.0 System.out.println(z); //false // } } |
4. Local variables: The variable which declares in a method are called as Local variables We can access local variables by directly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Employee { public static void main(String[] args) { int x; x=10; System.out.println(x); } } |
Note: There is no default value for local variables, means if we do not assign any value and using
then we will get an error message.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Employee { public static void main(String[] args) { int x; System.out.println(x); //error as we are not assigned any value to local variable x } } |
Note: If static and local variables are the same, and accessing the variable directly then it takes local variable value not static variable value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package Admin; public class Employee { static int x=10; public static void main(String[] args) { int x; x=20; System.out.println(x);//20 System.out.println(Employee.x); //10 } } |
Note: It is best to use by using className.variable for static variables.
5. Block variables: The variables which we declare in a block are called as block variables.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package Admin; public class Employee { public static void main(String[] args) { for(int i=0; i<10; i++) { int x=10; //block variable } System.out.println(x); //error message } } |
Chapter 5 – Conditional Statements
Conditional Statements: These are used to execute the statements depends on given conditions.
In java we have below conditional statements:
- if
- if else
- if else if (nested if)
- switch
- If: it executes the statements when the given condition is passed, otherwise, it does not execute the statements.
Syntax:
if(condition)
{
<Statements>;
}
Example 1: Write a java program for the below scenario
Do you know the testing tools course?
if yes then display a message “try for a job”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConditionalStmts { public static void main(String[] args) throws IOException { String status; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Do you know the testing tools course?"); status=reader.readLine(); if(status.equals("yes")) { System.out.println("try for a job"); } } } |
- if else – This condition has 2 blocks one is pass block and another one if false block based on a statement it depends which block will execute. In this condition also either only one statement only will execute.
It executes the statements depends on given condition.
If the given condition is passed, then it executes pass block
if the given condition is failed then it executes fail block
Syntax:
if(condition)
{
statements;
}
else
{
statements;
}
Example 2: Write a java program for the below scenario
Do you know the testing tools course?
if yes then display a message “try for a job”
if no then display a message “learn testing tools course”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConditionalStmts { public static void main(String[] args) throws IOException { String status; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Do you know testing tools course?"); status=reader.readLine(); if(status.equals("yes")) { System.out.println("try for a job"); } else { System.out.println("learn testing tools course"); } } } |
3. Nested if: By using this condition one can try multiple conditions. First, it will try in if condition, when if condition not satisfied then it will try else if condition. Like this, we can try multiple conditions using else if.
Syntax:
if(Condition)
{
statements;
}
else if(condition)
{
statements;
}
Example 3: write a java program for the below scenario
do you know testing tools course?
if no then display a message “learn testing tools course”
if yes then find do you know selenium?
if yes then display a message “try for a job”
If no then display a message “learn selenium and try for a job”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConditionalStmts { public static void main(String[] args) throws IOException { String value; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Do you know testing tools course?"); value = reader.readLine(); if(value.equals("no")) { System.out.println("leaarn testing tools course"); } else { if(value.equals("yes")) { System.out.println("Do you know selenium?"); value = reader.readLine(); if(value.equals("yes")) { System.out.println("try for a job"); } else { System.out.println("learn selenium and then try for a job"); } } } } } |
- switch: It is used to executes the statements depend on multiple conditions based on the input which we give it will jump to that particular case and it will execute that specific block.
Program: write a java program for the below scenario “Read a value in run time and display corresponding week name”.
You might get we already try with nested if why we need this approach. if we have one or two multiple conditions we can go else if (nested if) approach. when we have more options( statements) then it will degrade performance as it will go and check every condition.
To overcome this problem and the best approach is Switch case.
Let’s see examples with both approaches and you may get the idea!
Without a Switch Case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConditionalStmts { public static void main(String[] args) throws IOException { String value; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any number"); value = reader.readLine(); int number=Integer.parseInt(value); if(number==1) { System.out.println("Sunday"); } if(number==2) { System.out.println("Monday"); } if(number==3) { System.out.println("Tues day"); } if(number==4) { System.out.println("Wedness day"); } if(number==5) { System.out.println("Thurs day"); } if(number==6) { System.out.println("Fri day"); } if(number==7) { System.out.println("Satur day"); } if(number < 1 || number > 7) { System.out.println("invalid number is entered"); } } } |
Note: In the above program, we have more number of statements and performance is also slow, to overcome this issue we are using a switch statement.
Let’s see with the Switch case:
Syntax:
switch(variable to test)
{
case <value>
<statements>;
break;
case <value>
<statements>
break;
default:
<statements>
break;
}
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConditionalStmts { public static void main(String[] args) throws IOException { String value; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any number"); value = reader.readLine(); int number=Integer.parseInt(value); switch(number) { case 1: System.out.println("sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tues day"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("invalid entry"); } } } |
Chapter 7 – Methods
I this section we are going to discuss about methods which is so important in any programming language as it reduces the human effort not to write code again and again.
Method or Function is nothing but A group of statements into a single unit is called as a method.
Methods are used for program reusability.
We have two types of methods:
- Predefined (or) system defined methods
- User-defined methods.
User-defined methods: The methods which are defined by a programmer to achieve some task are called as User defined methods. We will concentrate on user-defined methods because we will work on this.
When defining methods remember 2 things. One with a return type or without return type.
Return type methods will give some output and this output we can store or handle somewhere in the further process.
Non-return type (void) will not return anything simply it will execute steps provided inside the method like just printing name.
Syntax:
returntype/void methodName(arg1,arg2,arg3,,,,,,,,,,,)
{
<statements>;
<statements>;
[return];
}
Ex: Non-Return Type
void demo()
{
System.out.println(“hello”);
System.out.println(“Please come here and learn selenium”);
}
Ex: Return Type
Public int addition(int a , int b)
{
Int c=a+b;
return c;
}
Note : We can declare methods in two ways:
- Instance (or) non static method declaration
- Class (or) static method declaration
- Instance Method (non-static) declaration:
A method that is defined in a class and without static keyword is known as an Instance method
or non static method declaration.
There are two ways to access the instance method:
- By using object
–>Use this method if it is required only one time.
- By using Object Reference
–>Use this method, if it required more than one time
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class MethodsDemo { void demo() { System.out.println("hello"); System.out.println("please come here and learn selenium"); } public static void main(String[] args) { // by using object new MethodsDemo().demo(); // by using object Reference MethodsDemo obj=new MethodsDemo(); obj.demo(); } } |
2. class methods declaration:
A method which is declared in a class and with a static keyword is called a class method
static: It is called as a modifier because it will modify the behavior of the variable, method, block and class . By using static keyword we can create class variables, class methods…………………
Note: we can access class methods in the below ways:
1. By Directly
2. By Class Name
3. By object
4. By object Reference
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class MethodsDemo { static int x=10; static void demo() { System.out.println("hello"); System.out.println("please come here and learn selenium"); } public static void main(String[] args) { //directly demo(); //by class name MethodsDemo.demo(); //by using object new MethodsDemo().demo(); //by using object Reference MethodsDemo obj=new MethodsDemo(); obj.demo(); } } |
Ex: Write a method for finding cube for a given number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Cube { int cubeVal(int a) { int b=a * a * a; return b; } public static void main(String[] args) { int x=new Cube().cubeVal(10); System.out.println(x); } } |
Check below snapshot and know the terminologies:
Note: In Java, we can declare methods in 4 categories:
- Methods with arguments and with a return value
- Methods with arguments and without a return value
- Methods without arguments and with a return value
- Methods without arguments and without a return value
Ex 1: Methods with arguments and with a return value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //find the cube value for a given number - with arguments and with return value public class Methods { int cubeVal(int a) { int b; b=a * a * a; return b; } public static void main(String[] args) throws IOException { String val; int x; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any number"); val=reader.readLine(); x=Integer.parseInt(val); x=new Methods().cubeVal(x); System.out.println("cube value for a given number is : " + x); } } |
2. Methods with arguments and without a return value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package Admin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //find the cube value for a given number - with arguments and without return value public class Methods { void cubeVal(int a) { int b; b=a * a * a; System.out.println("cube value for a given number is : " + b); } public static void main(String[] args) throws IOException { String val; int x; BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any number"); val=reader.readLine(); x=Integer.parseInt(val); new Methods().cubeVal(x); } } |
3. Method without arguments and with a return value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //find the cube value for a given number - without arguments and with return value public class Methods { int cubeVal() throws IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any number"); String val=reader.readLine(); int x=Integer.parseInt(val); int b=x* x* x; return b; } public static void main(String[] args) throws IOException { int x=new Methods().cubeVal(); System.out.println("cube value for a given number : " + x); } } |
4. Method without arguments and without a return value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //find the cube value for a given number - without arguments and with return value public class Methods { void cubeVal() throws IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any number"); String val=reader.readLine(); int x=Integer.parseInt(val); int b=x* x* x; System.out.println("cube value for a given number : " + b); } public static void main(String[] args) throws IOException { new Methods().cubeVal(); } } |
Method Overloading: If two or more methods with the same name and different arguments are called as method overloading.
we can declare method overloading in below 3 ways:
1. Different in a number of arguments
1 2 3 |
void add() void add(int x, int y) void add(int x) |
2. Different in data type
1 2 |
void add(int x, int y) void add(float x, float y) |
3. Different in order of arguments
1 2 |
void add(int x, float y) void add(float x, int y) |
Ex: For method overloading
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
public class MethodOverloading { void add() { int x=10; int y=20; System.out.println(x+y); } void add(int x,int y) { System.out.println(x+y); } void add(float x, float y) { System.out.println(x+y); } void add(int x, float y) { System.out.println(x); System.out.println(y); } void add(float x,int y) { System.out.println(x); System.out.println(y); } public static void main(String[] args) { new MethodOverloading().add(); new MethodOverloading().add(10, 20); new MethodOverloading().add(10.0f,20.0f); new MethodOverloading().add(10,20.0f); new MethodOverloading().add(20.f,10); } } |
Method overriding: with two or more methods with the same name and same arguments list
is called Method Overriding.
Ex:
1 2 3 4 5 6 7 8 9 |
void add(int x,int y) { } void add(int x, int y) { } |
Note: we will discuss more concepts on method overriding in the inheritance concept.
Chapter 8 – String class Methods
Generally, String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
In Java, if you want to handle a sequence of characters then you need to declare as “String”. A string is a class and it has several methods to handle to string type of data.
Simply in 2 ways, we can create a string object.
1)Literally
2)Keyword
In Literally we can declare as String s=”My Name Is Khan”;
In Keyword we can declare as String s=new String(“My Name Is Khan”);
In general, Strings are immutable (Not able to update) once we declare we cannot manipulate.
Whereas in Keyword you can change because it’s an Object.
Note: We can access string methods, for a variable with data type as String
Ex:
String text;
text.<displays all string methods>
Let’s see most used string methods below,
- length(): This method is used to find a number of characters for a given string
Ex:
1 2 3 |
String str="my name is Khan" System.out.println(str.length()); //15 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package unittest; public class Test2 { public static void main(String[] args) { String str="my name is Khan"; System.out.println(str.length()); } } |
Very clear explanation…. Very helpful for the beginner’s… Good work.
Thank you..
There is certainly a great deal to learn about this subject.
I love all the points you have made.
I was recommended this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my trouble. You are incredible! Thanks!|