0% found this document useful (0 votes)
5 views215 pages

Java Programming Course Overview

The document outlines a Java programming course offered by Ethnotech Academy, detailing the course structure, including topics such as Java fundamentals, flow control, and object-oriented programming. It also provides installation steps for Java, environment setup, and input/output operations using standard packages and the Scanner class. Additionally, it discusses variable scope and the importance of comments and documentation in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views215 pages

Java Programming Course Overview

The document outlines a Java programming course offered by Ethnotech Academy, detailing the course structure, including topics such as Java fundamentals, flow control, and object-oriented programming. It also provides installation steps for Java, environment setup, and input/output operations using standard packages and the Scanner class. Additionally, it discusses variable scope and the importance of comments and documentation in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

JAVA PROGRAMMING

ETHNOTECH ACADEMY
CERTIFICATE FORMAT
Click icon to add picture

ETHNOTECH ACADEMY
COURSE OUTLINE

S1 JAVA FUNDAMENTALS

S2 SCOPE OF VARIABLES , COMMENT & DOCUMENT

S3 DATA TYPES ,VARIABLES & STRINGS

S4 ARRAYS,ARRAY LISTS,PARSING,CASTING & CONVERSION

ETHNOTECH ACADEMY
COURSE OUTLINE
FLOW CONTROL IMPLEMENTATION
S5
BRANCHING STATEMENTS

S6 LOOPING STATEMENTS

OBJECT ORIENTED PROGRAMMING


S7 CONSTRUCT & EVALUATE CLASS DEFINITIONS

DECLARE , IMPLEMENT & ACCESSING DATA MEMBERS IN


S8 CLASSES

ETHNOTECH ACADEMY
COURSE OUTLINE

S9 DECLARE , IMPLEMENT & ACCESSING METHODS

S10 INSTANTIATE & USE CLASS OBJECTS

S11 CODE COMPILATION

S12 DEBUGGING

ETHNOTECH ACADEMY
EXIT PROFILE

Jav
a
Senior We
b
Developer Develo
per

Junior
Developer Programmer
Analyst

Java
Android Free
lanc
Developer Full Stack ing
Java
Developer

ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
SESSION 1- JAVA FUNDAMENTALS

• Download Java

• Installation Steps (Setting up of Java)

• Set Environment In Java

• Test the Java Installation

• Describe the use of main in a Java application

• Perform basic Input and Output using Standard


Packages
ETHNOTECH ACADEMY
Download Java
• Download the latest Java Development Kit installation file for Windows 10 to
have the latest features and bug fixes.

1. Using your preferred web browser, navigate to the Oracle Java Downloads page.

2. On the Downloads page, click the x64 Installer download link under
the Windows category. At the time of writing this article, Java version 17 is the
latest long-term support Java version.

Wait for the download to complete.


ETHNOTECH ACADEMY
Installation Steps(Setting up of Java)

We must have:
• The Java Runtime Environment (JRE)
• Includes Java Virtual Machine (JVM)
• The Java Developer Kit (JDK)
• Includes the Java Compiler
• A text editor
Optional:
• An Integrated Development Environment (IDE) – a software application that
provides comprehensive facilities to computer programmers for software
development
• NetBeans
• Eclipse

ETHNOTECH ACADEMY
Installation Steps Cont’d..
Step 1: Run the Downloaded File
• Double-click the downloaded file to start the installation.
Step 2: Configure the Installation Wizard
• After running the installation file, the installation wizard welcome screen
appears.
1. Click Next to proceed to the next step.

ETHNOTECH ACADEMY
Installation Steps Cont’d..
2. Choose the destination folder for the Java installation files or stick to the default
path. Click Next to proceed.

ETHNOTECH ACADEMY
Installation Steps Cont’d..
3. Wait for the wizard to finish the installation process until the Successfully
Installed message appears. Click Close to exit the wizard.

ETHNOTECH ACADEMY
Set Environment In Java
Step 1: Add Java to System Variables
1. Open the Start menu and search for environment variables.
2. Select the Edit the system environment variables result.

ETHNOTECH ACADEMY
Set Environment In Java Cont’d..
3. In the System Properties window, under the Advanced tab, click Environment
Variables…

ETHNOTECH ACADEMY
Set Environment In Java Cont’d..
4. Under the System variables category, select the Path variable and click Edit:

ETHNOTECH ACADEMY
Set Environment In Java Cont’d..
5. Click the New button and enter the path to the Java bin directory:
6. Click OK to save the changes and exit the variable editing window.

ETHNOTECH ACADEMY
Set Environment In Java Cont’d..
Step 2: Add JAVA_HOME Variable
• Some applications require the JAVA_HOME variable. Follow the steps below to
create the variable:
• 1. In the Environment Variables window, under the System variables category,
click the New… button to create a new variable.

ETHNOTECH ACADEMY
Set Environment In Java Cont’d..
2. Name the variable as JAVA_HOME.
3. In the variable value field, paste the path to your Java jdk directory and
click OK.
4. Confirm the changes by clicking OK in the Environment Variables and System
properties windows.

ETHNOTECH ACADEMY
Test the Java Installation
• Run the java -version command in the command prompt to make sure Java
installed correctly:

• If installed correctly, the command outputs the Java version. Make sure
everything works by writing a simple program and compiling it. Follow the steps
below:

ETHNOTECH ACADEMY
Test the Java Installation Cont’d
Step 1: Write a Test Java Script
• 1. Open a text editor such as Notepad++ and create a new file.
• 2. Enter the following lines of code and click Save:

• 3. Name the file and save it as a Java source file (*.java).

ETHNOTECH ACADEMY
Java Features

• Compiled and Interpreted


• Platform Independent and Portable
• Object Oriented
• Robust and Secure
• Multithreaded and Interactive
• Dynamic and Extensible
• High Performance

ETHNOTECH ACADEMY
Describe the use of main in a Java
Application
Signature of main
public static void main(String[] args)

ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..

public static void main(String[] args)

ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..

Simple example:

