Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Module (Minggu 4)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Praktik Pemrograman Java

Chapter 1. Java Introduction

1.1 What is Java?


Java is a popular programming language, created in 1995. Java is
a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!

1.2 Why Use Java?


There are some reasons why Java used.
a) Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
b) It is one of the most popular programming language in the world
c) It has a large demand in the current job market
d) It is easy to learn and simple to use
e) It is open-source and free
f) It is secure, fast and powerful
g) It has a huge community support (tens of millions of developers)
h) Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
i) As Java is close to C++ and C#, it makes it easy for programmers to switch
to Java or vice versa

1.3 History of Java


The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital cable
television industry at the time. The history of Java starts with the Green Team. Java
team members (also known as Green Team), initiated this project to develop a
language for digital devices such as set-top boxes, televisions, etc. However, it was

Disusun Oleh : Kadri Yusuf [1]


Praktik Pemrograman Java

best suited for internet programming. Later, Java technology was incorporated by
Netscape.
The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.

Currently, Java is used in internet programming,


mobile devices, games, e-business solutions, etc.
Following are given significant points that describe
the history of Java.

1.4 Types of Java Applications


There are mainly 4 types of applications that can be created using Java
programming:
a. Standalone Application
Standalone applications are also known as desktop applications or
window-based applications. These are traditional software that we need
to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
b. Web Application
An application that runs on the server side and creates a dynamic page is
called a web application. Currently, Servlet, JSP, Struts, Spring,
Hibernate, JSF,etc. Technologies are used for creating web applications in
Java.
c. Enterprise Application
An application that is distributed in nature, such as banking applications,
etc. is called an enterprise application. It has advantages like high-level
security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.
d. Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile
applications.

Disusun Oleh : Kadri Yusuf [2]


Praktik Pemrograman Java

1.5 Java Platforms / Editions


There are 4 platforms or editions of Java:
a. Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such
as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes
core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.
b. Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and
enterprise applications. It is built on top of the Java SE platform. It includes
topics like Servlet, JSP, Web Services, EJB, JPA, etc.
c. Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
d. JavaFX
It is used to develop rich internet applications. It uses a lightweight user
interface API.
The estimated total pay for a Java Programmer is $87,249 per year in the
United States area, with an average salary of $81,219 per year. These numbers
represent the median, which is the midpoint of the ranges from our proprietary Total
Pay Estimate model and based on salaries collected from our users. The estimated
additional pay is $6,030 per year. Additional pay could include cash bonus,
commission, tips, and profit sharing. The "Most Likely Range" represents values that
exist within the 25th and 75th percentile of all pay data available for this role.

Prerequisite
To learn Java, you must have the basic knowledge of C/C++ programming language.
Audience
Our Java programming tutorial is designed to help beginners and professionals.
Problem
We assure that you will not find any problem in this Java tutorial. However, if there
is any mistake, please post the problem in the contact form.

Disusun Oleh : Kadri Yusuf [3]


Praktik Pemrograman Java

Chapter 2. Java Getting Started

2.1 Java Install


In Some PCs might have Java already installed. To check if you have Java
installed on a Windows PC, search in the start bar for Java or type the following in
Command Prompt (cmd.exe):

If Java is installed, you will see something like this (depending on version):

If you do not have Java installed on your computer, you can download it for free
at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is possible
to write Java in an Integrated Development Environment, such as IntelliJ IDEA,
Netbeans or Eclipse, which are particularly useful when managing larger collections
of Java files.

2.2 Setup for Windows


To install Java on Windows:
1. Go to "System Properties" (Can be found on Control Panel > System and
Security > System > Advanced System Settings)
2. Click on the "Environment variables" button under the "Advanced" tab
3. Then, select the "Path" variable in System variables and click on the "Edit"
button
4. Click on the "New" button and add the path where Java is installed, followed
by \bin. By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If
nothing else was specified when you installed it). In that case, You will have
to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
5. At last, open Command Prompt (cmd.exe) and type java -version to see if Java
is running on your machine

Disusun Oleh : Kadri Yusuf [4]


Praktik Pemrograman Java

Disusun Oleh : Kadri Yusuf [5]


Praktik Pemrograman Java

Disusun Oleh : Kadri Yusuf [6]


Praktik Pemrograman Java

Disusun Oleh : Kadri Yusuf [7]


