LEC_3
LEC_3
Outline
• Data entry in Java
• Java Methods
• Java - Modifier Types (Access Modifiers & Non-Access Modifiers)
• Java - Strings Class
• Class String Methods in Java
• Arrays - Passing Arrays to Methods
• Multidimensional Arrays
• Java Development libraries
1
Data entry in Java:
If we want to ask the user to enter data from the keyboard:
Scanner class is a ready-made class in Java, generally used to make the program
receive data from the user in addition to the possibility of converting the type of
this data and modifying it. It is very large as it consists of 9 constructors and more
than 50 functions.
To make the program receive data from the user in Java:
- import java.util.Scanner;
- Scanner input = new Scanner(System.in);
- int a = input.nextInt();
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
Method Description
2
nextDouble() Reads a double value from the user
Java Methods:
A method is a block of code which only runs when it is called. You can pass data,
Creating Method
Considering the following example to explain the syntax of a method :
public static int methodName(int a, int b) {
// body
}
Here,
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown
in the following syntax :
3
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
Example:
Write method takes two parameters n1 and n2 and returns the minimum between the
two numbers?
return min;
}
Method Calling
For using a method, it should be called. There are two ways in which a method is called
i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when −
• the return statement is executed.
• It reaches the method ending closing brace.
Following is the example to demonstrate how to define a method and how to call it :
4
Example
return min;
}
}
5
Swapping Example:
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
6
Java - Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. Java
language has a wide variety of modifiers, including the following −
Example
Access Modifiers
For classes, you can use either public or default:
Modifier Description
7
default The class is only accessible by classes in the same package. This is used
when you don't specify a modifier.
For attributes, methods and constructors, you can use the one of the
following:
Modifier Description
default The code is only accessible in the same package. This is used when you
don't specify a modifier. You will learn more about packages in
the Packages
protected The code is accessible in the same package and subclasses. You will learn
more about subclasses and superclasses in the Inheritance
Non-Access Modifiers
Modifier Description
8
final The class cannot be inherited by other classes (You will learn more
about inheritance in the Inheritance)
abstract The class cannot be used to create objects (To access an abstract class,
it must be inherited from another class. You will learn more about
inheritance and abstraction in the Inheritance and Abstraction )
For attributes and methods, you can use one of the following:
Modifier Description
static Attributes and methods belong to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods.
The method does not have a body, for example abstract void run();. The
body is provided by the subclass (inherited from). You will learn more
about inheritance and abstraction in the Inheritance and Abstraction
transient Attributes and methods are skipped when serializing the object
containing them
9
volatile The value of an attribute is not cached thread-locally, and is always read
from the "main memory"
The word static in Java Why is there a need to define something as static?
If you want to define something that is constant for all objects, define it as static.
If you want to define something inside a specific class, and you want to access it directly from
the class instead of creating an object from the class and then calling the thing from it, define
it as static
Remember that even if you declare it like a regular variable, the compiler will consider
it an object. And like any object, you can create an object of its type String with the
word new and through the constructor
Technical terms:
10
The number of characters in a string is called length.
You, as a programmer, can take advantage of the cell numbers to reach the content of
the text and do whatever you want with it.
There are many ready-made functions in Java to deal with scripts, you just have to
understand how they work and use them.
The String class is a ready-made class in Java. It contains many functions for dealing
with text content, whether to search for characters, words or sentences, split text,
change the case for characters, merge texts, etc..
We will divide class String functions into 5 basic classes as in the following table:
• Searching methods
• Substring methods
• Replacing methods
• Comparison methods
• Manipulation methods
Note !!!
String is an Immutable class, which means that when you call any function on a
String, it will not modify the content of the String that called it, but will return a
modified version of this String and the original String will remain.
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = "java";
s1.concat(" rules");
// Yes, s1 still refers to "java"
11
System.out.println("s1 refers to " + s1);
Output
s1 refers to java
Explanation:
1. The first line is pretty straightforward: create a new String “java” and refer s1 to it.
2. Next, the VM creates another new String “java rules”, but nothing refers to it. So, the
second String is instantly lost. We can’t reach it.
String Methods:
The String class has a set of built-in methods that you can use on strings.
12
Checks whether a string contains the exact
contentEquals() same sequence of characters of the boolean
specified CharSequence or StringBuffer
13
Returns the position of the last found
lastIndexOf() occurrence of specified characters in a int
string
14
Converts this string to a new character
toCharArray() char[]
array
The charAt() method returns the character at the specified index in a string.
The index of the first character is 0, the second character is 1, and so on.
Example:
System.out.println(result);
if index is negative or not less than the length of the specified string it
Throws IndexOutOfBoundsException
15
Substring Method:
public class Main {
System.out.println( s.substring(11) );
System.out.println( s.substring(11, 25) );
}
}
Output:
Java.com, best site for learning
Java.com, best
Java Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
String[] cars;
16
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
17
Create an array by using the new operator with the following syntax:
Example
Following statement declares an array variable, myList, creates an array of 10 elements
of double type and assigns its reference to myList −
The following picture represents array myList. Here, myList holds ten double values
and the indices are from 0 to 9.
18
Note:
The default value of zero is given by the array type.
- If the array type is int or long, the default value to be given to all array elements is 0.
- If the array type is double or float, the default value to be given to all array elements is 0.0.
- If the array type is String, the default value to be given to all array elements is null.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because
all of the elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays −
19
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
1.9
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5}; 2.9
3.4
20
System.out.print(array[i] + “ “);
}
}
You can invoke it by passing an array. For example, the following statement invokes
the printArray method to display 3, 1, 2, 6, 4, and 2
Example
Example2:
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
int st[]=new int[3];
21
Scanner Keyboard= new Scanner(System.in);
// Print all the array elements
for (int i=0;i<3;i++) {
st[i]=Keyboard.nextInt();
}
for (int r=0;r<3;r++) {
System.out.println("\t" + st[r]);
}
}
}
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:
22
for (int j=0;j<2;j++)
st[i][j]=Keyboard.nextInt();
}
for (int r=0;r<3;r++) {
for (int c=0;c<2;c++)
System.out.println("\t" + st[r][c]);
}
}
}
The Java Development Kit comes with many libraries which contain classes and
methods for you to use Some of these:
Library Services / Classes Applications
This package contains classes that
Ordinary Algorithmic
java.util represent common data structures
Programming
such as classes, packages, etc.
This package contains all the classes Programs that require
java.io required for input and output immediate interaction
operations. with the user
his package contains classes related to
program implementation and
monitoring, including classes that
All programs/all
java.lang handle implementation errors and
applications
some general classes. Due to its
importance, this package is included in
every program
This package contains classes that Engineering applications
java.math perform arithmetic operations with and mathematics
any accuracy requested by the user applications
23
This package contains classes that applications that require
java.sql
specialize in database operations databases
Java AWT (Abstract Window Toolkit)
is an API to develop Graphical User applications that require
java.awt
Interface (GUI) or windows-based graphical user interfaces
applications in Java.
This package extends the capabilities applications that require
java.swing
of the previous package graphical user interfaces
This package contains classes that
specialize in implementing security
applications that require
java.security measures in the program, such as user
security measures
monitoring, input maintenance, and
more
This package provides many classes to
java.net deal with networking applications in networking applications
Java
24