class ethnotech
{
public static void main( String args[])
{
[Link](“Ethnotech Academy");
}
}
Output: Ethnotech Academy

ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..
How to consume an instance of your own class:

• An object that is created using a class is said to be an instance


of that class.

• We will sometimes say that the object belongs to the class.

• The variables that the object contains are called instance variables.

• The methods (that is, subroutines) that the object contains are
called instance methods.

ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..
Declaration of Class:

• A class is declared by use of the class keyword.

• The class body is enclosed between curly braces


{ and }.

• The data or variables, defined within a class are
called instance variables.

• The code is contained within methods.

• Collectively, the methods and variables defined


within a class are called members of the class.
ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..
Declaration of Instance Variables :

• Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables.

• An instance variable can be declared public or private or default (no modifier).

• When we do not want our variable’s value to be changed out-side our class we should declare
them private.

• Public variables can be accessed and changed from outside of the class.
ETHNOTECH ACADEMY
Describe the use of main in a Java Application
Cont’d..
Declaration of Methods :
• A method is a program module that contains a series of statements that carry out a
task.

• To execute a method, you invoke or call it from another method; the calling method
makes a method call, which invokes the called method.

• Any class can contain an unlimited number of methods, and each method can be
called an unlimited number of times.

• The syntax to declare method is given below.

ETHNOTECH ACADEMY
Input & Output using Standard
Packages
Java IO : Input-output in Java with Examples

• It brings various Streams with its I/O package that helps


the user to perform all the input-output operations.

• These streams support all the types of objects, data-


types, characters, files etc. to fully execute the I/O
operations.

ETHNOTECH ACADEMY
Input & Output using Standard Packages
cont’d..
Java provides 3 standard or default streams

ETHNOTECH ACADEMY
Input & Output using Standard Packages
cont’d..

[Link]: This is the standard input stream that is used to


read characters from the keyboard or any other standard input
device.

[Link]. out: This is the standard output stream that is used to


produce the result of a program on an output device like the
computer screen.

[Link]: This is the standard error stream that is used to


output all the error data that a program might throw, on a computer
screen or any standard output device

ETHNOTECH ACADEMY
.

Input & Output using Standard


Packages cont’d..
List of the various print functions that we use to
output statements:
[Link]()- It prints string inside the quotes.

2. println() - It prints string inside the quotes similar like print() method.
Then

the cursor moves to the beginning of the next line.

3. printf()- It provides string formatting (similar to printf in C


programming).
ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
Simple Example: println() ,printf() and print()
Methods
public class Output
{
public static void main(String[] args)
{
[Link]("1. println ");
[Link]("2. println "); Output:
1. println
[Link]("World%n");
2. println
[Link]("1. print "); world
[Link]("2. print"); 1. print 2. print
}
}
ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
What is Scanner class:

• Scanner is a class in [Link] package used


for obtaining the input of the primitive types
like int, double and strings etc.
• It is the easiest way to read input in a
program.
• In order to use the Scanner class, you can
create an object of the class and use any of
the Scanner class methods.
ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
Import Scanner class:
• Import the [Link] package before we can use
the Scanner class.
import
[Link];
Create a Scanner Object in Java:
Scanner S = new
Scanner([Link]);
• We have created an object of Scanner named S.

• The [Link] parameter is used to take input from


the standard input. It works just like taking inputs from
the keyboard
ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
Input Types:
METHOD DESCRIPTION
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
next() Reads a String value from the user(single word)
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
nextLine() Reads a line of text

ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
Example on Scanner Input Types:

// Java program to read data of various types using Scanner class.


import [Link];
public class ScannerDemo1
{
public static void main(String[] args)
{
// Declare the object and initialize with
Scanner sc = new Scanner([Link]); // predefined standard input
object
String name = [Link]();// String input

ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..

char gender = [Link]().charAt(0); // Character input


[Link]("Name: "+name);

int age = [Link]();// Numerical data input

long mobileNo = [Link]();// byte, short and float can


be read

double cgpa = [Link]();// using similar-named


functions.

ETHNOTECH ACADEMY
.

Input & Output using Standard Packages


cont’d..
Example on Scanner Input Types:

// Print the values to check if the input was correctly obtained.


[Link]("Name: "+name);
[Link]("Gender: "+gender);
[Link]("Age: "+age);
Name: raj
[Link]("Mobile Number: "+mobileNo);
[Link]("CGPA: "+cgpa); Gender: M
Age: 24
} CGPA: 78.98
}

ETHNOTECH ACADEMY
Input and Output Using IO package
Streams
Creating DataInputStream Object for Reading values From Keyboard
DataInputStream d=new DataInputStream([Link]);
To read Integer values
int i=[Link]([Link]());
To Read Floating point values
float f=[Link]([Link]());
To Read Double values
double d=[Link]([Link]());

ETHNOTECH ACADEMY
Input and Output Using IO package
Cont’d
To Read Long values
Long l=[Link]([Link]());
To Read String
String name=[Link]();
To read Boolean Value
Boolean b=[Link]([Link]());
To Read Byte Value
byte b=[Link]([Link]());

ETHNOTECH ACADEMY
Input and Output Using IO package
Streams
import [Link].*;
class scan
{
public static void main(String args[])throws IOException
{
DataInputStream s=new DataInputStream([Link]);
[Link]("Enter rollno");
int rollno=[Link]([Link]());
[Link](“Enter mobile no\n");
long mno=[Link]([Link]());
String name=[Link]();
double per=[Link]([Link]());
[Link](“Enter gender");
ETHNOTECH ACADEMY
Input and Output Using IO package
Streams
char g=(char)[Link]();
byte b1=[Link]("123");
boolean b=[Link]("true");
[Link]("rollno="+rollno);
[Link]("name="+name);
[Link]("gender="+g);
[Link]("mno="+mno);
[Link]("per="+per);
[Link]("b="+b);
[Link]("b1="+b1);
}
}

ETHNOTECH ACADEMY
SESSION-2

• Evaluate the Scope of a Variable.

• Comment and Document Programs

• Solving Simple Exercise Problems

ETHNOTECH ACADEMY
.

Evaluate the Scope of a Variable

• In programming, a variable can be declared and defined inside a class,


method, or block.

• It defines the scope of the variable i.e. the visibility or accessibility of a


variable.

• Variable declared inside a block or method are not visible to outside.

• If we try to do so, we will get a compilation error.

• Note that the scope of a variable can be nested.


ETHNOTECH ACADEMY
.

Evaluate The Scope Of A Variable


Cont’d..
• We can declare variables anywhere in the program but it has limited
scope.

• A variable can be a parameter of a method or constructor.

• A variable can be defined and declared inside the body of a method


and constructor.

• It can also be defined inside blocks and loops.

• Variable declared inside main() function cannot be accessed outside


the main() function

ETHNOTECH ACADEMY
.

Evaluate The Scope Of A Variable


Cont’d..
THREE TYPES OF VARIABLES:

ETHNOTECH ACADEMY
.

Evaluate The Scope Of A Variable


Cont’d..
Simple Example: Instance ,Class & Local variable
public class Demo
{
static String name = “Ethnotech"; //static variable
double height= 5.9; //instance variable
public static void main(String args[])
{
int marks = 72; //local variable Output:
[Link]("Marks="+marks);
}
Marks=72
}

ETHNOTECH ACADEMY
.

Comment and Document Programs


Comments:
• The Java comments are the statements in a program that are not executed by
the compiler and interpreter.
Why do we use comments in a code?
• Comments are used to make the program more readable by adding the details
of the code.

• It makes easy to maintain the code and to find the errors easily.

• The comments can be used to provide information or explanation about


the variable, method, class, or any statement.

ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Types of Java Comments:

Three types of Comments


are:

[Link] Line Comment

[Link] Line Comment

[Link] Comment

ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Single line Comment:

• The single-line comment is used to comment only one line of the


code.

• It is the widely used and easiest way of commenting the


statements.

• Single line comments starts with two forward slashes (//).

• Any text in front of // is not executed by Java.

• Syntax:
ETHNOTECH ACADEMY //This is single line comment
.

Comment and Document Programs


Cont’d
Single line Comment Example:

public class CommentExample1


{
public static void main(String[] args)
{
int i=10; // i is a variable with value 10
[Link](i); //printing the variable i
} Output:
}
10

ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Multi line Comment:
• The multi-line comment is used to comment multiple lines of
code.

• It can be used to explain a complex code snippet or to comment


multiple lines of code at a time (as it will be difficult to use single-
line comments there).

• Multi-line comments are placed between /* and */. Any text


between /* and */ is not executed by Java.

Syntax: /* This
is
multi line
comment */
ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Multi line Comment Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=100;
[Link](i);
/* float j = 5.9f;
float k = 4.4f;
Output:
[Link]( j + k ); */
} 100
}

ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Documentation Comment:

• Documentation comments are usually used to write large programs for a project
or software application as it helps to create documentation API.

• These APIs are needed for reference, i.e., which classes, methods, arguments,
etc., are used in the code.

• To create documentation API, we need to use the Javadoc tool.

• The documentation comments are placed between /** and */.

ETHNOTECH ACADEMY
.

Comment and Document Programs


Cont’d
Documentation Comment:
Syntax:

/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

ETHNOTECH ACADEMY
SESSION 3

• Primitive Data Types

• Type Conversions.

• Strings

• Operators and Expressions


ETHNOTECH ACADEMY
Primitive Data Types

What is a Data Type in Java?


As the name suggests, data types specify the type of data that can be
stored inside variables in Java.
Java is a statically-typed language. This means that all variables must be
declared before they can be used.
Data types in Java are classified into two types:
• Primitive—which include Integer, Character, Boolean, and Floating
Point.
• Non-primitive—which include Classes, Interfaces, and Arrays.

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Java Primitive Data Types


Name Values Examples
boolean true ,false true, false
char character 'a', 'A', '1', 'ก', ‘:', ‘,', '\t'
Byte 8-bit integer -127, ..., -1, 0, 1, ..., 127
short 16-bit integer -32768 ... 0 ... 32767
int 32-bit integer -400 47 20000000
long 64-bit integer -1234567890L 0L 888L
float decimal 3.14159F 0.0F -2.5E-8F
double 64-bit decimal 3.14159265358979E234
ETHNOTECH ACADEMY
Primitive Data Types Cont’d..
Byte Data Type
• The byte data type is an example of primitive data type. It is an 8-bit
signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). Its minimum value is -128 and maximum value is 127.
Its default value is 0.
• The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int" data
type.
Example:
byte a = 10; byte b = -20 ;
ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Boolean Data Type


The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false
conditions.
The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.
Example:
boolean one = false ;

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive). Its minimum
value is -32,768 and maximum value is 32,767. Its default value is 0.
Short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.

