0% found this document useful (0 votes)
2 views

LEC_3

The document provides an overview of Java programming concepts, including data entry using the Scanner class, method creation and calling, modifier types, and the String class. It details how to read user input, define and invoke methods, and explains access and non-access modifiers in Java. Additionally, it covers the String class methods and array handling in Java, including declaration, accessing elements, and modifying arrays.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

LEC_3

The document provides an overview of Java programming concepts, including data entry using the Scanner class, method creation and calling, modifier types, and the String class. It details how to read user input, define and invoke methods, and explains access and non-access modifiers in Java. Additionally, it covers the String class methods and array handling in Java, including declaration, accessing elements, and modifying arrays.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Lecture 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();

import java.util.Scanner; // import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + 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

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

2
nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads an int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

Java Methods:
A method is a block of code which only runs when it is called. You can pass data,

known as parameters, into a method.

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?

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

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

public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

This will produce the following result −


Output
Minimum value = 6

5
Swapping Example:

public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}

public static void swapFunction(int a, int b) {


System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

// 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 −

• Java Access Modifiers


• Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The
modifier precedes the rest of the statement, as in the following example.

Example

public class className {


// ...
}

private boolean myFlag;


static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;

public static void main(String[] arguments) {


// body of method
}

Access Modifiers
For classes, you can use either public or default:

Modifier Description

public The class is accessible by any other class

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

public The code is accessible for all classes

private The code is only accessible within the declared class

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

For classes, you can use either final or abstract:

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

final Attributes and methods cannot be overridden/modified

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

synchronized Methods can only be accessed by one thread at a time

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

Java - Strings Class


Strings, which are widely used in Java programming, are a sequence of characters. In
Java programming language, strings are treated as objects.

The most direct way to create a string is to write −


String greeting = "Hello world!";

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.

The number of the digit is called index.

If we take a part of the String, this part is called a substring.

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.

Class String Methods in Java

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.

The reference variable s1 still refers to the original string “java”.

String Methods:
The String class has a set of built-in methods that you can use on strings.

Method Description Return Type

Returns the character at the specified index


charAt() char
(position)

Returns the Unicode of the character at the


codePointAt() int
specified index

Returns the Unicode of the character before


codePointBefore() int
the specified index

Returns the number of Unicode values


codePointCount() int
found in a string.

compareTo() Compares two strings lexicographically int

Compares two strings lexicographically,


compareToIgnoreCase() int
ignoring case differences

Appends a string to the end of another


concat() String
string

Checks whether a string contains a


contains() boolean
sequence of characters

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

Returns a String that represents the


copyValueOf() String
characters of the character array

Checks whether a string ends with the


endsWith() boolean
specified character(s)

Compares two strings. Returns true if the


equals() boolean
strings are equal, and false if not

Compares two strings, ignoring case


equalsIgnoreCase() boolean
considerations

Returns a formatted string using the


format() specified locale, format string, and String
arguments

Encodes this String into a sequence of


getBytes() bytes using the named charset, storing the byte[]
result into a new byte array

Copies characters from a string to an array


getChars() void
of chars

hashCode() Returns the hash code of a string int

Returns the position of the first found


indexOf() occurrence of specified characters in a int
string

Returns the canonical representation for


intern() String
the string object

isEmpty() Checks whether a string is empty or not boolean

13
Returns the position of the last found
lastIndexOf() occurrence of specified characters in a int
string

length() Returns the length of a specified string int

Searches a string for a match against a


matches() regular expression, and returns the boolean
matches

Returns the index within this String that is


offsetByCodePoints() offset from the given index by int
codePointOffset code points

regionMatches() Tests if two string regions are equal boolean

Searches a string for a specified value, and


replace() returns a new string where the specified String
values are replaced

Replaces the first occurrence of a substring


replaceFirst() that matches the given regular expression String
with the given replacement

Replaces each substring of this string that


replaceAll() matches the given regular expression with String
the given replacement

split() Splits a string into an array of substrings String[]

Checks whether a string starts with


startsWith() boolean
specified characters

Returns a new character sequence that is a


subSequence() CharSequence
subsequence of this sequence

Returns a new string which is the substring


substring() String
of a specified string

14
Converts this string to a new character
toCharArray() char[]
array

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

Removes whitespace from both ends of a


trim() String
string

Returns the string representation of the


valueOf() String
specified value

Searching Methods: Java String charAt() Method

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:

String myStr = "Hello";

char result = myStr.charAt(0);

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 {

public static void main(String[] args) {

String s = "welcome to Java.com, best site for learning";

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.

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

String[] cars;

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

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in 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.

Change an Array Element


To change the value of a specific element, refer to the index number:

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

cars[0] = "Opel";

System.out.println(cars[0]);

// Now outputs Opel instead of Volvo

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:

arrayRefVar = new dataType[arraySize];


The above statement does two things −
• It creates an array using new dataType[arraySize].
• It assigns the reference of the newly created array to the variable
arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array
to the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];

Example
Following statement declares an array variable, myList, creates an array of 10 elements
of double type and assigns its reference to myList −

double[] myList = new double[10];

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 −

public class TestArray {

public static void main(String[] args) { 1.9


double[] myList = {1.9, 2.9, 3.4, 3.5};
2.9

// Print all the array elements 3.4


for (int i = 0; i < myList.length; i++) { 3.5
System.out.println(myList[i] + " ");
Total is 11.7
}
Max is 3.5
// 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++) {

19
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

The foreach Loops


Example
The following code displays all the elements in the array myList −

public class TestArray {

1.9
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5}; 2.9
3.4

// Print all the array elements 3.5


for (double element : myList) {
System.out.println(element);
}
}
}

Passing Arrays to Methods


Just as you can pass primitive type values to methods, you can also pass arrays to
methods. For example, the following method displays the elements in an int array –
Example

public static void printArray(int[] array) {


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

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

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method


A method may also return an array. For example, the following method returns an array
that is the reversal of another array –
Example 1:

public static int[ ] reverse(int[ ] list) {


int[ ] result = new int[list.length];

for (int i = 0, j = result.length – 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}

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:

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

If we want to ask the user to enter data from the keyboard:


package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
int st[][]=new int[3][2];
Scanner Keyboard= new Scanner(System.in);
// Print all the array elements
for (int i=0;i<3;i++) {

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

You might also like