Java Step by Step Tutorial for Beginners

Java Step by Step Tutorial for Beginners, Java Environment Setup, Java Programming Fundamentals, and Java Object oriented programming.

java tutorial

Core Java Step by Step Tutorial

Java Tutorial for Beginners

1. Intruduction to Java

2. Java Environment Setup

3. Java Syntax and Program Structure

4. Comments in Java

5. Java Modifiers

6. Java Data Types

7. Java Variables

8. Operators in Java

9. Java Control Flow – Decision Making / Conditional Statements

10. Java Control Flow – Loop Statements

11. Java Control Flow – Branching Statements

12. String handling java

13. Java Array and ArrayList

14. Java IO – Getting User Input

15. Java IO – File Handling

16. Java User Defined Methods

17. Java Built-in Methods

18. Java Exception Handling

19. Java Object Oriented Programming

20. Java Inheritance

21. Java Polymorphism

22. Java Abstraction

23. Java Interface

24. Java Encapsulation


1. Introduction to Java 

i. What is Java?

> Java is a general-purpose programming language, to be used for writing software in the widest variety of application domains.

> Java Programming language was developed by James Gosling with his team (Java Team, also known as Green Team) in 1995 for Sun Microsystems, later Java was acquired by Oracle in 2010.

> Java is a Programming Language and a Platform, Java is used as programming to develop Software Applications, and It also used as a Software Platform to run Java applications.

> Java is an Object Oriented Programming languages, In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

> Java is a simple programming language, It is easy to learn, and its syntax is simple, clean and easy to understand.

> Java is a platform independent language, Write once, run anywhere (WORA), was a slogan created by Sun Microsystems to illustrate the cross-platform benefits of the Java language.

> There are four platforms of the Java programming language, Java Standard Edition (Java SE) / Core Java, Java Enterprise Edition (Java EE) / Advanced Java, Java Micro Edition (Java ME), and JavaFX.

> Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network.

> Java Development Environment is required to write & execute Java programs. Download your operating system compatible Java (JDK) software, set Java Environment variable path, Download & extract Eclipse IDE, and write Java programs using Eclipse IDE Editor.

> Java program hierarchy is, Java Project > Java Package > Java Class / Interface. We write Java code in the Java Class.

ii. Uses of Java

Java is used to develop Desktop Applications, Web Applications, Enterprise Applications (ex: Banking, Insurance, ERP etc…), Mobile Applications, Embedded Systems, Smart Cards, Games Applications, Scientific Applications Etc…


2. Java Environment Setup

Java Environment is required is to write and execute Java programs.

Three important steps in Software Programming,
i) Write a Program (in an Editor)
ii) Compile the Program
iii) Run the program

A) Steps for writing and executing Java programs using the command-line interface

i) Download Java Software (JDK) and Install
ii) Set Java Environment variable in the OS Environment
iii) Write a Java program in Notepad and save with “.java” extension
iv) Compile the java program file in command prompt and Run…

B) Steps for writing and executing Java programs using Eclipse IDE

i) Download Java Software (JDK) and Install
ii) Set Java Environment variable in the OS Environment
iii) Download Eclipse IDE and Extract
iv) Write Java programs in Eclipse Editor and Run

Download Java Software (JDK) from either java.com or oracle.com, and install
Note: Download Java Software based on your Operating Environment
Ex: Windows 10 64 bit OS

After Java Software installation we get “Java” Folder in C:/Program Files/
Set Java Environment Variable…

Copy jdk bin directory path from your computer,

Navigation to set Java Environment Variable:

> Select MyComuter and Right Click

> Properties
> Click “Advanced System Settings”
> Click “Environment Variables”
> Select “Path” Variable in System Variables pane
> > Click “Edit”
> Paste Jdk bin directory path
> Clcik “OK”
> Clcik “OK”
————————–
Step 1: Write a Program in Notepad

public class Sample{
public static void main (String [] args){
System.out.println(“Hello Java”);
}
}

save as .java file with class name
—————————
Step 2: Compile the Program

> Launch the Command prompt
> Change to Java program file directory
> Type javac File Name/sample.java

* Then it will create Java class file (.class)
———————————-
Step 3: Run the program

> Launch the Command prompt
> Change to Java program file directory
> Type java and Class file name without extension

* It will display the output on the Console

Eclipse IDE:
——————-
> Eclipse IDE is an Open Source software

> It is a platform to write & execute Software programs like Java, C, C++, Perl, Python, Ruby, PHP etc…

> It provides Editor for writing Programs, Syntax Guidance, Context Help and Auto compilation etc…

Navigation for writing and executing Java programs in Eclipse IDE