Example:
short s = 10000; short r = -5000;

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Int Data Type


• The int data type is a 32-bit signed integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648 and maximum value
is 2,147,483,647. Its default value is 0.
• The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.

Example:
int a = 100000; int b = -200000;
ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-
range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type
is used when you need a range of values more than those provided by
int.
Example:
long a = 100000L, long b = -200000L

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating
[Link] value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of
floating point numbers.
The float data type should never be used for precise values, such as
currency. Its default value is 0.0F.

Example:
float f1 = 234.5f;
ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating
point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3 ;

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

Char for Character data


• The char data type is for character data.

• Java uses 2-byte Unicode for character data, in order to hold the

world's alphabets. Including Thai.


• Unicode: [Link]

• You can also use char to hold special values:

'\t' tab character


'\n' new-line character
'\u03C0‘ Unicode sequence number for (pi)
ETHNOTECH ACADEMY
Primitive Data Types Cont’d..

char TAB = '\t';


char NEWLINE = '\n';
char PI ='\u03C0';
// Print greek pi symbol
[Link]("I love cake and "+PI);
// Use tab to align output
[Link]("Hello" + NEWLINE
+ TAB + "world"+NEWLINE)

ETHNOTECH ACADEMY
Primitive Data Types Cont’d..
Escape Sequences For Special chars
These ‘\x’ values represent special characters:
Code Name meaning
\t Horizontal Tab Advance to next tab stop
\n New line Start a new line
\v Vertical Tab Performs a vertical tab (maybe)
\f Form feed Start a new page on printed media
\r Carriage return Move to beginning of line
\0 Null Null character, has value 0
\" Double Quote Use for " inside of String
\' Single Quote Use for ' inside of char
\\ Backslash Display a \
ETHNOTECH ACADEMY
Type Conversion