Praktik Pemrograman Java

2.3 Java Quickstart


In Java, every application begins with a class name, and that class must match
the filename.
Let's create our first Java file, called Main.java, which can be done in any text editor
(like Notepad).
The file should contain a "Hello World" message, which is written with the following
code:

Don't worry if you don't understand the code above - we will discuss it in detail in
later chapters. For now, focus on how to run the code above.
Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe),
navigate to the directory where you saved your file, and type "javac Main.java":

This will compile your code. If there are no errors in the code, the command prompt
will take you to the next line. Now, type "java Main" to run the file:

Disusun Oleh : Kadri Yusuf [8]


Praktik Pemrograman Java

Chapter 3. Data Type, Variable and Conversion

3.1 The Data Type


Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean.
3.1.1 Integer types
T y pe Si z e R a ng e
byte 8 bits —128 to 127
short 16 bits —32,768 to 32,767
int 32 bits —2,147,483,648 to 2,147,483,647
long 64 bits —9223372036854775808 to 9223372036854775807
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.
3.1.2 Floating-point
This is used for numbers with a decimal part. There are two floating-point
types: float (32 bits, single-precision) and double (64bits, double-precision).
class Area
{
public static void main(String args[])
{
double pi, r, a;

Disusun Oleh : Kadri Yusuf [9]


Praktik Pemrograman Java

r = 10.8; // radius of circle


pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Output:
Area of circle is 366.24
3.1.3 Char
The char type is used for individual characters. Because Java uses the Unicode
character set, the char type has 16 bits of precision, unsigned.
class CharDemo
2nd Module (Java Complete Reference:Herbert Schield)
Mangala KB, Dept of CSE,CiTech Page 8
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
output:
ch1 and ch2: X Y
// char variables behave like integers.
class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
output:

Disusun Oleh : Kadri Yusuf [10]


Praktik Pemrograman Java

ch1 contains X
ch1 is now Y

3.1.4 Boolean
The boolean type can have one of two values, true or false.
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
}
output:
b is false
b is true
This is executed.
10 > 9 is true

3.2 Variable
A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and
the set of operations that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form
of a variable declaration −

Here data type is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated
list.

Disusun Oleh : Kadri Yusuf [11]


Praktik Pemrograman Java

Following are valid examples of variable declaration and initialization in Java −


Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

This chapter will explain various variable types available in Java Language. There are
three kinds of variables in Java −
• Local variables
• Instance variables
• Class/Static variables

3.2.1 Local Variables


• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or
block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.

public class Test {


public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}

Disusun Oleh : Kadri Yusuf [12]


Praktik Pemrograman Java

}
This will produce the following result −

Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the
time of compilation.

public class Test {


public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
This will produce the following error while compiling it −

Output
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
3.2.2 Instance Variables
• Instance variables are declared in a class, but outside a method, constructor or
any block.
• When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
• Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
• Instance variables can be declared in class level before or after use.

Disusun Oleh : Kadri Yusuf [13]


Praktik Pemrograman Java

• Access modifiers can be given for instance variables.


• The instance variables are visible for all methods, constructors and block in
the class. Normally, it is recommended to make these variables private (access
level). However, visibility for subclasses can be given for these variables with
the use of access modifiers.
• Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.
• Instance variables can be accessed directly by calling the variable name inside
the class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified name.
ObjectReference.VariableName.

Example
Live Demo
import java.io.*;
public class Employee {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

Disusun Oleh : Kadri Yusuf [14]


Praktik Pemrograman Java

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This will produce the following result −

Output
name : Ransika
salary :1000.0

3.2.3 Class/Static Variables


• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
• Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the
program stops.
• Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
• Default values are same as instance variables. For numbers, the default value
is 0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
• Static variables can be accessed by calling with the class name
ClassName.VariableName.
• When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final,
the naming syntax is the same as instance and local variables.

Example

Disusun Oleh : Kadri Yusuf [15]


Praktik Pemrograman Java

import java.io.*;
public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
This will produce the following result −

Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be
accessed as Employee.DEPARTMENT

Disusun Oleh : Kadri Yusuf [16]


Praktik Pemrograman Java

3.3 Conversion
Type conversion is simply the process of converting data of one data type into
another. This process is known as type conversion, typecasting, or even type coercion.
The Java programming language allows programmers to convert both primitive as
well as reference data types
3.3.1 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.

Example:
class GFG {

// Main driver method


public static void main(String[] args)
{
int i = 100;

// Automatic type conversion


// Integer to long type
long l = i;

// Automatic type conversion


// long to float type
float f = l;

// Print and display commands


System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);

Disusun Oleh : Kadri Yusuf [17]


Praktik Pemrograman Java

}
}

Output:
Int value 100
Long value 100
Float value 100.0
3.3.2 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. This is useful for incompatible data types
where automatic conversion cannot be done. Here, the target type specifies the
desired type to convert the specified value to.

char and number are not compatible with each other. Let’s see when we try to
convert one into another.

Example:
// Java program to illustrate Incompatible data Type
// for Explicit Type Conversion

// Main class
public class GFG {

// Main driver method


public static void main(String[] argv)
{

// Declaring character variable


char ch = 'c';
// Declaringinteger variable
int num = 88;
// Trying to insert integer to character
ch = num;
}
}

Disusun Oleh : Kadri Yusuf [18]


Praktik Pemrograman Java

Output: An error will be generated

This error is generated as an integer variable takes 4 bytes while character datatype
requires 2 bytes. We are trying to plot data from 4 bytes into 2 bytes which is not
possible.
How to do Explicit Conversion?
Example:
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
// fractional part lost
System.out.println("Int value " + i);
}
}