> Launch Eclipse IDE
> Create a Java project
> Create Java Package under the Java Project
> Create Java Class under the Java Package
> Write Java code in the Java Class…

Java Program Example:

public class Sample {

public static void main(String[] args) {
int a=10, b=20;
System.out.println(“Addition of a, b is: “+ (a+b));

if (a>b){
System.out.println(“A is a Big Number”);
}
else {
System.out.println(“B is a Big Number”);
}
}
}


3. Java Syntax and Program Structure

1) Java Program Structure
ii) Java Program Example

1. Java Program Structure

i. Documentation Section

It includes comments to tell the program’s purpose, it improves the readability of the Program

ii. Package Statement

package abcd;

iii. Import statement/s

We import predefined and user defined libraries using “import” keyword

Example:

import java.util.Scanner;
java – Project
util – Package
Scanner – Class

import java.util.*; // Importing all classes from a package

iv. Class Definition

Ex:
public class Sample{

}

v. Interface Section

In this section, we create/declare Static variables, and create/declare Methods

vi. main() Method

Java program execution starts from main() method, which is mandatory in every Java program.

public static void main (String [] args){
//Code
}

public – Access Modifier
static – Non Access Modifier (use main method without invoking an object)
void – Returns Nothing
main – Predefined Identifier(Method name)

(String[] args) -? – NagaLaxmi
——————————————-
//Within Main method

main method{
//Main Program
Creating Object/s
ClassName objectName = new ClassName();

Comments
Declarations….(Variable with Data Types, Constants/Final Variables)
Normal Statements
int a;//Declaration
a=100;//Initialization
int b=a;//Reading
System.out.println(10+20); //Print Statement
final int x=100;

if (){ //Condition Code Block
.
}

for (){ //Loop Code Block
.
}

}
—————————-
Sections of Java Program

1. Documentation Section – Optional

2. Package Statement – Mandatory

3. Import Statement/s – Depends on our program requirement

4. Class Definition { //Mandatory

5. Interface Section //Depends on our program requirement

6. main method(){
//Main Program contains normal statements, and code blocks
Object Creation //Depends on our program requirement
Declarations/Initialization/Reading – normal statements
Operations/Display statements etc…
Code Blocks
Conditions/Decision-making blocks
Loop Blocks
Constructor Block
Etc…
}
Interface Section //Depends on our program requirement
}

2. Java Program Example

//This program is for explaining Java Syntax and program Structure.

package abcd;

import java.util.Scanner;

public class Sample {
//Create a Non static method with arguments and return a value
public int add(int a, int b) {
int result;
result=a+b;
return result;
}
//Create a Non static method without arguments and returns Nothing
public void sub() {
int x=100;
int y=50;
System.out.println(x-y);
}
//Create a Static method with arguments and return a value
public static int multiply(int num1, int num2) {
int result= num1*num2;
return result;
}
//Create a Static method without arguments and returns Nothing
public static void comparision() {
int x=100, y=50;

if (x>y) {
System.out.println(“X is Big Number”);
}
else {
System.out.println(“Y is Big Number”);
}
}

public static void main (String [] args){
Scanner scan = new Scanner (System.in);

System.out.println(“Enter Your Name”);
String myName = scan.nextLine();
System.out.println(“My Name is: ” + myName);
int a; //Variable Declaration
a=100;
int b=200; // Variable Declaration with Initialization
char x=’Y’;
String myCountry = “India”;
int c, d, e; //Declaring multiple variables
int f=20, g=40, h=60; //Declaring multiple variables with Initialization
final int price=100;

if (a>b)
{
System.out.println(“A is Big Number”);
}
else
{
System.out.println(“B is Big Number”);
}
System.out.println(“”);

for (int i=1; i<=10; i++)
{ // Print 1 to 10 Numbers
System.out.println(i);
}
System.out.println(“”);

int i=1;
while (i<=5) {
System.out.println(i);
i++;
}
System.out.println(“My Output”);
//Print 1 to 5 Numbers except 4
for (int j=1; j<=5; j++) {
if (j!=4) {
System.out.println(j);
}
}

//Create Object and call non static methods
Sample obj = new Sample();
int val = obj.add(100, 200);
System.out.println(val);//300

System.out.println(obj.add(10, 20));//30

obj.sub();//50

//Call Static methods

val = multiply(10, 40);
System.out.println(val);//400

comparision();//X is Big Number
}
}


4. Comments, Modifiers, and Data Types in Java

1) Java Comments
2) Java Modifiers
3) Java Data Types

1) Java Comments

Comments are English words used for Code Documentation