Type conversion in Java


When you assign a value of one data type to another, the two types
might not be compatible with each other.
If the data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion, and if not then
they need to be cast or converted explicitly.
For example, assigning an int value to a long variable.

ETHNOTECH ACADEMY
Type Conversion Cont’d..

Widening or Automatic Type Conversion


• Widening conversion takes place when two data types are
automatically converted. This happens when:
• The two data types are compatible.
• When we assign a value of a smaller data type to a bigger data type.
• For Example, in java, the numeric data types are compatible with each
other but no automatic conversion is supported from numeric type to
char or boolean. Also, char and boolean are not compatible with each
other.

ETHNOTECH ACADEMY
Type Conversion Cont’d..

ETHNOTECH ACADEMY
Type Conversion Cont’d..

class Ethno
{
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
[Link]("Int value " + i);
[Link]("Long value " + l);
}

ETHNOTECH ACADEMY
Type Conversion Cont’d

Narrowing or Explicit Conversion


If we want to assign a value of a larger data type to a smaller data type
we perform explicit type casting or narrowing.

ETHNOTECH ACADEMY
Type Conversion Cont’d..
public class GFG
{
public static void main(String[] args)
{
double d = 100.04;
// data from double type to long type
long l = (long)d;
// Explicit type casting
int i = (int)l;
[Link]("Double value " + d);
[Link]("Long value " + l);
[Link]("Int value " + i);
}}

ETHNOTECH ACADEMY
Strings

What is String?
Widely used in Java programming, are a sequence of characters. In
the Java String is a group of characters stored in string object.
Creating Strings:
String greeting = "Hello world!";
String Length:
The length function which returns the number of characters
contained in the string object.
int n=[Link]();

ETHNOTECH ACADEMY
Strings Cont’d..
Concatenating Strings:
[Link](string2);
This returns a new string that is string2 added to it at the end of string1
Strings are more commonly concatenated with the + operator, as in:
"Hello" + " world" + "!“
Character Extraction
Example1: char ch; ch = “abc”.charAt(1); //assign the value “b” to ch
Example2:String name=“java Program”; char ch=[Link](5);

ETHNOTECH ACADEMY
Strings Cont’d..

String Comparison
To compare two strings for equality
Syntax:boolean equals(String str)
Example:String s1=“java”;
String s2=“JAVA”;
[Link](s2);//Returns true if s1 is equal to s2
To perform a comparison that ignores case differences
boolean equalsIgnoreCase(String str)
Example:[Link](s2);
//Returns true if s1 is equal to s2 and ignoring case of characters

ETHNOTECH ACADEMY
Strings Cont’d
To find position of given character
String s=“java program”;
int n=[Link](‘a’);//Returns position of first occurrence of character ‘a’
int n=[Link](‘a’);//Returns position of last occurrence of character ‘a’

To Extract part of string or subString.


String s1=[Link]();//Returns whole string as a substring.
String s1=[Link](2);//Returns a substring starting from position 2 till end of the
String.
String s1=[Link](2,5);//Returns a substring starting from 2 till 5(Excluding 5).

ETHNOTECH ACADEMY
Strings Cont’d
To replace characters by new characters
Syntax:[Link] (char original,char new);
String s=“Java”;
String s1=[Link](‘j’,’L’);
Program:
class StringDemo
{
public static void main(String args[])
{
String s1=“java”;
String s2=“program”;
ETHNOTECH ACADEMY
Strings Cont’d
[Link](“the length of string s1=“+[Link]());
[Link](“The concatenated string of s1 and s2=“+[Link](s2));
[Link](“The substring of s2 =“+[Link](2,5));
[Link],println(“The replaced string of s1=“[Link](‘j’,’L’));
[Link](“The position of character a in s1=“+[Link](‘a’));
[Link](“The last position of a in s1=“+[Link](‘a’));
[Link](“The character at position 1 in s2=“[Link](1));
}
}

ETHNOTECH ACADEMY
Strings Cont’d..
Example
class EqualsDemo
{
public static void main(String args[ ])
{
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = “Hi”;
String s4 = “HELLO”;
[Link]([Link](s2));
[Link]([Link](s3));
[Link]([Link](s4));
[Link]([Link](s4));
}}
ETHNOTECH ACADEMY
Output

ETHNOTECH ACADEMY
String Cont’d
StringBuffer Class:
It is a peer class of String class unlike String class, StringBuffer creates
string of flexible length and we can modify string in terms of length and
contents in Original string itself.
Method Description

[Link](n,ch) Modifies nth character to ch

[Link](n) Sets string length to n

[Link](S2) Appends string S2 at the end of String S1

[Link](n,s2) Inserts string S2 at position n

ETHNOTECH ACADEMY
String Cont’d

class stringBuf
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object language ");
[Link]("The original string is="+str);
int pos=[Link]("language");
[Link](pos ,"Oriented ");
[Link]("After inserting ,the string is ="+str);
[Link](6,'_');

ETHNOTECH ACADEMY
Strings Cont’d

[Link]("after modifyinh character the string is="+str);


[Link]("Improves Security");
[Link]("after appending the string is="+str);
}
}

ETHNOTECH ACADEMY
Operators In Java
There are many types of operators in Java which are given below:
• Unary Operator
• Arithmetic Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Ternary Operator
• Assignment Operator

ETHNOTECH ACADEMY
Operators Cont’d..

Java Unary Operator


The Java unary operators require only one operand

• Incrementing/decrementing a value by one (++,--)

• Negating an expression (-)

• Inverting the value of a boolean (!)

ETHNOTECH ACADEMY
Operators Cont’d..

public class OperatorExample


{
public static void main(String args[])
{
int x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
}}
ETHNOTECH ACADEMY
Output

ETHNOTECH ACADEMY
Operators Cont’d..

Java Arithmetic Operator Example


public class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
ETHNOTECH ACADEMY
Output