Disusun Oleh : Kadri Yusuf [19]


Praktik Pemrograman Java

Output
Double value 100.04
Long value 100
Int value 100
Note: While assigning value to byte type the fractional part is lost and is reduced to
modulo 256(range of byte).

// Java Program to Illustrate Conversion of


// Integer and Double to Byte
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring byte variable
byte b;
// Declaring and initializing integer and double
int i = 257;
double d = 323.142;
// Display message
System.out.println("Conversion of int to byte.");
// i % 256
b = (byte)i;
// Print commands
System.out.println("i = " + i + " b = " + b);
System.out.println(
"\nConversion of double to byte.");
// d % 256
b = (byte)d;

// Print commands
System.out.println("d = " + d + " b= " + b);
}
}
Output
Conversion of int to byte.
i = 257 b = 1

Conversion of double to byte.

Disusun Oleh : Kadri Yusuf [20]


Praktik Pemrograman Java

d = 323.142 b= 67

Disusun Oleh : Kadri Yusuf [21]


Praktik Pemrograman Java

Chapter 4. String Data Type

4.1 String Data Type


In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
Here, we have created a string variable named type. The variable is initialized with
the string Java Programming.
Below is an example of a String in Java:
public class StringExample {
// Main Function
public static void main(String args[])
{
String str = new String("example");
System.out.println(str);
}
}

Output
Example

4.2 String Literal


A combination of characters is a string. Strings in Java are instances of the class
String. Strings are not simple arrays of characters as they are in C or C++, although
they do have many array like characteristics (for example, you can test their length
and add and delete individual characters as if they were arrays). Because string
objects are real objects in Java, they have methods that enable you to combine, test,
and modify strings very easily.
String literals consist of a series of characters inside double quotes:
“Hi, I’m a string literal.”
“” //an empty string
Strings can contain character constants such as newline, tab, and Unicode characters:
“A string with a \t tab in it”
“Nested strings are \”strings inside of\” other strings”
“This string brought to you by Java\u2122”

Disusun Oleh : Kadri Yusuf [22]


Praktik Pemrograman Java

In the last example, the Unicode code sequence for \u2122 produces a trademark
symbol (™)

When you use a string literal in your Java program, Java automatically creates an
instance of the class String for you with the value you give it. Strings are unusual in
this respect; the other literals do not behave in this way (none of the primitive base
types are actual objects), and usually creating a new object involves explicitly
creating a new instance of a class.

4.3 Special Characteristics in Java


Some characters, like the quotation mark, are part of the Java language; others,
like the new line character, are simply a regular letter – the letter n in this case.
However, when combined with the backslash symbol, these special characters tell
the compiler to treat them differently than it usually would. When the compiler
encounters \n in the text, it understands that this is not just a symbol and a letter to
display in the console, but rather, a special command to start a new line – equivalent
to pressing Enter.
For example, this example Java code shows how to use the newline special character
\n to to display the lyrics of a song:

public class NewLineExample {


public static void main(String[] args) {
String lyric = "Wave after wave will flow with the tide\nAnd bury the world as it
does\nTide after tide will flow and recede\nLeaving life to go on as it was);
System.out.println(lyric);
}
}

The code above outputs our lyrics as four distinct lines:


Wave after wave will flow with the tide
And bury the world as it does
Tide after tide will flow and recede
Leaving life to go on as it was

Here is the full list of special characters in Java:

\t – tab
\b – backspace (a step backward in the text or deletion of a single character)
\n – new line
\r – carriage return

Disusun Oleh : Kadri Yusuf [23]


Praktik Pemrograman Java

\f – form feed
\’ – single quote
\” – double quote
\\ – backslash

4.3 Java String Operations


Java String provides various methods to perform different operations on strings. We
will look into some of the commonly used string operations.

4.3.1 Get length of a String


To find the length of a string, we use the length() method of the String. For example,
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
System.out.println("Length: " + length);
}
}

Output:
String: Hello! World
Length: 12
In the above example, the length() method calculates the total number of characters
in the string and returns it.

4.3.2 Join Two Java Strings


We can join two strings in Java using the concat() method. For example,
class Main {
public static void main(String[] args) {
String first = "Java "; // create first string
System.out.println("First String: " + first);
String second = "Programming"; // create second
System.out.println("Second String: " + second);
// join two strings

Disusun Oleh : Kadri Yusuf [24]


Praktik Pemrograman Java

String joinedString = first.concat(second);


System.out.println("Joined String: " + joinedString);
}
}

Output:
First String: Java
Second String: Programming
Joined String: Java Programming
In the above example, we have created two strings named first and second. Notice
the statement,

String joinedString = first.concat(second);


Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.

We can also join two strings using the + operator in Java. To learn more, visit Java
String concat().

Disusun Oleh : Kadri Yusuf [25]


Praktik Pemrograman Java

4.3.3 Compare two Strings


In Java, we can make comparisons between two strings using the equals() method.
For example,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}

Output

Strings first and second are equal: true


Strings first and third are equal: false

In the above example, we have created 3 strings named first, second, and third. Here,
we are using the equal() method to check if one string is equal to another.

The equals() method checks the content of strings while comparing them. To learn
more, visit Java String equals().

4.3.4 Methods of Java String


Besides those mentioned above, there are various string methods present in Java.
Here are some of those methods:

Disusun Oleh : Kadri Yusuf [26]


Praktik Pemrograman Java

Methods Description

contains() checks whether the string contains a substring

substring() returns the substring of the string

join() join the given strings using the delimiter

replace() replaces the specified old character with the specified new chara

replaceAll() replaces all substrings matching the regex pattern

replaceFirst() replace the first matching substring

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

compareTo() compares two strings in the dictionary order

compareToIgnoreCase() compares two strings ignoring case differences

trim() removes any leading and trailing whitespaces

format() returns a formatted string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

valueOf() returns the string representation of the specified argument

toCharArray() converts the string to a char array

Disusun Oleh : Kadri Yusuf [27]


Praktik Pemrograman Java

matches() checks whether the string matches the given regex

startsWith() checks if the string begins with the given string

endsWith() checks if the string ends with the given string

isEmpty() checks whether a string is empty of not

intern() returns the canonical representation of the string

contentEquals() checks whether the string is equal to charSequence

hashCode() returns a hash code for the string

subSequence() returns a subsequence from the string

Frequently Asked Questions


1. What are strings in Java?
Strings are the types of objects which can store characters as elements.

2. Why string objects are immutable in Java?


Because java uses the concept of string literal. Suppose there are 5 reference
variables, all refer to one object “Sachin”. If one reference variable changes the value
of the object, it will be affected by all the reference variables. That is why string
objects are immutable in Java.

3. Why Java uses the concept of string literal?


To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

Disusun Oleh : Kadri Yusuf [28]


Praktik Pemrograman Java

References:
1. https://www.javatpoint.com/history-of-java
2. Java Getting Started (w3schools.com)
3. Source : https://www.glassdoor.com/Salaries/java-programmer-salary-
SRCH_KO0,15.htm
4. https://www.tutorialspoint.com/java/java_variable_types.htm
5. Java String (With Examples) (programiz.com)

Disusun Oleh : Kadri Yusuf [29]

You might also like