Java Java Basics For Beginners
Java Java Basics For Beginners
The list is long. I have only added the first few items from the list to give you
an overview of how it looks and what you will find in there. If you want to
see what Jshell is currently doing, type in the –v command and see how it
works. You can assign values in Java to variables, which are sequences of
different characters. I will now create a variable of type integer and then
assign it a value of 55. See how to do that.
jshell> int a=55
a ==> 55
jshell>
You can see that the command was successfully executed, and a value was
assigned to the variable. Line a ==>55 lets us know that the value 5 has been
assigned to the variable that you have just created. You can declare as many
variables as you want. I will now create another variable with a different
value.
jshell> int x=556
x ==> 556
jshell>
As long as you do not close the jshell session, the variables will exist, and
their values will remain intact. We can use them further on. Now let us add
the two variables and see the output. I will use the + operator to get the sum
of the two variables in the jshell. The process is the same as it is in plain
mathematics. See the following piece of code.
jshell> int a=55
a ==> 55
jshell> a + x
$4 ==> 611
jshell>
I have added two variables, but I have not stored the result of the two in a
third variable. That’s why jshell has created a scratch variable for storing the
result of the two and printing the same inside the log. However, that variable
can never be used in the later statements because it lacks a name. Now
everything seems fine. You can create variables and execute operations
perfectly. Anything that you can write in Java can also be written in jshell
and then executed as well.
The basic building blocks of Java are known as classes. These are pieces of
code that are modeled on real-world objects as well as events. Java classes
contain different types of members; those that are modeled to states are
known as class variables, and those that are modeled on behavior are called
methods. Class variables are also known as properties and fields. Now I will
declare the first string variable in the following section.
jshell> String msg = "I am starting to learn Java development."
msg ==> "I am starting to learn Java development."
jshell>
I have declared a variable of String type and then named it as msg. You can
name it whatever you like. The String class carries several methods that you
may call for text modification purposes. I will call one method to turn the
piece of text into upper case in the next example.
jshell> String msg = "I am starting to learn Java development."
msg ==> "I am starting to learn Java development."
jshell> msg.toUpperCase()
$7 ==> "I AM STARTING TO LEARN JAVA DEVELOPMENT."
jshell>
The final statement is known as the String method. It has turned the piece of
text into uppercase. Let us see what happens when you type in something that
is not recognized by Java.
jshell> msg.toMultiverse()
| Error:
| cannot find symbol
| symbol: method toMultiverse()
| msg.toMultiverse()
| ^--------------^
jshell>
JShell will tell you in clear words that it does not recognize the command. It
will not recognize plain text either. You can create more methods as well.
jshell> String creatingHello(String x){
...> return "Hello " + x;
...> }
| created method creatingHello(String)
jshell> creatingHello(msg)
$9 ==> "Hello I am starting to learn Java development."
jshell>
If you need to see the variables that you already have declared in the JShell
play session, you may do so by the execution of the vars command. The
command will display a list of all the variables that I have just created in the
shell.
jshell> /vars
| int i = 42
| int a = 55
| int x = 556
| int $4 = 611
| String text = "I am starting to learn Java development."
| String msg = "I am starting to learn Java development."
| String $7 = "I AM STARTING TO LEARN JAVA
DEVELOPMENT."
| String $9 = "Hello, I am starting to learn Java development."
jshell>
Java is a compiled language that allows you to reuse the code once it
has been developed.
Let us see how you can create a variable and store in it a number to display.
public class JavaX {
public static void main(String[] args) {
int tezNum = 555;
System.out.println(tezNum);
}
}
555
You can see that I have changed the keyword from string to int to store and
display a number.
Variable Without Assignment
You can create a variable, but you no longer have to assign it during the
creation step. You can do that after it has been created. This works when you
are building some complex pieces of code.
public class JavaX {
public static void main(String[] args) {
int tezNum;
tezNum = 555;
System.out.println(tezNum);
}
}
555
There is a common problem with variables. If you assign an existing variable
a new value, it tends to overwrite the existing value.
public class JavaX {
public static void main(String[] args) {
int tezNum = 555;
tezNum = 777;
System.out.println(tezNum);
}
}
777
If you have already developed a code and you are concerned about someone
overwriting the existing values, you can use the final keyword or the constant
keyword to keep the values of variables from changing. The keywords final
and constant mean read-only and unchangeable.
public class JavaX {
public static void main(String[] args) {
final int tezNum = 555;
tezNum = 777;
System.out.println(tezNum);
}
}
555.555
The following example shows how you can create a char variable and assign
a value to the same.
public class JavaX {
public static void main(String[] args) {
char tezLetter = 'M';
System.out.println(tezLetter);
}
}
M
Here is an example of how you can create a Boolean variable and assign
value to that.
public class JavaX {
public static void main(String[] args) {
boolean tezBool = true;
System.out.println(tezBool);
}
}
true
Chapter Three: Java Data Types
Data types in Java are divided into a couple of groups. One group is named as
primitive data types like short, bytes, float, long, boolean, double, char, and
int. The second group is called non-primitive data types like String, Classes,
and Arrays.
Primitive Data Types
The primitive data type generally specifies the type and size of the values of
the variable. It does not contain any additional methods. See what the
primitive data types are and how they are described.
The first primitive data type is called byte. Its size is 1 byte and it
stores all whole numbers starting from -128 and ending on 127.
public class JavaX {
public static void main(String[] args) {
byte tezNum = 120;
System.out.println(tezNum);
}
}
120
The second primitive data type is named as short. Its size is 2 bytes
and it stores all whole numbers starting from -32,768 and ending on
32,767.
public class JavaX {
public static void main(String[] args) {
short tezNum = 30000;
System.out.println(tezNum);
}
}
30000
The third primitive data type is called int. Its size is 4 byte and it
stores all whole numbers starting from -2,147,483,648 and ending on
2,147,483,647.
public class JavaX {
public static void main(String[] args) {
int tezNum = 2200000;
System.out.println(tezNum);
}
}
2200000
The fourth primitive data type is long. Its size is 8 bytes and it stores
all whole numbers starting from -9,223,372,036,854,775,808 and
ending on 9,223,372,036,854,775,807.
public class JavaX {
public static void main(String[] args) {
long tezNum = 300000000;
System.out.println(tezNum);
}
}
300000000
The fifth primitive data type is called float. Its size is 4 bytes and it
stores all fractional numbers that should be sufficient to store six to
seven decimal digits.
public class JavaX {
public static void main(String[] args) {
float tezNum = 4.45f;
System.out.println(tezNum);
}
}
4.45
The sixth primitive data type is called double. Its size is 8 bytes and it
stores all fractional numbers starting from 15 decimal digits.
public class JavaX {
public static void main(String[] args) {
double tezNum = 24.45d;
System.out.println(tezNum);
}
}
24.45
The seventh primitive data type is called boolean. Its size is 1 bit, and
it stores only true and false values.
The eighth primitive data type is called char. Its size is 2 bytes, and it
stores a single character or letter or ASCII values.
The String datatype in Java is so much integrated into the language that
programmers dub it as the ninth type. A string is a non-primitive data type
because it alludes to an object. The String object carries multiple methods
that are handy in performing different types of operations in strings.
Non-Primitive Data Types
Non-primitive data types are also known as reference types because they tend
to refer to objects. The major difference between the two data types is that
primitive types have been pre-defined in Java. However, the non-primitive
data types are created by programmers. Except for String, Java does not pre-
define any of them.
Non-primitive data types are used to call different methods to perform a
number of operations, while primitive data types cannot do that. A primitive
data type has a value, while a non-primitive data type may be null at times.
You always have to start a primitive data type with a lowercase letter, while
you always have to start a non-primitive data type with an uppercase letter.
This also works well for differentiating different data types.
Java Type Casting
Type casting happens when you assign a certain value of a primitive data
type to another one. There are two casting types in Java. The first type is
known as Widening Casting, used to convert a smaller type into a bigger type
size.
The second type is the narrowing casting type that happens manually. It is
used to convert a bigger type into a smaller type.
You can do widening casting when you pass a smaller size data type to a
bigger size data type.
public class JavaX {
public static void main(String[] args) {
int tezInt = 19;
double tezDouble = tezInt; // This is an example of Automatic
casting: I am converting int into double
System.out.println(tezInt);
System.out.println(tezDouble);
}
}
19
19.0
Now let us check out how narrowing casting works. It needs to be done
manually by putting a data type in parentheses before the value.
public class JavaX {
public static void main(String[] args) {
double tezDouble = 19; // This is an example of manual casting: I
am converting double into int
int tezInt = (int) tezDouble;
System.out.println(tezDouble);
System.out.println(tezInt);
}
}
19.0
19
Chapter Four: Java Operators & Java Strings
Operators are used to perform different operations on certain values and
variables. For example, you can use the + operator to combine two values.
public class JavaX {
public static void main(String[] args) {
int a = 150 + 500;
System.out.println(a);
}
}
650
The + operator is used for adding two values as it did in the above example, it
may be used to add a variable and a value. It may also be used to pair up a
variable with another variable.
public class JavaX {
public static void main(String[] args) {
int summing1 = 1000 + 10;
int summing2 = summing1 + 550;
int summing3 = summing2 + summing2;
System.out.println(summing1);
System.out.println(summing2);
System.out.println(summing3);
}
}
1010
1560
3120
Arithmetic Operators
One is addition. You have seen how it works in the above example. The
second arithmetic operator is subtraction. It is used to extract one value from
another. I will use the same example to show how this one works.
public class JavaX {
public static void main(String[] args) {
int summing1 = 1000 - 10;
int summing2 = summing1 - 550;
int summing3 = summing2 - 11;
System.out.println(summing1);
System.out.println(summing2);
System.out.println(summing3);
}
}
990
440
429
The third arithmetic operator is for multiplication of two values. See how it
works.
public class JavaX {
public static void main(String[] args) {
int xx = 50;
int yy = 30;
System.out.println(xx * yy);
}
}
1500
The fourth arithmetic operator is about division of two values. One value is
divided by another one to get the result.
public class JavaX {
public static void main(String[] args) {
int xx = 48;
int yy = 12;
System.out.println(xx / yy);
}
}
4
The following arithmetic operator is used to calculate the modulus of the
numbers.
public class JavaX {
public static void main(String[] args) {
int xx = 50;
int yy = 12;
System.out.println(xx % yy);
}
}
2
This arithmetic operator will increment of the value by one number.
public class JavaX {
public static void main(String[] args) {
int xx = 50;
++xx;
System.out.println(xx);
}
}
51
The arithmetic operator -- is used to cut down the value of the variable by a
single number. See the following example.
public class JavaX {
public static void main(String[] args) {
int xx = 50;
--xx;
System.out.println(xx);
}
}
49
All the code is the same except the operator. It has decreased the number one.
The operators are very useful and almost necessary to use in Java. They are
integral to performing important mathematical calculations.
Java Strings
You can use Java strings to store pieces of text. A string may carry a
collection of different characters that are surrounded by double-quotes. In the
next example, I will create a string variable and then assign it a value.
public class JavaX {
public static void main(String[] args) {
String msg = "Strings are the most commonly used data type in
Java and other programming languages.";
System.out.println(msg);
}
}
Strings are the most commonly used data type in Java and other
programming languages.
In the world of Java, a string is generally used in the form of an object. It
contains certain methods that tend to perform many operations regarding
strings. You can find the total length of a string by using the length() method.
public class JavaX {
public static void main(String[] args) {
String msg = "Strings are the most commonly used data type in
Java and other programming languages.";
System.out.println(msg);
System.out.println("the length of the above mentioned string is : " +
msg.length());
}
}
Strings are the most commonly used data type in Java and other
programming languages.
the length of the above-mentioned string is: 84
String Methods
The string is amazing in the sense that you can find a wide range of methods
to experiment with the pieces of text you add to your code. In the next
example, I will experiment with the upper case and lower case methods to
change the case of the code.
public class JavaX {
public static void main(String[] args) {
String msg = "Strings are the most commonly used data type in
Java and other programming languages.";
System.out.println(msg.toUpperCase());
System.out.println(msg.toLowerCase());
}
}
You can find a certain character inside of a string. The indexOf() string
method will return the index number of the very first occurrence of a specific
text inside a string. The method applies to whitespaces.
public class JavaX {
public static void main(String[] args) {
String msg = "Strings are the most commonly used data type in
Java and other programming languages.";
System.out.println(msg.indexOf("Java"));
}
}
48
The index number starts at zero, which is why Java counts the index position
from zero and goes onward.
Concatenation Process
You can use the addition operator to add one string to another. This may
sound odd, but it is possible. The + operator adds not only two numbers but
also two strings as well. The process of adding one string into another is
called string concatenation. The method is useful, especially when you have
to take the input from users and combine it so that it makes sense when you
store it in the database. It refines raw input and makes it readable. The
following example will help explain how you can use the concatenation
method to combine strings.
public class JavaX {
public static void main(String args[]) {
String fName = "Astral";
String lName = "Tree";
System.out.println("My full name is " + fName + " " + lName + ".
You can call me Astro in short.");
}
}
String is the most useful data type in "Java." It offers many methods
to do experiments with.
There is an escape character \b that performs the function of the backspace
key on the computer keyboard. It will delete one character to the back of its
position. You have to place it right after the letter you want to do away with.
Java Mathematics
Java math has several methods that help you perform many mathematical
tasks when you are dealing with numbers. The first method to do
mathematical functions helps you find the highest value of two numbers.
public class JavaX {
public static void main(String[] args) {
System.out.println(Math.max(1444, 55));
}
}
1444
You can use the mini method to find out the lowest number of the two. See
how it works. I will use the same code example. The only difference is that I
will replace max with min keyword.
public class JavaX {
public static void main(String[] args) {
System.out.println(Math.min(1444, 55));
}
}
55
Java Arrays
Java offers a specific data structure, the array, to programmers. Arrays store
fixed-size collections of the same types. They are written and stored in a
proper sequence. An array is defined as a data collection. However, it is more
appropriate to consider it a collection of variables of the same type. Instead of
declaring individual variables like number0, number1, and number50, you
need to declare one variable in the array like a number[0] for the
representation of individual variables.
Declaration of Array Variables
When you want to use a specific array in a particular program, you need to
declare a variable for referencing an array. You also need to specify the array
type that the variable can refer to.
When you are processing the elements of an array, you often need to use the
for loop or the foreach loop because all the elements of the array share the
same type. The size of the array is also clearly known.
public class TestingTheArray {
2.9
5.9
6.4
6.5
Here is the total of the array: 21.700000000000003
The Maximum value of the array is 6.5
Here is the function of the for loop in Java arrays. The for loop will print all
the elements of the array.
public class TestingTheArray {
2.9
5.9
6.4
6.5
Java ArrayList
The ArrayList in Java is a class that is used for the resizable array. You can
use the java.util package to find the ArrayList class. There is a difference
between the Java built-in array and the ArrayList class. The size of the array
cannot be modified at all. If you have built a program that demands that you
add or remove certain elements in an array, you need to have a custom array.
ArrayList allows you to add or remove as many elements from an array as
you need to.
Adding Items
The ArrayList class carries a number of useful methods. If you need to add
elements to the ArrayList class, you can use add() method.
import java.util.ArrayList;
}
}
}
}
12
Looping ArrayLists
You can create a loop through the arraylist. The for loop will iterate through
all the elements and display them neatly on the screen. You also can add to
the code the size() method to specify the number of times you have looped
through the arraylist.
import java.util.ArrayList;
pumpkin
tomato
ginger
potato
okra
garlic
onion
cabbage
cilantro
radish
carrot
egg plant
You also can use the for-each loop to iterate through the ArrayList. The result
with the same but the method to reach that result is different.
import java.util.ArrayList;
pumpkin
tomato
ginger
potato
okra
garlic
onion
cabbage
cilantro
radish
carrot
egg plant
I have used strings as objects in the above examples. You can use other types
as well. A string is an object but never a primitive type. To use different other
types like int, you need to specify the class Integer. You also can use
Boolean, Character, and Double etc. You can create the ArrayList for storing
numbers like adding elements of different types like Integers.
import java.util.ArrayList;
7
14
21
28
35
42
Sorting
There is another useful class in java.until package. It is known as Collections
class. It includes sort() method to sort out lists alphabetically or numerically.
import java.util.ArrayList;
import java.util.Collections;
cabbage
carrot
cilantro
egg plant
garlic
ginger
okra
onion
potato
pumpkin
radish
tomato
Similarly, you can sort out an arraylist of numbers.
import java.util.ArrayList;
import java.util.Collections;
Collections.sort(TezNumbers);
19
23
32
39
48
84
LinkedList
Here is an example of the linked list that is almost identical to arraylist.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> vegetables = new LinkedList<String>();
vegetables.add( " pumpkin " );
vegetables.add( " tomato " );
vegetables.add( " ginger " );
vegetables.add( " potato " );
vegetables.add( " okra " );
vegetables.add( " garlic " );
vegetables.add( " onion " );
vegetables.add( " cabbage " );
vegetables.add( " cilantro ");
vegetables.add( " radish ");
vegetables.add( " carrot ");
vegetables.add( " eggplant ");
System.out.println(vegetables);
}
}
}
}
pumpkin
pumpkin
tomato
egg plant
egg plant
garlic
Hash Map
A hash map allows you to add items to the code in the form of key-value
pairs. You can later on access them. You can use one object as key to another
value known as value. It will store different types like strings, integers and
other similar types.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> famousCities = new HashMap<String,
String>();
famousCities.put("England", "Manchester");
famousCities.put("Germany", "Berlin");
famousCities.put("Italy", "Rome");
famousCities.put("USA", "New York");
famousCities.put("South Africa", "Cape Town");
famousCities.put("India", "Mumbai");
famousCities.put("Pakistan", "Lahore");
System.out.println(famousCities);
}
}
New York
Rome
I will use the remove() method to remove items from the hash map.
import java.util.HashMap;
6
You also can create a loop through all the items of HashMap. I will build a
for-each loop in the following example and let it run its course through the
items of the hashmap. The method used for the purpose is called keyset()
method. However, it is only perfect if you need the keys only. You can use
values() method if you need to use the values as well.
import java.util.HashMap;
USA
Pakistan
England
Italy
Germany
India
We also can print the values through the for-each loop. See the following
example.
import java.util.HashMap;
New York
Lahore
Manchester
Rome
Berlin
Mumbai
You can use both keys and values to produce in an output. The following
example will explain its usage.
import java.util.HashMap;
Last year I travelled to USA. I found New York city to be the most
beautiful and hospitable.
Last year I travelled to Pakistan. I found Lahore city to be the most
beautiful and hospitable.
Last year I travelled to England. I found Manchester city to be the
most beautiful and hospitable.
Last year I travelled to Italy. I found Rome city to be the most
beautiful and hospitable.
Last year I travelled to Germany. I found Berlin city to be the most
beautiful and hospitable.
Last year I travelled to India. I found Mumbai city to be the most
beautiful and hospitable.
Chapter Five: Java Conditionals & Switch
Statement
You have learned how to create statements and which types of operators you
must use. Elements of logic must be added at times to run the code and keep
it running without interruption. This chapter will walk you through the
process of manipulating the code execution, using conditional statements and
repetitive statements to achieve the goal. You can represent an algorithm and
a solution by using flowcharts.
Java supports the logical conditions in mathematics. Here is a rundown of the
conditions that you can use in the codes in Java. You can use the less than
condition x<y, the less than and equal to sign x <= y, the greater than sign x >
y, the greater than or equal condition x >= y, the equal to condition x == y,
and the not equal to condition x != y.
You can use all these conditions for performing a set of actions for various
reasons. For example, the if statement helps you specify a certain block of
code that must be executed in case a specified condition turns out to be true.
You can use the else statement to specify the code that must execute if a
condition returns false. You can use the else if statement for specifying and
testing a condition in case of false condition. You can use the switch
statement for specifying different codes that must be executed.
The if Statement
You can use the if statement if you want a specific piece of code in Java to
execute. The if keyword is always written in lowercase letters. If you write it
in uppercase letters like If or IF, the compiler will generate an error. Let us
test some conditions using the if statement and see how it works in Java.
public class JavaX {
public static void main(String[] args) {
if (300 > 30) {
System.out.println("Yes, 300 is greater than 30.");
}
}
}
It is a bright noon.
Java Switch Statement
When there are multiple code blocks but you need to execute only one of
them, you have to use the switch statement to execute the desired block of
code. You can evaluate the switch statement only once. Each case in the
block of code presents itself for comparison with the value of each
expression. In case of a match, the targeted block of code is immediately
executed. You may come other keywords like default and break. I will
explain them later on. I will use the switch statement in the following code to
see how it can be used to pick one of the several code lines in a lengthy and
complex program. I will use a small program that indicates the weekdays and
the related activities for each weekday.
public class JavaX {
public static void main(String[] args) {
int tezday = 3;
switch (tezday) {
case 1:
System.out.println("Monday is blue.");
break;
case 2:
System.out.println("Tuesday fires up the momentum.");
break;
case 3:
System.out.println("Wednesday brings full speed to work.");
break;
case 4:
System.out.println("Thursday keeps up the momentum.");
break;
case 5:
System.out.println("Friday finishes key tasks and gets you ready
to get relaxed.");
break;
case 6:
System.out.println("Saturday is sleepy.");
break;
case 7:
System.out.println("Sunday is all about food ");
break;
}
}
}
0
1
2
3
4
5
6
The declaration as well as the initialization of the counter variable int x=0
exists out of the statement. However, the increment of the counter is executed
in the code block. The repetition also starts here. Also, one major benefit of
using the while loop is that the condition in the block of code is not quite
necessary. The condition also is not mandatory at this point. You can replace
it entirely with true. However, you need to make sure that you have included
an exit condition in the block of code that will execute at one or the other
point. Otherwise, the execution of the block of code is likely to end up in
error. This particular condition should be replaced at the start of the code to
prevent the execution of some useful logic where it must not be.
The most important thing to keep in mind is that you should increase the
variable x or the loop will be infinite. It will never end and ultimately crash
the program it is a part of.
The while statement works best when you are working with a specific
resource that is never always online. Let us say you are using a remote
database for your application that exists in an unstable network. The while
statement helps you save your data over multiple timeouts until you succeed.
The do-while Loop
The do-while loop is no different from the while loop. The only difference is
that the condition for continuation is generally evaluated in the former loop
after the code block has been executed. This triggers the code block to be
executed at least once unless the developer embeds the exit condition in the
code. In most cases, the do-while and while loops can be easily and
flawlessly interchanged. In most cases, you need a minimum change in the
logic of the code block. Traversing the array and the printing of values of the
elements may be written by using the do-while loop. There is no need to
change the code.
The do-while loop statement works perfectly well when the code block needs
to be executed at least once. Otherwise, you have to evaluate the condition at
least once.
In the following example, I will use the do-while loop. The compiler will let
the statement execute once even if the condition turns out to be false in the
first run. Its reason is that the code block, which exists before the condition,
is always tested.
public class JavaX {
public static void main(String[] args) {
int x = 0;
do {
System.out.println(x);
x++;
}
while (x < 7);
}
}
0
1
2
3
4
5
6
For Loops
The for loop is highly recommended for the iteration of the objects such as
lists and arrays that need to be counted. For example, traversing of an array
and then printing the same can be done easily by the for loop.
public class JavaX {
public static void main(String... args) {
int array[] = {50, 31, 12344, 42, 53};
for (int x = 0; x < array.length; ++x) {
System.out.println("This is Java array[" + x + "] = " + array[x]);
}
}
}
0
1
2
3
4
5
6
In the first statement, the variable is defined and set up before the start of the
loop. In the second statement, the condition is defined so that the loop has
something to understand and run. If the condition returns as true, the loop
starts all over again. If the condition returns as false, the loop will reach its
end. In the third statement, the variable's value increases each time the block
of code inside the loop is executed.
By changing the condition, we can affect the output of the for loop. The
following code will print the multiple of three.
public class JavaX {
public static void main(String[] args) {
for (int x = 0; x <= 15; x = x + 3) {
System.out.println(x);
}
}
}
0
3
6
9
12
15
The for-each Loop
The next loop I will explain is the for-each loop. The for-each loop is used
exclusively to looping through different elements inside an array. In the
following example, I will use an array of kitchen accessories and print all the
elements using the for-each loop. See how it is different from the standard for
loop. Please note down the difference in the code block as well.
public class JavaX {
public static void main(String[] args) {
String[] kitchen = {"spatula", "spoon", "napkin", "ladle", "steak
hammer"};
for (String x : kitchen) {
System.out.println(x);
}
}
}
spatula
spoon
napkin
ladle
steak hammer
Breaking Loops
In previous examples, I pointed out that you must use the break statement to
exit a loop. You can use and manipulate the break statement in three ways.
1. The break statement is used to exit a loop. If a label accompanies
the break statement, it will break the loop. This comes extremely
handy when you are working with nested loops, because that’s
how you can break from the nested loops and not only the one that
contains this statement.
2. The continue statement is used to skip any execution of code after
it. It then move on to the next step.
3. The return statement is generally used for exiting a certain method
so is the loop, the if statement, or the switch statement are inside
the body of the method, you can use it to exit the loop. As per the
best practices, the use of return statements for exiting a method
must not be abused as they might risk the execution harder to
follow up.
The break Statement
The break statement may only be used in switch, do-while, and while
statements. You have seen how it can be used inside a code. You have seen
what results it produces in a code. I have used it when I explained the switch
statement. Now, I will demonstrate the use of the break statement in all the
other types of loops. You can break out of the for loop, while loop, or do-
while loop with the help of the break statement. However, you must control it
by the exit condition otherwise you will not be able to execute a single step.
In the next example, I will restrict the loop to some elements even if the loop
traverses all the elements.
public class JavaX {
public static final int thisarray[] = {5, 1, 2, 3, 4};
public static void main(String... args) {
for (int x = 0; x < thisarray.length ; ++x) {
if (x == 4) {
System.out.println("You have reached the end of the loop!");
break;
}
System.out.println("the looped through value: [" + x + "] = " +
thisarray[x]);
}
}
}
5050
The return keyword can work with more than one parameter. See the
following example that has two parameters.
public class JavaX {
static int thisMeth(int a, int b) {
return b + a;
}
5050
When you return a value through a method, you can channel it toward a
variable and store it to use it later on in the program. The process is simple.
All we need is a third variable for the code. In the following example, I will
add a third variable in the code and send the returned result.
public class JavaX {
static int thisMeth(int a, int b) {
return b + a;
}
5050
Method Overloading
With the help of method overloading, multiple methods may take the same
name with the help of different parameters. The following example has two
methods that add different types of numbers.
public class JavaX {
static int thisMethInt(int a, int b) {
return a + b;
}
X
the int number : 130
the double number: 14.559999999999999
Scope
The variables in Java are only accessible in the region they are created in,
which is called scope. The variables declared in a method can be located and
traced after the line of code they are declared in.
public class JavaX {
public static void main(String[] args) {
int a = 100;
System.out.println(a);
}
}
100
Block of Scope
A block of code alludes to the code that exists between curly braces. The
code can only access the variables that are declared in the blocks of code in
between curly braces, which ultimately follows the line on which the
programmer declares the variable.
public class JavaX {
public static void main(String[] args) {
{
int a = 500;
System.out.println(a);
}
}
500
Java Recursion
Recursion in Java is a technique to make a function call by itself. The
technique offers a way to break down complicated problems into simple
problems that are usually easier to solve. Recursion may get a lot tough to
understand. However, the best way to find out how it works it to experiment
with the same.
The addition of two numbers is easy but the addition of a range of different
numbers is complicated. In the following example, I have used recursion to
add a wide range of numbers by breaking them down into simple task of
adding two numbers.
public class JavaX {
public static void main(String[] args) {
int theresult = summingup(20);
System.out.println(theresult);
}
public static int summingup(int a) {
if (a > 0) {
return a + summingup(a - 1);
} else {
return 0;
}
}
}
210
Halting Condition
As loops run into one or another problems of becoming infinite loops,
recursive functions have the same tendency of becoming infinite recursion.
Infinite recursion happens when the function never stops making a call to
itself. Every recursive function must have a halting condition, which is where
your function will stop making a call to itself. In the past example, the halting
condition occurred where the parameter became zero. In the next example,
the function will add multiple numbers between the start and the end. The
halting condition for the recursive function is when the end is never greater
than the start.
public class JavaX {
public static void main(String[] args) {
int theresult = summingup(50, 100);
System.out.println(theresult);
}
public static int summingup(int thestart, int theend) {
if (theend > thestart) {
return theend + summingup(thestart, theend - 1);
} else {
return theend;
}
}
}
3825
Advanced Method Concepts
There are a couple of more method concepts that you must take into
consideration. The first is about the use of arrays in methods. You have
learned how to integrate primitive data types in the code. Apart from the
primitive data types, you can use arrays as well. You can use arrays as
parameters. For that purpose, you need to use square brackets after the
parameter's data type in the method's declaration. When you need to call this
method, you must declare the array and then pass it on to an argument to your
method.
You also can return an array from a method. To ensure the return in a
method, you should add square brackets after the return type inside the
declaration of methods. First of all, declare an array and then assign to it the
result of the method.
package arraymethoddemo;
import java.util.Arrays;
class ThisClass{
}
}
The first element in the array will be 1
[0, 2, 4]
I have included a couple of classes in the same file to keep it simple and easy
for reading and practicing. There are two methods in the ThisClass. The first
method is labeled as printingtheFirstElement(). This shows how to use an
array in the form of a parameter. The second method returningtheArray()
shows how you can return the array in the second phase. I then initialized the
ThisClass object known as amd in the main() method. I then declared the
array and also passed it on as argument to printingtheFirstElement() method.
I also declared a second array inside the main() method and then assigned the
result of returningtheArray() method to the same. Then I printed the contents.
This Keyword
The following example uses the this keyword to access the total number of
classes.
public class ThisKeyword {
// This is the Instance sum of variables
int number = 100;
ThisKeyword() {
System.out.println("This is a brilliant example program built
around the keyword this");
}
ThisKeyword(int number) {
// I am invoking default constructor in the following step
this();
try {
in = new FileInputStream("thisisinput.txt");
out = new FileOutputStream("thisisoutput.txt");
int x;
while ((x = in.read()) != -1) {
out.write(x);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams
Java Byte Streams are usually used for performing input and output for the 8-
bit bytes. On the other hand, Java Character streams may be used for
performing the input and output of 16-bit Unicode. The most frequently used
classes in Character streams are FileWriter and FileReader.
import java.io.*;
public class CopyingtheFile {
int x;
while ((x = in.read()) != -1) {
out.write(x);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
This program will create an output file that will have the same content that
the input file had.
Standard Streams
Programming languages provide support for standard I/O where user’s
program take the input from keyboard and then produce the output on the
screen. If you are acquainted with C or C++ programming languages, you
need to be aware of three standard devices - STDIN, STDERR, and
STDOUT. Java provides three standard streams such as Standard Error,
Standard Input, and Standard Output.
Standard Input is generally used for feeding data to the user’s program. For
this purpose, keyboard us used as the input stream. Standard output is used to
process the output of data that is produced by a user’s program. Usually
programmers use a computer screen for the standard output stream. Standard
Error is used to process the output error data that is produced by user’s
program. A computer screen is generally used for standard error stream and is
represented as System.err.
import java.io.*;
public class ReadingTheConsole {
try {
cin = new InputStreamReader(System.in);
System.out.println("Here you can Enter the characters, enter 'q'
for quitting the program.");
char x;
do {
x = (char) cin.read();
System.out.print(x);
} while(x != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Chapter Eight: Java Classes
OOP in Java stands for object oriented programming. Procedural
programming in Java is about composing methods and procedures that will
perform certain operations on your data. In contrast, object-oriented
programming focuses on the creation of objects that contain methods and
data. Object oriented programming carries multiple advantages over
procedural programming. It is faster than procedural programming and is
quite easier to execute.
Object oriented programming offers a clear structure for programs. It also
helps keep Java code from repeating itself and cluttering the program. It
makes your code easier to maintain, debug or modify. It also makes it
possible for you to create reusable applications with less code and a shorter
development time. Consequently, it will save you resources. The object
oriented programming technique favors the DRY principle, known as Don’t
Repeat Yourself in full form. This principle focuses on cutting down on the
repetition of code. You must slice out the codes that are common to your
application, and then place them in a single place. From there you can take
them and reuse them instead of repeating them.
Classes
Classes and objects are two parts of object oriented programming. A class is
like a general template for objects and an object is like an instance of a single
class. when you create individual objects, they will inherit the variables and
different methods from the class.
Everything in Java is connected with objects or classes, and their methods or
attributes. A leopard is an object and it has attributes like height, color, and
gestures. It sits, eats, runs, and fights. Similarly, we give attributes to the
objects in Java classes. In the following example, I will create an object from
a class. I will use the keyword new along with the name of the object.
public class JavaX {
int a = 50;
50
You can create more than objects in a class. See the demonstration in
the following example.
public class JavaX {
int a = 50;
50
50
You can create an object and then access the same in another class. This more
often is used for the better organization of classes. One class takes all the
methods and attributes while the other class has one main method. You need
to remember that the name of the Java file you are saving your code in must
match the name of the class.
Java Class Attributes
You can access the attributes of a class by creating a class object and also by
using the dot syntax. The following example will create object of a class. I
will use the a attribute on the object to print the value.
public class JavaX {
int a = 50;
50
Modifying Attributes
Changing values of attributes becomes imminent at times. You need to
replace the old values with new values. You can modify the attributes of
classes by the following method.
public class JavaX {
int a;
400
Even if the initial value of the attribute a is something like 20, you can
modify it. I will change 20 to 400 inside the class without removing the first
value. That’s called the process of modifying attributes in Java classes.
public class JavaX {
int a = 20;
400
If you are writing a large-scale code and don’t want other programmers to
change the value, you can block modification by declaring its attribute final.
You will see an error in return. See the following example.
public class JavaX {
final int a;
50
555
You can add as many attributes as you like.
public class JavaX {
String name = "John";
String profession = "doctor";
int theage = 32;
// In the following step, I will create the speed() method and then I
will add to it a parameter
public void bikespeed(int maximumSpeed) {
System.out.println("The Maximum speed of the bike is " +
maximumSpeed + "mph.");
}
// Inside JavaX class, I will call on the methods on the bike1 object
public static void main(String[] args) {
JavaX bike1 = new JavaX(); // It is time to create the bike1
object
bike1.topThrottle(); // I am now calling the topThrottle() method
bike1.bikespeed(500); // I am now calling the bikespeed()
method
}
}
// In the following step, I will create the speed() method and then I
will add to it a parameter
public void bikespeed(int maximumSpeed) {
System.out.println("The Maximum speed of the bike is " +
maximumSpeed + "mph.");
}
// Inside JavaX class, I will call on the methods on the bike1 object
public static void main(String[] args) {
JavaX bike1 = new JavaX(); // It is time to create the bike1
object
bike1.topThrottle(); // I am now calling the topThrottle() method
bike1.bikespeed(500); // I am now calling the bikespeed()
method
JavaX bike2 = new JavaX(); // It is time to create the bike1
object
bike2.topThrottle(); // I am now calling the topThrottle() method
bike2.bikespeed(300); // I am now calling the bikespeed()
method
JavaX bike3 = new JavaX(); // It is time to create the bike1
object
bike3.topThrottle(); // I am now calling the topThrottle() method
bike3.bikespeed(400); // I am now calling the bikespeed()
method
}
}
// In the following step, I will create the speed() method and then I
will add to it a parameter
public void bikespeed(int maximumSpeed) {
System.out.println("The Maximum speed of the bike is " +
maximumSpeed + "mph.");
}
}
The above-mentioned section will go to the file name JavaX. This is the main
class and it needs a separate file to be saved in. The following section will be
saved in the second file named after the name of the class. See below which
part will take a separate file.
Class Bike{
// Inside JavaX class, I will call on the methods on the bike1 object
public static void main(String[] args) {
JavaX bike1 = new JavaX(); // It is time to create the bike1
object
bike1.topThrottle(); // I am now calling the topThrottle() method
bike1.bikespeed(500); // I am now calling the bikespeed()
method
JavaX bike2 = new JavaX(); // It is time to create the bike1
object
bike2.topThrottle(); // I am now calling the topThrottle() method
bike2.bikespeed(300); // I am now calling the bikespeed()
method
JavaX bike3 = new JavaX(); // It is time to create the bike1
object
bike3.topThrottle(); // I am now calling the topThrottle() method
bike3.bikespeed(400); // I am now calling the bikespeed()
method
}
}
As the name of the class is Bike, the name of the file will be Bike as well.
Java Constructors
A Java constructor is used to initialize objects. The java constructor may be
called when you create a class object. You can also use it to set up the initial
values for the attributes of an object.
// I am creating the JavaX class
public class JavaX {
int a;
5
You must note that the Java constructor needs to match the name of the class.
Also, you cannot add a return type in this code. You can only call the
constructor when you create an object. All the Java classes need to have
constructors by default. If you do not create one, Java will do that for you.
However, in that situation, you will not be able to set up the initial values for
the object's attributes.
Java constructors can take certain parameters that are used to initialize
attributes. In the following example, I will add a parameter to the Java
constructor. Inside the constructor, I will pass parameter to the constructor.
See the following example to understand how to do that.
public class JavaX {
int a;
public JavaX(int b) {
a = b;
}
You can add to the code as many parameters as you need to.
public class JavaX {
int mYear;
String mName;
class TheInnerClass {
int b = 5000;
}
}
5100
Unlike the regular class, the inner class can be protected or private. If you
don’t need outside objects for accessing the inner class and declaring classes
as private.
class TheOuterClass {
int a = 100;
private class TheInnerClass {
int b = 50;
}
}
50
Accessing Outer Class From Inner Class
The biggest advantage of the inner classes is that they tend to access the
attributes and methods of outer classes.
class TheOuterClass {
int a = 100;
class TheInnerClass {
public int TheInnerMethod() {
return a;
}
}
}
100
Chapter Nine: Modifiers, User Input, Interfaces
You might have noticed a heavy use of the word ‘public’ in the codes. The
public keyword is labeled as access modifier. It means that you can use it to
set up the access level for your classes, methods, attributes and constructors.
There are different types of modifiers in Java; one is called access modifiers
and the other one is called non-access modifiers. The access modifiers tend to
control the access level while the non-access modifiers need not control the
access level. Instead, it provides some other kind of functionality.
For classes, you can use default or public modifier. When you add public to a
class, you label the class as literally public. Anyone can access the class, edit
it or modify it. The default modifier for a class makes the class accessible
only by other classes inside a package. You can set the modifier to default
when you don’t want to specify a modifier.
public class JavaX {
public static void main(String[] args) {
System.out.println("The public modifier makes this class accessible
to anyone.");
}
}
To use the default method, all you need to do is remove the public keyword
from the above code like this:
class JavaX {
public static void main(String[] args) {
System.out.println("The public modifier makes this class accessible
to anyone.");
}
}
When you are dealing with method, attributes, and constructors, you can use
the following modifiers.
public class JavaX {
public String name = "David";
public String profession = "Coach";
public String contact = "[email protected]";
public int age = 48;
}
Now I will set the attributes to private, which means that now the
attributes will only be accessible inside the declared class. See the
following example.
public class JavaX {
private String name = "David";
private String profession = "Coach";
private String contact = "[email protected]";
private int age = 48;
You can call Static methods even if you don't create objects
You can call public methods by creating certain objects.
Abstract
The abstract method is connected with the abstract class. It lacks a body. The
subclass provides the body for the class.
// This is the abstract class
abstract class JavaX {
public String name = "David";
public String profession = "Coach";
public String contact = "[email protected]";
public int age = 48;
}
class Main {
public static void main(String[] args) {
Leopard leopard1 = new Leopard(); // I am creating a leopard
object
leopard1.animalSounds();
leopard1.sleepmode();
}
}
this.name = newName;
}
}
JavaX.java:3: error: cannot find symbol
Man Obj1 = new Man();
^
symbol: class Man
location: class JavaX
JavaX.java:3: error: cannot find symbol
Man Obj1 = new Man();
^
symbol: class Man
location: class JavaX
2 errors
Now I will use the getName() and setName() methods to update the variables.
Now the methods will have access to the variables and there will be no error
on your screen.
public class JavaX {
public static void main(String[] args) {
Man Obj1 = new Man();
Obj1.setName = "Johnny Boy";
System.out.println(Obj1.getName);
}
}
MEDIUM
You can add enum inside a switch statement as well. See the following
example for reference. Inside the switch statement, the enums are used for
checking corresponding values.
enum TezLevel {
LOW,
MEDIUM,
HIGH
}
switch(Var1) {
case LOW:
System.out.println("You are at the Lowest level in the code.");
break;
case MEDIUM:
System.out.println("You are at the Medium level in the code.");
break;
case HIGH:
System.out.println("You have reached the Highest level now.");
break;
}
}
}
switch(Var1) {
case LOW:
System.out.println("You are at the Lowest level in the code.");
break;
case MEDIUM:
System.out.println("You are at the Medium level in the code.");
break;
case HIGH:
System.out.println("You have reached the Highest level now.");
break;
}
}
}
LOW
MEDIUM
HIGH
An enum, like a class, carries attributes and it can also have methods. The
only difference is that the enum constants are final, public, and static. You
cannot override them. They cannot help you create objects. Also, you cannot
extend them to other classes as well. However, they can implement
interfaces. The best way to use them is for values like colors, months, years,
and weekdays, which do not change in any case.
Java User Input
You can use the Scanner class in Java to receive user input. The class can be
obtained from java.util package. If you want to use the class, you have to
create an object and then apply the available methods of Scanner class. There
are multiple methods for the Scanner class. In the following example, I will
use the nextLine() method that is specially used to read different types of
strings.
import java.util.Scanner; // Here I am importing Scanner class from the
package
class Main {
public static void main(String[] args) {
Scanner ThisObj = new Scanner(System.in);
String myuserName;
class Main {
public static void main(String[] args) {
Scanner Obj1 = new Scanner(System.in);
class JavaX {
public static void main(String[] args) {
Leopard Pig1 = new Leopard();
Pig1.animalSounds();
Pig1.sleepmode();
}
}
interface Interface2 {
public void TheOtherMethod(); // This is the second interface method
}
true
true
true
The implements keyword forms the IS-A relationship. The implements
keyword is used inside classes for inheriting properties of interfaces. Classes
do not extend these interfaces. Let us use the instanceof operator for checking
whether Mammal family belongs to animal kingdom and dog also is of
animal kingdom. This operator works perfectly well.
interface AnimalKingdom{}
class MammalFamily implements AnimalKingdom{}
true
true
true
If a class inherits method from superclass, the method that is not marked as
final is likely to be overridden. There is a positive angle to this development.
It provides you the ability to define a particular behavior that’s belongs to the
subclass type. This means that a subclass will implement the parent class
method on the basis of the requirement. In object-oriented programming,
overriding means overriding the total functionality of a specific method that
already exists.
class AnimalKingdom {
public void moveon() {
System.out.println("All the animals in the kingdom can move.");
}
}
}
}
// Here I will display the time and date by using the toString()
method
System.out.println(date.toString());
}
}
System.out.printf(string);
}
}
Here is the Current Date & Time : Thu May 20 09:43:28 UTC 2021
Of course, you don’t have the time to feed in the date multiple times to
format each part of the program. That’s why a format string will indicate the
argument’s index that should be formatted. The index needs to immediately
follow % and it should be terminated by $.
import java.util.Date;
public class DateDemonstration {
Thread.sleep(5*180*10);
System.out.println(new Date( ) + "\n");
Difference is : 9028
If you take a look at the Georgian Calendar, you will find out that it is a solid
implementation of Calendar class. It implements the Gregorian Calendar that
you use every day. The getInstance() method will return the Gregorian
Calendar. It will be initialized with date and time in its default time zone.
There will be two fields known as AD and BC. They will represent two eras
by Gregorian Calendar.
import java.util.*;
public class TheGregorianCalendarDemonstration {
int theYear;
// I will now create the Gregorian calendar
// That will have the present date and time in its
// default locale as well as timezone.
The Found value is as follows: You placed this order for QT3000!
OK?
The Found value is as follows: You placed this order for QT300
The Found value is as follows: 0
RegEx Syntax
The following is given different regular expression metacharacters that Java
entertains.
while(m.find()) {
countingit++;
System.out.println("Here is the top Match number
"+countingit);
System.out.println("Here is the starting point(): "+m.start());
System.out.println("Here is the ending point(): "+m.end());
}
}
}
Chapter Twelve: Java Generics
Java Generic methods and classes tend to enable programmers to specify a
set of methods or a set of related methods with one declaration of class. Java
generic provides compile-time type safety that will allow programmers to
detect the invalid types at the time of compilation. By using Java Generic
concept, I will write a generic method to sort out an array of different objects
and then invoke a generic method with the help of Double arrays, Integer
arrays, and String arrays.
Generic Methods
You may write one single method declaration that will be called with
different types of arguments. Based on argument types passed to generic
method, the Java compiler will handle each method appropriately. Here are
the rules for defining Generic Methods.
if(b.compareTo(maximum) > 0) {
maximum = b; // This will assume that b is the largest
}
if(c.compareTo(maximum) > 0) {
maximum = c; // This assumes that c is the largest
}
return maximum; // This code will return the largest object in the
code
}
public T get() {
return a;
}
integerBox.adding(new Integer(100));
stringBox.adding(new String("I am learning Java
programming."));