ETHNOTECH ACADEMY
Operators Cont’d..
Java Ternary Operator
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5; OUTPUT
int min=(a<b)?a:b; 2
[Link](min);
}}
ETHNOTECH ACADEMY
Expressions Evaluation

• Expression evaluation in Java is used to determine the order of the


operators to calculate the accurate output.
• Arithmetic, Relational, Logical, and Conditional are expression
evaluations in Java.
• Operator precedence: It dictates the order of evaluation of operators
in an expression
• Associativity: It defines the order in which operators of the same
precedence are evaluated in an expression. Associativity can be either
from left to right or right to left

ETHNOTECH ACADEMY
Expressions Evaluation Cont’d..

Consider the following example:


24 + 5 * 4
• Here we have two operators + and *, Which operation do you think
will be evaluated first, addition or multiplication?
• If the addition is applied first then answer will be 116 and if the
multiplication is applied first answer will be 44.
• To answer such question we need to consult the operator
precedence table.

ETHNOTECH ACADEMY
Expressions Evaluation Cont’d
Operators Meaning Associativity
() Parenthesis Left to right
[] Square bracket
. Dot
-> arrow
++,--
+,- Unary plus, minus Right to left
sizeof
(type)
&
*,/,% Multiplication,division,modul Left to right
us,
+,- Addition,subtraction Left to right

ETHNOTECH ACADEMY
SESSION 4

• Arrays in Java

• ArrayList in Java

• Wrapper Classes

• Parsing in Java
ETHNOTECH ACADEMY
Java Arrays

