0% found this document useful (0 votes)
25 views107 pages

Java

Uploaded by

Nitya
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)
25 views107 pages

Java

Uploaded by

Nitya
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
You are on page 1/ 107

INTRODUCTION TO JAVA

 Java is a programming language developed by James Gosling and first released by Sun

Microsystems in 1995.

 Around 56 billion devices run Java, as of June 2022.

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)

 https://www.oracle.com/java/technologies/downloads/#jdk19-windows
PROGRAMMIN
G STRUCTURE
DOCUMENTATION /
COMMENT
 Single-line comments: start with two forward slashes (//).

 Multi-line comments: start with /* and ends with */.

 Documentation Comment: It starts with the delimiter (/**) and ends with */.
PACKAGE
A package in Java is used to group related classes.
IMPORT STATEMENT
JAVA CLASS
 Every application begins with a class name, and that class must match the filename
CLASS DEFINITION
• The class is a blueprint of a Java program that contains information about user-defined methods,
variables, and constants.
• Every line of code that runs in Java must be inside a class. Without the class, we cannot create any
Java program.
11 / 85

• Every Java program has at least one class that contains the main().
• We use the class keyword to define the class.
• A class name should always start with an uppercase first letter.
MAIN METHOD CLASS
• The execution of all Java programs starts from the main() method.

• In other words, it is an entry point of the class. It must be inside the class.

• Inside the main method, we create objects and call the methods.

• public- This is the access modifier of the main method. It has to be public so that java runtime can
execute this method.

• It can be either String[] args or String args[]


WHY MAIN() METHOD MUST BE
STATIC IN JAVA?
 The public static void main(String ar[]) method is the entry point of the execution in Java.
 When we run a .class file JVM searches for the main method and executes the contents of it line
by line.
 Static − If you declare a method or a variable to be static, it is loaded along with the class.
 In Java whenever we need to call an method, we should instantiate the class (containing it) and call
it.
 If we need to call a method without instantiation it should be static.
 In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by
instantiating its class.
 And, it should be loaded into the memory along with the class and be available for execution.
Therefore, the main method should be static.
WHEN THE MAIN METHOD IS NON-
STATIC?
 You can write the main method in your program without the static modifier, the program gets compiled

without compilation errors. But, at the time of execution JVM does not consider this new method (without
static) as the entry point of the program.

 It searches for the main method which is public, static, with return type void, and a String array as an

argument. If such a method is not found, a run time error is generated.


VOID
 Each method in java has a different return type, such as Integer, Double, Boolean, String, etc.

A Java main() function does not return anything to keep things simple and has the return type
void.

 After executing the main() method, the program will be terminated, and returning anything

from the main() method is useless because the JVM cannot do anything with the return value.
The following error will be thrown if we do not provide the main() method with a void return
type:
PRINT STATEMENTS
JAVA PRINT
 There is also a print() method, which is similar to println().

 The only difference is that it does not insert a new line at the end of the output

 Double Quotes: When you are working with text, it must be wrapped inside double

quotations marks "".

 If you forget the double quotes, an error occurs


 To combine both text and a variable, use the + character:

 You can also use the + character to add a variable to another variable:

 For numeric values, the + character works as a mathematical operator.


JAVA VARIABLES AND
IDENTIFIERS
JAVA VARIABLES
DECLARING (CREATING)
VARIABLES
To create a variable, you must specify the type and assign it a value:
FINAL VARIABLES
 If you don't want others (or yourself) to overwrite existing values, use the final

keyword (this will declare the variable as "final" or "constant", which means
unchangeable and read-only):
JAVA DECLARE MULTIPLE
VARIABLES
 To declare more than one variable of the same type, you can use a comma-separated list:

 You can also assign the same value to multiple variables in one line:
JAVA IDENTIFIERS
 All Java variables must be identified with unique names called identifiers.

 Identifiers can be short names (like x and y) or more descriptive names (age, sum,

totalVolume).

 Note: It is recommended to use descriptive names in order to create understandable

and maintainable code:


The general rules for naming variables are:

 Names can contain letters, digits, underscores, and dollar signs

 Names must begin with a letter

 Names should start with a lowercase letter and it cannot contain whitespace

 Names can also begin with $ and _ (but we will not use it in this tutorial)

 Names are case sensitive ("myVar" and "myvar" are different variables)

 Reserved words (like Java keywords, such as int or boolean) cannot be used as names
3 TYPES OF VARIABLE
 Static variable: A variable that is declared as static is called a static variable. It cannot be local.

Memory allocation for static variables happens only once when the class is loaded in the memory. It is
the variable that should be initialized first, especially before an instance variable is initialized.

 Instance variable: A variable declared inside the class but outside the body of the method, is called an

instance variable. It is not declared as static.

 Local variable: A variable declared inside the body of the method is called local variable. A local

variable cannot be defined with "static" keyword.


PRACTISE PROGRAMS
 Instance variables:

String Ename- To store the name of the Employee

int EmployeeID- To store the ID of the employee

 Static variable:

String Eaddress- To store the address of the Employee

 Instance methods:

display()-display Ename , EmployeeID, Eaddress

 main method :

display Ename , EmployeeID, Eaddress


DATA TYPES – PRIMITIVE &
NON-PRIMITIVE
JAVA DATA TYPES
Primitive data types - includes byte, short, int, long, float, double, boolean and char

Non-primitive data types - such as String, Arrays and Classes


BOOLEAN VALUES
PRACTISE PROGRAM
Find out if a person is old enough to vote.
DEFAULT VALUES ASSIGNED TO
PRIMITIVE DATA TYPES
 Default values are values assigned by the compiler to the variables

which are declared but not initialized or given a value.


Primitive data type Non-primitive data type

Primitive types are predefined (already Non-primitive types are created by the programmer and is not
defined) in Java defined by Java (except for String).

It cannot Non-primitive types can be used to call methods to perform


certain operations

A primitive type has always a value Non-primitive types can be null

primitive type starts with a lowercase letter while non-primitive types starts with an uppercase letter

size of a primitive type depends on the data non-primitive types have all the same size
type
TYPE CASTING
JAVA TYPE CASTING
 Type casting is when you assign a value of one primitive data type to another type. In Java, there are

two types of casting:


Widening Casting

Narrowing Casting
JAVA OPERATORS
JAVA OPERATORS
Operators are used to perform operations on variables and values.

1. Arithmetic operators

2. Assignment operators

3. Comparison operators

4. Logical operators

5. Bitwise operators
ARITHMETIC OPERATORS
 Although the + operator is often used to add together two values, like in the example above, it

can also be used to add together a variable and a value, or a variable and another variable:
ASSIGNMENT OPERATORS
COMPARISON OPERATORS
 Comparison operators are used to compare two values (or variables).

 The return value of a comparison is either true or false. These values are known as Boolean

values.
LOGICAL OPERATORS
 Logical operators are used to determine the logic between variables or values. You can also

test for true or false values with logical operators.


STRINGS & ITS FUNCTIONS
JAVA STRINGS
 Strings are used for storing text.

 A String variable contains a collection of characters surrounded by double quotes

 A String in Java is actually an object, which contain methods that can perform certain

operations on strings.
Method Description Return Type
charAt() Returns the character at the specified index (position) char

compareTo() Compares two strings lexicographically int


compareToIgnoreCase() Compares two strings lexicographically, ignoring case int
differences
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of characters boolean

contentEquals() Checks whether a string contains the exact same sequence of boolean
characters of the specified CharSequence or StringBuffer

endsWith() Checks whether a string ends with the specified character(s) boolean

equals() Compares two strings. Returns true if the strings are equal, and boolean
false if not
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
indexOf() Returns the position of the first found occurrence of specified int
characters in a string
Method Description Return Type
isEmpty() Checks whether a string is empty or not boolean
lastIndexOf() Returns the position of the last found occurrence of specified characters in a string int
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular expression, and returns the matches boolean
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified characters boolean
subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence
substring() Returns a new string which is the substring of a specified string String
Method Description Return Type
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the specified value String
replace() Searches a string for a specified value, and returns a new string where the String
specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that matches the given regular String
expression with the given replacement
replaceAll() Replaces each substring of this string that matches the given regular expression String
with the given replacement
JAVA NUMBERS AND STRINGS
 If you add a number and a
 Java uses the + operator for both addition and concatenation.
string, the result will be a
 Numbers are added. Strings are concatenated.
string concatenation:
 If you add two numbers, the result will be a number:

 If you add two strings, the result will be a string concatenation:


STRINGS - SPECIAL
CHARACTERS
 Because strings must be written within quotes, Java will misunderstand this string, and generate an

error:
 The solution to avoid this problem, is to use the backslash escape character.

 The backslash (\) escape character turns special characters into string characters:
Escape sequences
PROGRAMS ON STRING
METHODS
The indexOf() method returns the index (the position) of the first occurrence of a specified text in a
string (including whitespace):

lastIndexOf(int ch) returns last index position for the given char value
STRING CONCATENATION
 The + operator can be used between strings to combine them. This is called concatenation:

 You can also use the concat() method to concatenate two strings:
SUBSTRING
 String substring(int startIndex, int endIndex)

 startIndex specifies the beginning index, and endIndex specifies the stopping point.

 returns a copy of the substring that begins at startIndex and runs to the end of the

invoking string.

 substring (1) String st=“sheela”;

 substring(1,3) [1,2]=he
The Java String class equals() method compares the two given strings based on the content of the string. If any
character is not matched, it returns false. If all characters are matched, it returns true.

public class EqualsExample


{
public static void main(String args[])
{
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
compareTo()

 Compares the given string with the current string lexicographically. It returns a positive

number, negative number, or 0.

if s1 > s2, it returns positive number

if s1 < s2, it returns negative number

if s1 == s2, it returns 0

 If first string is an empty string, the method returns a negative

 If second string is an empty string, the method returns a positive number that is the length of

the first string


public static void main(String args[])

{
String s1="hello";

String s2="hello";

String s3="meklo";

String s4="hemlo";

String s5="flag";

System.out.println(s1.compareTo(s2)); //0 because both are equal

System.out.println(s1.compareTo(s3)); //-5 because "h" is 5 times lower than "m"

System.out.println(s1.compareTo(s4)); //-1 because "l" is 1 times lower than "m"

System.out.println(s1.compareTo(s5)); //2 because "h" is 2 times greater than "f"

}
compareToIgnoreCase() :

 A positive number is returned if string 1 is greater than string 2.

 A negative number is returned if string 1 is less than string 2.

 Zero is returned if string 1 is equal to the string 2.


public class CompareToIgnoreCase {

public static void main(String argvs[]) {


String string1 = "Book";

String string2 = "book";

String string3 = "look";

String string4 = "abc";

String string5 = "BEEN";

System.out.println(string1.compareToIgnoreCase(string2));

System.out.println(string1.compareToIgnoreCase(string3));

System.out.println(string1.compareToIgnoreCase(string4));

System.out.println(string1.compareToIgnoreCase(string5));

}}
S1=B S2 =A
65<66
contains() method searches the sequence of characters in this string. It returns true if the sequence
of char values is found in this string otherwise returns false.

class ContainsExample

public static void main(String args[])

{
String name="what do you know about me";

System.out.println(name.contains("do you know"));

System.out.println(name.contains("about"));

System.out.println(name.contains("hello"));

}
The Java String class isEmpty() method checks if the input string is empty or not
true if length is 0 otherwise false.

public class IsEmptyExample


{
public static void main(String args[])
{
String s1="";
String s2="javatpoint";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
The Java String class replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

public class ReplaceExample1

public static void main(String args[])

String s1="javatpoint is a very good website";

String replaceString=s1.replace('a','e’); //replaces all occurrences of 'a' to 'e'

System.out.println(replaceString);

}
public class ReplaceStringMain

public static void main(String args[])

{ String str = "Java C C++ Java";

String oldString = "Java";

String newString = "Python";

String resultStr = str.replace(oldString, newString);

System.out.println(resultStr);

}
endsWith(): The Java String class endsWith() method checks if this string ends with a given
suffix. It returns true if this string ends with the given suffix; else returns false.

public class EndsWithExample

public static void main(String args[])

String s1="java by javatpoint";

System.out.println(s1.endsWith("t"));

System.out.println(s1.endsWith("point"));

}
 equals() method compares the two given strings based on the content of the string. If any

character is not matched, it returns false. If all characters are matched, it returns true.

 Trim(): It remove only leading and trailing spaces.


 CharAt()

String name="javat";
char ch=name.charAt(4); //returns the char value at the 4th index
System.out.println(ch);
Output :t
Greater index value-throws StringIndexOutOfBoundsException at run time
PRACTICE PROGRAMS
A person wants to name his newborn baby boy by considering his grandfather and great grandfather's names.
Newborn baby boy name length is seven characters out of these seven characters first three characters are
taken from the first three characters of grandfather's name and the last four characters are taken from the last
four characters of his great grandfather's name. Write a java program to find the newborn baby boy's name by
considering the person's grandfather and great grandfather names.

Sample input:

Person's grandfather name: Rammurthy

Person's great grandfather name: Sidhayya

Output:

Newborn baby boy's name is Ramayya


class fat2

public static void main(String arg[])

{
String st1="Rammurthy";

String st2="Sidhayya";

System.out.println(st1.substring(0,3)+st2.substring(st2.length()-4));

}
MATH FUNCTIONS IN JAVA
https://www.javatpoint.com/java-math
ARRAYS IN JAVA
ARRAYS
 Java Arrays are used to store multiple values of same datatype in a single variable, instead

of declaring separate variables for each value.

 To declare an array, define the variable type with square brackets:

String[ ] cars;

 We have now declared a variable that holds an array of strings. To insert values to it, you

can place the values in a comma-separated list, inside curly braces:

String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};


 You can access an array element by referring to the index number.
 To change the value of a specific element, refer to the index number:

String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

System.out.println(cars[0]); // Now outputs Opel instead of Volvo

 To find out how many elements an array has, use the length property:

String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length); // Outputs 4
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
class Main class Main
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int[ ] age = {12, 4, 5}; int[ ] age = {12, 4, 5};
System.out.println("Using for Loop:"); System.out.println("Using for-each Loop:");
for(int i = 0; i < age.length; i++) for(int a : age)
{ {
System.out.println(age[i]); System.out.println(a);
} }
} }
} }

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
complete array sequentially without using an index variable.
PRINT AN ARRAY USING FOR
LOOP
public class Array {

public static void main(String[ ] args) {


int[ ] array = {1, 2, 3, 4, 5};

for (int element: array) {


System.out.println(element);
}
}
}
PRINT AN ARRAY USING STANDARD
LIBRARY ARRAYS
import java.util.Arrays;