Purpose of Comments:
To make the Code Readable
To make the code prevent from Execution

Note: Java Supports single line comments and multiple line comments.

Syntax:

a) Use // for Single line Syntax

b) Use /*……………….

…………………………..

…………………………..

……………….*/ for multiple line comments

Any text between /* and */ will be ignored by Java.

Note: It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

Or Eclipse IDE Navigation:

Comment

> Select Statements / Steps
> Source Menu (In Eclipse IDE)
> Add Block Comment

Uncomment
> Select Comment Block
> Source Menu (In Eclipse IDE)
> Remove Block Comment

Example:

public static void main(String[] args) {
// It is a Sample Program
int a, b; //Declaration of Variables
a=10; b=20; // Initialization
System.out.println(a+b);//30

/*if (a > b){
System.out.println(“A is a Big Number”);
}
else {
System.out.println(“B is a Big Number”);
}*/

}
}

Usage of Comments in Test Automation

a) To write Test case Header
b) To write Method header
c) To explain Complex Logic etc…

2) Modifiers in Java

Two Categories of Modifiers in Java
a) Access Modifiers
b) Non -Access Modifiers

a) Access Modifiers

Access Modifiers can be used to define access control for classes, methods, and variables.

i) public

public access modifier is accessible everywhere

Example:

public class Sample{
…..
}

public int a =10;

public int add (Parameters){
method body…
}

ii) private

The private access modifier is accessible only within the class

private int b=200;

iii) default

if we don’t specify any modifier then It is treated as a default, this can be accessed only within the package

Example:

class Sample{
…..
}

iv) protected

The protected modifier is accessible within the package, outside of the package but through Inheritance.

Example:

protected class Sample{
….
}

b) Non -Access Modifiers

i) static

static modifier is used to create classes, methods, and variables.

Example:
static int a=10;
static int add (parameters){
…………..
…………..
}

ii) final

final modifier for finalizing classes, methods, and variables.

Example:

final int x =100;//Correct
final int y;//Incorrect
y=200;

iii) abstract

abstract modifier is used to create abstract classes and abstract methods.

Example:

abstract class Sample{
……..
}
abstract int add(); //abstract method
public int add(){ //concreate method
………..
}

3) Java Data Types

What is Data Type?

> Data Type is a classification of the type of data that a Variable or Constant or Method can hold in computer programming.

> Data types specify the different sizes and values that can be stored in the variable.

Ex: Character, Number, Number with decimal values, Logical data, String, Date, Currency etc…

Note: Java supports explicit declaration of Data Types.
(We need to specify the Data Type before declaring Variables, Constants, and methods…)

Syntax:

a) Variables

Syntax:

dataType variableName;
Or
dataType variableName = value;
Or
dataType variable1Name, variable2Name, variable3Name;
or
dataType variable1Name=value, variable2Name= value, variable3Name=value;

Example:

int a;
a=10;
int b=100;
int c, d, e;
c=30; d=40; e=50;
int f=60, g=70, h=80;

b) Constants

Note: Variables and Constants are for holding the data, Variables may vary, but constants never change

int a;
a=100;//Correct for Variable
.
.
.
.
a=30; //Correct for Variable

final int b;
b=200; //Incorrect
final int c =300;//Correct
.
.
.
c=400; //Incorrect

c) Method with Return Value

public int add (int a, int b, int c){
……………………..
……………………..
……………………..
return…;
}

Two Categories of Data Types in Java
1) Primitive Data Types
2) Non-primitive data Types

1) Primitive Data Types
a) Integer Data Types
i) byte
ii) short
iii) int
iv) long
int
b) Relational Data Types
v) float
vi) double
double
c) Character Data Type
vii) char
char
d) Conditional Data Type
boolean viii) boolean

Primitive Data Types

a) Integer Data Types

i) byte (8 bits)

Minimum value is -128 (-2^7), Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
byte a=10;

ii) short (16 bits)

Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Default value is 0.
short b=1000;

iii) int (32 bits)

Minimum value is – 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
The default value is 0
int c =10000;
int d=12;
int e=1;

iv) long (64 bits)

Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
Default value is 0L
long f =1000000000000000;

b) Relational Data Types (Numbers with Decimal Places)

v) float (32 bits)

float x = 10.23f;

vi) double (64 bits)

double y = 1234.5678765;

c) Character Data Type

vii) character

char z = ‘A’;
char s = ‘1’;
char r = ‘*’;

d) Conditional Data Type

viii) boolean

boolean k = true/false;

2) Non Primitive data types / Reference data types

Non Primitive data types in Java are Objects (String, Array etc…)

Example:

Sample a = new sample();
String x = ‘India”;