What is an Array?
An array is a collection of similar type of elements which has
contiguous memory location.
There are two types of array
• Single Dimensional Array
• Multidimensional Array
Syntax to Declare an Array in Java
dataType []arr; (or)
dataType arr[];
ETHNOTECH ACADEMY
Java Arrays Cont’d
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
class Testarray{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
ETHNOTECH ACADEMY
Java Arrays Cont’d

//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

ETHNOTECH ACADEMY
Java Arrays Cont’d..
Output
10 20 70 40 50

Multidimensional Arrays
• A multidimensional array is an array of arrays.
• To create a two-dimensional array, add each array within its own set
of curly braces:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

ETHNOTECH ACADEMY
Java Arrays Cont’d..

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

int x = myNumbers[1][2];

[Link](x); // Outputs 7

ETHNOTECH ACADEMY
Java Arrays Cont’d..
Iterating Array Elements
terating over an array means accessing each element of array one by
one. There may be many ways of iterating over an array in Java, below
are some simple ways.
Using for loop:
This is the simplest of all where we just have to use a for loop where a
counter variable accesses each element one by one.

ETHNOTECH ACADEMY
Java Arrays Cont’d..
class Ethno {
public static void main(String args[])
{
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int i, x;

// iterating over an array


for (i = 0; i < [Link]; i++)
{
// accessing each element of array
x = ar[i];
[Link](x + " ");
}}

ETHNOTECH ACADEMY
Java ArrayList
What is ArrayList?
• Java ArrayList class uses a dynamic array for storing the elements.
• It is like an array, but there is no size limit.
• We can add or remove elements anytime. So, it is much more flexible
than the traditional array.

• It is found in the [Link] package


ArrayList<int> al = ArrayList<int>(); // does not work
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

ETHNOTECH ACADEMY
Java ArrayList Cont’d..

Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean add(E e) It is used to append the specified element at the
end of a list.
void clear() It is used to remove all of the elements from this
list.
E get(int index) t is used to fetch the element from the particular
position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
void set(int index,E e) Sets nth element to e
void remove(int index) Remove the specified elememt from the list

ETHNOTECH ACADEMY
Arraylist

ETHNOTECH ACADEMY
Wrapper Classes

• The wrapper class in Java provides the mechanism to convert


primitive into object and object into primitive.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal
with objects many times like in Collections, Serialization,
Synchronization, etc.

ETHNOTECH ACADEMY
Wrapper Classes Cont’d..

Primitive Types and Equivalent Wrapper Classes


Primitive Type Wrapper Class
int Integer
float Float
long Long
double Double
char Character
boolean Boolean
byte Byte
short Short

ETHNOTECH ACADEMY
Parsing in Java

What is Parsing?
• Parsing in its most general sense is the extraction of the necessary
information from some piece of data, most often textual data.
• There are many Java classes that have the parse() method.
• The parse() method receives some string as input, "extracts" the
necessary information from it and converts it into an object of the
calling class.

ETHNOTECH ACADEMY
Parsing in Java Cont’d..
public class Parsing
{
public static void main(String args[])
{ int x = [Link]("12");
double c = [Link]("12.56"); OUTPUT
int b = [Link]("100",2);
[Link]([Link]("12 “)); 12
[Link]([Link]("12.56")); 12.56
[Link]([Link]("100",2)); 4
[Link]([Link]("101", 8)); 65
}}
ETHNOTECH ACADEMY
SESSION-5 Flow Control
Implementation

• Construct and evaluate code that uses branching


statements

• Jump statements

• Solving Simple Exercise Problems

ETHNOTECH ACADEMY
.

Branching Statements

• if statement

• if-else statement

• if-else-if ladder statement

• switch statement

ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


if statement
• The Java if statement tests the condition. It executes the if block
if condition is true.
Syntax:

if(condition)
{
//code to be executed
}

ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Simple Example:
public class Larger
{
public static void main(String[] args)
{
Output:
x + y is greater th
int x = 10 , y = 12;
an 20
if(x+y > 20)
{
[Link]("x + y is greater than 20");
}
}
}
ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


If else statement
• if-else statement also tests the condition. It executes the if block if condition is
true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Simple Example:
public class Flow Output:
{
public static void main(String[] args) odd number
{
int number=13; //defining a variable
if(number%2==0) //Check if the number is divisible by 2 or not
{
[Link]("even number");
}
else{
[Link]("odd number"); } } }
ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


If-else-if ladder statement
• The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
} else if(condition2){
//code to be executed if condition2 is true
} else if(condition3){
//code to be executed if condition3 is true
} else{
//code to be executed if all the conditions are false
}

ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


If-else-if ladder flow chart

ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Simple Example:
public class Test {
public static void main(String args[]) {
Output:
int x = 30;
if( x == 10 ) { Value of X is
[Link]("Value of X is 10");
} else if( x == 20 ) {
30
[Link]("Value of X is 20");
} else if( x == 30 ) {
[Link]("Value of X is 30");
} else {
[Link]("This is else statement");
}
} }
ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Switch statement
• Instead of writing many if..else statements, you can use the switch statement.

• The switch statement selects one of many code blocks to be executed.


How it works:
• The switch expression is evaluated once.

• The value of the expression is compared with the values of each case.

• If there is a match, the associated block of code is executed.

• The break and default keywords are optional


ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Switch statement
Syntax: switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Switch statement flow chart

ETHNOTECH ACADEMY
.

Branching Statements Cont’d..


Simple Example:
public class SwitchExample { Output:
public static void main(String[] args) {

20
int number=20; //Declaring a variable for switch expression
switch(number) //Switch expression
{
case 10: [Link]("10"); //
Case statements case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
default:[Link]("Not in 10, 20 or 30"); //Default case statement
} } }
ETHNOTECH ACADEMY
SESSION-6 Looping Statements
Construct and evaluate code that uses loops:
• For

• While

• Do-while

• Solving Simple Exercise Problems

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


Construct and evaluate code that uses loops:
• Three types of loops in java

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


For Loop:
• The for loop is used to iterate a part of the program several times. If the number
of iteration is fixed, it is recommended to use for loop.
It consists of four parts:
[Link]: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is an
optional condition.

[Link]: It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return boolean value
either true or false. It is an optional condition.

[Link]/Decrement: It increments or decrements the variable value. It is an optional


condition.

ETHNOTECH ACADEMY
[Link]: The statement of the loop is executed each time until the second condition
.

Looping Statements Cont’d..


For Loop:

Syntax:
for(initialization; condition; increment/decrement)
{

//statement or code to be executed


}

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


For loop flow chart:

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


Simple for loop Example: Output:
1
public class Fexample 2
{ 3
public static void main(String[] args)
4
5
{
6
for(int i=1;i<=10;i++) //Code of Java for loop
7
{ 8
[Link](i); 9
} 10
}
}
ETHNOTECH ACADEMY
Looping Statements Cont’d..
Pattern Program
class Pattern
{
public static void main(String args[])
{
int n=4
for(i=0; i<n; i++) //outer loop for number of rows(n)
{
for(j=2*(n-i); j>=0; j--) // inner loop for spaces
{
[Link](" "); // printing space
}

ETHNOTECH ACADEMY
Looping Statements Cont’d..
for(j=0; j<=i; j++) // inner loop for columns
{
[Link]("* "); // print star
}
[Link](); // ending line after each row
}
}

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


while loop:

• while loop is a control flow statement that allows code to be executed


repeatedly based on a given Boolean condition.

• This loop can be thought of as a repeating if statement.

• while loop in Java comes into use when we need to repeatedly execute a block
of statements.

• The while loop is considered as a repeating if statement. If the number of


iterations is not fixed, it is recommended to use the while loop.

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


While loop:
The various parts of the While loop are:

1. Test Expression: In this expression, we have to test the condition. If the


condition evaluates to true then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the while loop.

Example:

i <= 10;

2. Update Expression: After executing the loop body, this expression


increments/decrements the loop variable by some value.

Example: i++;

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


While loop:

Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


While loop flow chart

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


Simple while loop Example: Output:
public class Wexample 1
{ 2
public static void main(String[] args) 3
{ 4
Int i=1;
5
6
while(i<=10) //Code of Java for loop
7
{ 8
[Link](i); 9
i++; 10
}
} }
ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


do while loop:

• The Java do-while loop is used to iterate a part of the program repeatedly, until
the specified condition is true.

• If the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use a do-while loop.

• Java do-while loop is called an exit control loop. Therefore, unlike while loop
and for loop, the do-while check the condition at the end of loop body.

• The Java do-while loop is executed at least once because condition is checked
after loop body.

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


do while loop:
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop
body is executed, and control goes to update expression. As soon as the
condition becomes false, loop breaks automatically.
Example:
i <=100;

2. Update expression: Every time the loop body is executed, the this expression
increments or decrements loop variable.

Example:
i++;
ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


do while loop

Syntax:

do
{
//code to be executed / loop body
//update statement
}while (condition);

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


do while loop flow chart:

ETHNOTECH ACADEMY
.

Looping Statements Cont’d..


Simple do while loop Example:
public class DWexample
{
public static void main(String[] args)
{
Output:
1
Int i=1; 2
do{ 3
[Link](i); 4
i++; 5
}while(i<=5);
}
}
ETHNOTECH ACADEMY
SESSION 7 Object Oriented
Programming
• Construct and evaluate class definitions
• Constructors

• Constructor Overloading

• this keyword

• Basic Inheritance

• Overriding

ETHNOTECH ACADEMY
.

Object Oriented Programming


What is Object Oriented Programming ?
• Object means a real-world entity such as a pen, chair, table,
computer, watch, etc.

• Object-Oriented Programming is a methodology or paradigm to


design a program using classes and objects.

• Object-oriented programming is a core of Java Programming, which


is used for designing a program using classes and objects.

• OOPs, can also be characterized as data controlling for accessing


the code.
ETHNOTECH ACADEMY
.

Object Oriented Programming Cont’d..

What is Object Oriented Programming in Java?

• OOPs in java is to improve code readability and reusability by


defining a Java program efficiently.

• The main principles of object-oriented programming


are abstraction, encapsulation, inheritance, and
polymorphism.

• These concepts aim to implement real-world entities in programs.

ETHNOTECH ACADEMY
.

Object Oriented Programming Cont’d..


Difference between Object OOPs & Procedural
Programming
• Procedural programming is about writing procedures or methods that perform
operations on the data.
• Object-oriented programming is about creating objects that contain both data and
methods.

Object-oriented programming has several advantages over procedural


programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and
shorter
ETHNOTECH development time
ACADEMY
.

Object Oriented Programming Cont’d..


Object Oriented Programming Concepts:
OOPS concepts are as follows:
[Link]
[Link]
[Link] of OOPs
[Link]
[Link]
[Link]
[Link]

ETHNOTECH ACADEMY
.

Object Oriented Programming Cont’d..


Object:
• Any entity that has state and behaviour is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.

• An Object can be defined as an instance of a class.

• An object contains an address and takes up some space in


memory.

• Objects can communicate without knowing the details of each


other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the
objects.

• Example: A dog is an object because it has states like color,


name, breed, etc. as well as behaviours like wagging the tail,
barking, eating, etc.
ETHNOTECH ACADEMY
.

Object Oriented Programming Cont’d..


Class:

• Collection of objects is called class. It is a


logical entity.

• A class can also be defined as a blueprint


from which you can create an individual
object.

• Class doesn't consume any space.

ETHNOTECH ACADEMY
.

Object Oriented Programming Cont’d..


Abstraction:
• Hiding internal details and showing
functionality is known as abstraction.

• For example phone call, we don't know the


internal processing.

• In Java, we use abstract class and interface


to achieve abstraction.
For example, when we are driving a car, we are only concerned
about driving the car like start/stop the car, accelerate/ break, etc.
We are not concerned about how the actual start/stop mechanism or
accelerate/brake process works internally. We are just not interested
in those details.

ETHNOTECH ACADEMY
SESSION-8 Accessing Data Members
In Classes
Declare, implement, and access data members in classes
• Private, Public & Protected

• Instance data members

• Static data members

• Static final to create constants

• Describe Encapsulation
ETHNOTECH ACADEMY
SESSION 9

• Declaring Methods
• Implementing Methods
• Accessing Methods
• Creating Objects
• Abstract Methods and Classes
• Final Method and Final Classes
• Visibility Control.

ETHNOTECH ACADEMY
Declaring Methods

What is a Method in java?


A method is a collection of statements grouped together to perform
a certain task . It is used to achieve the reusability of code. We write a
method once and use it many times.
A function defined in a java class is called method
Method Declaration
The method declaration provides information about method attributes,
such as visibility, return-type, name, and arguments. It has six
components that are known as method header, as we have shown in
the following figure.
ETHNOTECH ACADEMY
Declaring Methods Cont’d..

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

Method Signature: Every method has a method signature. It is a part of


the method declaration. It includes the method name and parameter
list.
Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java
provides four types of access specifier:
Public: The method is accessible by all classes when we use public
specifier in our application.
Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

Protected: When we use protected access specifier, the method is


accessible within the same package or subclasses in a different
package.
Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible
only from the same package only.
Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method
does not return anything, we use void keyword.

ETHNOTECH ACADEMY
Declaring Methods Cont’d..
Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method.
Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and
enclosed in the pair of parentheses. It contains the data type and
variable name. If the method has no parameter, left the parentheses
blank.
Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within the pair of curly braces.

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in
the Java class libraries is known as predefined methods
It is also known as the standard library method or built-in method.

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

Let's see an example of the predefined method.


[Link]
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
} }
ETHNOTECH ACADEMY
Declaring Methods Cont’d..
OUTPUT
The maximum number is: 9

User-defined Method
The method written by the user or programmer is known as a user-
defined method.
These methods are modified according to the requirement.

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

Let's create a user defined method that checks the number is even or
odd. First, we will define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}

ETHNOTECH ACADEMY
Declaring Methods Cont’d..

How to Call or Invoke a User-defined Method


import [Link];
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num); }}