public class Array {

public static void main(String[] args) {


int[ ] array = {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(array));
}
}
PRINT A MULTI-DIMENSIONAL
ARRAY
import java.util.Arrays;

public class Array {

public static void main(String[] args) {


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

System.out.println(Arrays.deepToString(array));
}
}
MULTIDIMENSIONAL ARRAYS
 Multidimensional arrays are arrays of arrays with each element of the array holding the reference of

other arrays.

 Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows

and columns.

 To create a two-dimensional array, add each array within its own set of curly braces.

double[][] matrix = { {1.2, 4.3, 4.0}, {4.1, -1.1} };


public class multiDimensional {
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
JAGGED / RAGGED ARRAY
 Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D

array but with a variable number of columns in each row.

 In a multidimensional array, each element in each dimension has the same, fixed size as the other elements

in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size.
class TestJaggedArray{
public static void main(String[] args){
int arr[][] = new int[3][]; //declaring a 2D array with odd columns
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

for (int i=0; i<arr.length; i++){


for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
CONTROL STATEMENTS IN
JAVA
HOW TO GET INPUT FROM
USER IN JAVA
 Java Scanner class allows the user to take input from the console.

 It belongs to java.util package. It is used to read the input of primitive types like int,

double, long, short, float, and byte.


import java.util.Scanner
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
REFERENCES
 Methods -
https://www.w3resource.com/java-exercises/method/index.php

 Conditional statement -
https://www.w3resource.com/java-exercises/conditional-statement/i
ndex.php#google_vignette

 Codes in this slide -


https://github.com/DivyaMeenaSundaram/JAVA

You might also like