123 – Integer Data Type
‘Y’ -Character
123.34 – float/double
“Selenium Testing” – String
“abc123*&^” – String
“123” – String
1 – Integer
‘1’ – Character

How to handle Date type data?

Converting Data / Data Conversion

Converting data from one type to another…

Assigning Values to Variables
1) Initialization – No Data Conversation
2) Reading – (Data Conversation is required)
Read Input (using Input Devices)
Read data from files
Read data from Application objects

> When Data Conversion is required?

Whenever we read data then the computer program considers that data as String type data, we need to convert the data in order to perform mathematical operations, Note: Generally we convert String type to Integer Type/ Relational type, we can’t convert Alpha bytes to numbers, etc…

Java General Topic:

Java has three types of features support
i) Built-in (Predefined & Built-in) – Use them directly – String, System, etc….
ii) Predefined – Import and use – Scanner, File,
iii) External – Download third party jar file/s, add to Java project, Import, and Use


III. Variables in Java

1) What is Variable?

A named memory location to store the temporary data within a program

Two types of Memory in Computer Environment
a) Primary Memory (RAM)
b) Secondary Memory (ROM / HDD, DVD, USB etc…)

2) Declaration of Variables

Java supports explicit declaration of variables
In Java

int a;
a=100;
b=200; //Incorrect

In VBScript
Dim a
a=100
b=200 ‘Correct

Variable Declaration Syntax:

dataType variableName;

dataType variableName=value;

dataType variable1Name, variable2Name, variable3Name;

dataType variable1Name=value, variable2Name=value, variable3Name=value;
————–
General Topic:

Data has two important types
i) File format – NoSQL Databases – MangoDB
ii) Table format – SQL Databases – MS Access, Oracle, MS SQL Server, MySQL, SyBase, DB2,
Big Data – Hadoop
————–

3) Assign Values to Variables

a) Initialization
int a=100;// Initialization

int b;
.
.
b=200; // Initialization

int x=a; //Reading

b) Reading
i) Read input using input devices
ii) Read data from files
iii) Read data from Application Objects

4) Variable naming restrictions

a) Java variables are case sensitive

int a;
int B;
.
a=100;
B=200;
.
.
b=300; //Incorrect

b) Java Variable names should start with a letter, or _ or $

myvar
MYVAR
$myvar
_myvar
7myvar //Incorrect
myvar7
*myvar //Incorrect

c) Variable names should not match with Java keywords

int a;
int do; //Incorrect
int od;

if, for, do, while, public, private, new,
true, false, null etc…

d) Java variables must be unique in the scope of the declaration
int a;
int b, c, d;
int e, f, a; //Incorrect

e) Variable names must not exceed 255 characters
1 to 255

5) Types of Variables

Three types of variables in Java
a) Local variables (Local variable is declared in methods or blocks)
b) Instance Variable (Instance variables are declared in a class but outside of a method or any code block)
c) Static / Class Variables (Variable that is declared as static, it cannot be local

Variable Example1:

package user;

class Sample {
//Interface Section
static int x=100; //Static Variable
int y=200; //Instance variable

public int add1() {
int a=10, b=20; //Local Variables
int res=a+b+x+y;
return res;
}

public static void main(String[] args) {
// Main Program
int z=300; //Instance variable
Sample obj = new Sample();

System.out.println(x+z+obj.y);//600
System.out.println(“”);
System.out.println(obj.add1());//330
System.out.println(“”);
if (z>200) {
int s=100;
System.out.println(x+z+s);//500
}
//System.out.println(x+s);
}
//Interface Section

}

Example2:

public class Sample {
static int x=100; //Static Variable
int z=200; //Non static variable

public int add() {
int a=10, b=20; //Local variables
return a+b+x+z;
}
public int add2() {
int c=30, d=20; //Local variables
return c+d+x+z;
}

public static void main(String[] args) {
//static int f=500;
Sample obj=new Sample();

System.out.println(obj.add());//330
System.out.println(obj.add2());//350

int s=400; //Non static variable
System.out.println(x+y);//300
System.out.println(x);//100
System.out.println(obj.z+s);//600

if (s>300) {
int g=22;
System.out.println(g+x+y);//322
}
//System.out.println(g+x+y);//322

}
static int y=200; //Static Variable

}

Note:
static variables – we declare static variables in the Interface Section (outside of the main method), and we use static variables everywhere in the class

local variables – we declare local variables in methods or any code blocks, but we have to use local variables within the block of code where it declared.


 

G C Reddy

G C Reddy, Working as a Software Testing Trainer in Hyderabad, India.

You may also like...