ETHNOTECH ACADEMY
Declaring Methods Cont’d..
• OUTPUT

ETHNOTECH ACADEMY
Accessing Methods

Instance Method
The method of the class is known as an instance method. It is a non-
static method defined in the class.
Before calling or invoking the instance method, it is necessary to create
an object of its class. Let's see an example of an instance method.

ETHNOTECH ACADEMY
Accessing Methods Cont’d..
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
[Link]("The sum is: "+[Link](12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s; }}
ETHNOTECH ACADEMY
Accessing Methods

What is static Method?


Features of static method:
• A static method in Java is a method that is part of a class rather than an instance
of that class.
• Every instance of a class has access to the method.
• Static methods have access to class variables (static variables) without using the
class’s object (instance).
• Only static data may be accessed by a static method. It is unable to access data
that is not static (instance variables).
• In both static and non-static methods, static methods can be accessed directly.

ETHNOTECH ACADEMY
Accessing Methods Cont’d..

public class Ehno public static void main(String[] args)

{ {

static int a = 40; Ethno obj = new Ethno();

// instance variable [Link]();

int b = 50; staticDisplay();


void simpleDisplay() }
{ }
[Link](a);
[Link](b);
}
static void staticDisplay()
{ ACADEMY
ETHNOTECH [Link](a);
Method Overloading

What is Method Overloading?


If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading

If we have to perform only one operation, having same name of the


methods increases the readability of the program.

ETHNOTECH ACADEMY
Method Overloading Cont’d..
class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
ETHNOTECH ACADEMY
Output

ETHNOTECH ACADEMY
SESSION 10

• Creating Objects

• Abstract Methods and Classes

• Final Method and Final Classes

• Visibility Control.

ETHNOTECH ACADEMY
Creating Objects

What is an object in Java?


An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc.

It can be physical or logical (tangible and intangible).

The example of an intangible object is the banking system.

ETHNOTECH ACADEMY
Creating Objects Cont’d..

An object has three characteristics:

ETHNOTECH ACADEMY
Creating Objects Cont’d..

• For Example, Pen is an object. Its name is Reynolds; color is white,


known as its state. It is used to write, so writing is its behavior.
• An object is an instance of a class. A class is a template or blueprint
from which objects are created. So, an object is the instance(result) of
a class.
• Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
ETHNOTECH ACADEMY
Creating Objects Cont’d..

How to Create Object in Java


he object is a basic building block of an OOPs language. In Java, we
cannot execute any program without creating an object. There is
various way to create an object in Java that we will discuss in this
section, and also learn how to create an object in Java.
Using new Keyword
• Using the new keyword is the most popular way to create an object or
instance of the class. When we create an instance of the class by
using the new keyword, it allocates memory (heap) for the newly
created object and also returns the reference of that object to that
memory. The new keyword is also used to create an array.
ETHNOTECH ACADEMY
Creating Objects Cont’d..
The syntax for Creating an Object is:
ClassName object = new ClassName();
[Link]
public class CreateObjectExample1
{
void show()
{
[Link]("Welcome to javaTpoint");
} } class ObjectExampleDemo{
public static void main(String[] args)
{
//creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
//invoking method using the object
[Link](); }}

ETHNOTECH ACADEMY
Constructors
What are Constructors?
Constructors are special methods used to initialize instance variable
and its name should be same as class [Link] does not return any
value.
class Student
{
int rollno,sem,age;
char name[15];
Student()//default Constructor
{}
r ACADEMY
ETHNOTECH
Constructors Cont’d
Student(int r,int a,int s,char n[])//parameterized Constructor
{
rollno=r;
age=a;
sem=s;
name=n;
}
void display()
{
[Link](rollno+”\t”+name+”\t”+sem+”\t”+age);}}

ETHNOTECH ACADEMY
Constructors Cont’d

class ConstructorDemo
{
public static void main(String args[])
{
Student s=new Student(111,24,3,”raj”);
[Link]();
}
}

ETHNOTECH ACADEMY
Abstract Methods

• The method that does not has method body is known as abstract
method. In other words, without an implementation is known as
abstract method. It always declares in the abstract class. It means the
class itself must be abstract if it has abstract method. To create an
abstract method, we use the keyword abstract.
Syntax:
abstract void method_name();

ETHNOTECH ACADEMY
Static keyword in Java
The static keyword in Java is used for memory management mainly. We
can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the
class(Object).
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class

ETHNOTECH ACADEMY
Static Keyword in Java Cont’d..

Static Variables:The static variable can be used to refer to the common


property of all objects (which is not unique for each object), for
example, the company name of employees, college name of students,
etc.
The static variable gets memory only once in the class area at the time
of class loading.
Advantages of static variable
It saves memory.
Ex:static String College=“EWIT”;

ETHNOTECH ACADEMY
Static Keyword in Java Cont’d..
Java static method
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a
class.
A static method can access static data member and can change the value of it.
The static method can not use non static data member or call non-static method
directly.
this and super cannot be used in static context.

ETHNOTECH ACADEMY
Static Keyword in Java Cont’d..
Java static block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
Ex:class A2
{
static{
[Link]("static block is invoked");
}
public static void main(String args[]){
[Link]("Hello main");
}
}
ETHNOTECH ACADEMY
Static Keyword in Java Cont’d..

It is not possible to execute a Java class without the main method.


class A3
{
static
{
[Link]("static block is invoked");
[Link](0);
}
}
ETHNOTECH ACADEMY
Inheritance in Java

Various forms of inheritance Supported by Java:


[Link] Inheritance
[Link] Inheritance
[Link] inheritance
[Link] Inheritance
[Link] Inheritance A super parent

B
sub
child

ETHNOTECH ACADEMY
Inheritance Cont’d…

Multilevel Inheritance
Super A Grand Father

Intermediate
B Father
Super

Sub class C Child

ETHNOTECH ACADEMY
Inheritance Cont’d…

Hierarchical Inheritance
super class
A

sub class B C sub class

ETHNOTECH ACADEMY
Inheritance Cont’d…

Multiple Inheritance
Super A B
Super

Sub
C

Java doesnot support for multiple inheritance that means a java class
doesnot have more than one super class but in real time applications it
is required so By using interface we can implement multiple inhertance.

ETHNOTECH ACADEMY
Inheritance Cont’d…

Defining Interface
interface Area
{
static final float PI=3.14159f;
float compute();
}

ETHNOTECH ACADEMY
Method Overloading

What is Method Overloading?


If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading

If we have to perform only one operation, having same name of the


methods increases the readability of the program.

ETHNOTECH ACADEMY
Method Overloading Cont’d..

• class Adder
• {
• static int add(int a,int b){return a+b;}
• static int add(int a,int b,int c){return a+b+c;}
• }
• class TestOverloading1{
• public static void main(String[] args){
• [Link]([Link](11,11));
• [Link]([Link](11,11,11));
• }
• }
ETHNOTECH ACADEMY
Method Overriding
If sub class has the same method as declared in the super class ,it is
known as method overriding.

It is one of the way implement run time polymarphism.

These are identical in method signatures.

The main advantage of method overriding is to implement multiple


definitions with same name.

ETHNOTECH ACADEMY
Method Overriding Cont’d..

ETHNOTECH ACADEMY
Abstract Methods Cont’d..

Example of abstract method


[Link] class AbstractDemo{
abstract class Demo //abstract class public static void main(String args[]) {
{ //creating object of abstract class
abstract void display(); Demo obj = new MyClass();
}
public class MyClass extends Demo //invoking abstract method
{ [Link]();
//method impelmentation }}
void display()
{
[Link]("Abstract method?");
}}

ETHNOTECH ACADEMY
Final variables

In java ,final keyword is used to create symbolic constants.


Ex: final int code=1001;
final String name=“fan”;
Name=“college” ;//illegal
We cannot change value of name because its is constant if we attemt
to change then it shows an error.

ETHNOTECH ACADEMY
Java Final Method
If you make any method as final, you cannot override it.
Example of method Overriding
class Bike{
final void run(){[Link]("running");}
}
class Honda extends Bike
{
void run()
{
[Link]("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
[Link](); }}
ETHNOTECH ACADEMY
Java Final Method Cont’d..

ETHNOTECH ACADEMY
Final Class
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
}
ETHNOTECH ACADEMY
Access Control

Access Modifiers in Java


The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
ETHNOTECH ACADEMY
Access Control Cont’d..

Protected: The access level of a protected modifier is within the


package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.

ETHNOTECH ACADEMY
Access Control Cont’d..

ETHNOTECH ACADEMY
CERTIFICATION QUESTIONS

ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
SUMMARY
Click icon to add picture

ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
ETHNOTECH ACADEMY
CERTIFICATION PATH
Click icon to add picture

ETHNOTECH ACADEMY
ETHNOTECH ACADEMY

You might also like