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

Java Basics - Class 1

java

Uploaded by

skumar027
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Java Basics - Class 1

java

Uploaded by

skumar027
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

What is Java?

Java is a general-purpose modern programming language initially developed by Sun Microsystems,


and currently owned by Oracle Corporation. The key feature of the language is platform
independence: it means that the same Java program can be run on multiple platforms without any
changes! This principle is also known as "write once, run anywhere" (or WORA).

Java has been one of the most popular programming languages for many years. It has earned the
top position in the TIOBE index (a programming language popularity index). This language is used by
a huge community of developers around the world! If you have a problem, you can always ask other
developers or find a suitable answer online.

Java is used in our Android smartphones, the financial services industry, telecommunications,


embedded systems, and in many other areas. Medical applications use it to store patient data,
computer games, such as Minecraft, are created using Java; development tools like IntelliJ IDEA and
Eclipse wouldn't exist without it.

A short history of Java

The Java language project was initiated in 1991 by James Gosling and his colleagues. In the
beginning, the language was called "Oak." Later the project was renamed "Java" as a reference to
Java coffee. For this reason, the language’s logo is a cup of coffee.

Sun Microsystems released Java 1.0 in 1996. After that, new versions were released every 1 to 3 years.
Since Java 9, released in 2017, new versions have been released every 6 months. You can read more
about its history and find the most recent version here.

Some important features of Java

As we've mentioned before, the most important feature of Java is platform independence.

Another important feature is a simple and clear syntax. Many elements of the language are easy to
read and are widely used in other programming languages such as C/C++, C#, JavaScript, and Go.

If you have ever written programs in C/C++, you know that manual memory cleaning can lead to
bugs in the code. Fortunately, Java has a garbage collector that automatically cleans
memory from unused objects during runtime.

It is also important to note that Java supports multiple programming paradigms; you will get to know
more about them in future topics. Java is primarily an imperative language based on the object-
oriented concept: almost every part of a program is an object. Therefore, a program itself can be
considered as a set of interacting objects. Also, it partially supports modern programming paradigms
such as generic programming, concurrent programming, functional programming, and some others.

If you are a beginner in programming, it may be difficult to comprehend all the features of Java right
now. This is not a bad thing. Throughout this set of topics, you will learn about all of these concepts.
Also, Java has comprehensive online documentation that comprises guides, tutorials, specifications,
API documentation, technical information, and more. We will refer you to it from time to time during
your studies.
In conclusion, Java is a modern and popular programming language that can be successfully used in
almost all domains.
Hello Sanjeev! - Programme :-

public class Main {


public static void main(String[] args) {
System.out.println("Hello, Sanjeev!");
}
}

Literals

Regardless of its complexity, a program always performs operations on numbers, strings, and other
values. These values are called literals. There are many different sorts of literals in Java, but in this
topic we will focus only on a few of them: the ones that surround us all the time in everyday life.

Let's consider integer numbers, strings, and characters in the format in which they are written in Java.

Integer numbers

1. These numbers are used to count things in the real world. Also, we will often use them in Java.

2. Here are several examples of valid integer number literals separated by commas: 0, 1, 2, 10, 11,
100.

3. If an integer value contains a lot of digits, we can add underscores to divide the digit into blocks
for increased readability: 1_000_000. It's more readable than the same value written as 1000000.

Characters

A single character can represent a digit, a letter or another symbol. To write a character we use single
quotes as follows: 'A', 'B', 'C', 'x', 'y', 'z', '0', '1', '2', '9'. Character literals can represent symbols of an
alphabet, digits from '0' to '9', whitespaces (' '), or other characters or symbols ('$').

Do not confuse characters that represent numbers (e.g. '9'), with numbers themselves (e.g. 9).

A character can't include two and more digits or letters because it represents only a single symbol.
The following two examples are incorrect: 'abc', '543'. These literals contain too many characters.

Strings

A string is a sequence of any individual characters. Strings represent text information such as a text
of advertising, an address of a web page or a login on a site.

To write a string we use double quotes instead of single ones. Here are some valid examples:  "text",
"I want to know Java", "123456", "[email protected]". A string consisting of a single character
like "A" is also a valid string, but do not confuse it with the 'A' character.

As you can see, strings can include letters, digits, whitespaces, and other characters.
Theory: Overview of the basic program

In this topic, we will build our very first Java program. Our program will simply print  "Hello,
World!" on the screen (a tradition by most programmers when learning new languages). Our code
may not seem too exciting at first, however, we will learn about the basic template that all Java
programs need to follow.

public class Main ( ) {


public static void main (String[ ] args) {
System.out.println ("Hello, World!");
}
}

The basic terminology

Now that you have seen the result, let's learn some basic terminology and then try to understand this
program.

 Program – a sequence of instructions (called statements), which are executed one after
another in a predictable manner. Sequential flow is the most common and straightforward
sequence of statements, in which statements are executed in the order that they are written
– from top to bottom in a sequential manner;
 Statement – a single action (like print a text) terminated by semi-colon ( ;);
 Block – a group of zero, one or more statements enclosed by a pair of braces {...}; There
are two such blocks in the program above.
 Method – a sequence of statements that represents a high-level operation (also known as
subprogram or procedure).
 Syntax – a set of rules that define how a program needs to be written in order to be valid;
Java has its own specific syntax that we will learn;
 Keyword – a word that has a special meaning in the programming language ( public, class,
and many others). These words cannot be used as variable names for your own program;
 Identifier or name – a word that refers to something in a program (such as a variable or a
function name);
 Comment – a textual explanation of what the code does. Java comments start with //.
 Whitespace – all characters that are not visible (space, tab, newline, etc.).

The Hello World program under a microscope

The Hello World program illustrates the basic elements of Java programs. For now, we will discuss
only the most important elements.

1. The public class. It is the basic unit of a program. Every Java program must have at least one class.
The definition of a class consists of the class keyword followed by the class name. A class can have
any name, such as App, Main, or Program, but it must not start with a digit. A set of
braces {...} encloses the body of a class.

public class Main {
    // ...
}
The text after // is just a comment, not a part of the program. We will learn about comments in
detail in later topics.

2. The main method. To make the program runnable, we put a method named main inside a class. It
is the entry point for a Java program. Again, the braces {...} enclose the body of the method, which
contains programming statements.

public static void main(String[] args) {
     // statements go here
}
The keywords public, static, and void will be discussed later, so just remember them for now. The
name of this method (main) is predefined and should always be the same. Capitalization matters; if
you name your first method like Main, MAIN or something else, the program cannot start.

The element String[] args represents a sequence of arguments passed to the program from the
outside world. Don't worry about them right now.

3. Printing "Hello, world!". The body of the method consists of programming statements that
determine what the program should do after starting. Our program prints the string "Hello,
World!" using the following statement:

System.out.println("Hello, World!"); 
//  each statement has to end with ;
This is one of the most important things to understand from the Hello World program. We invoke a
special method println to display a string followed by a new line on the screen. We will often use
this approach to print something of interest to the screen. The text is printed without double quotes.

It is important that "Hello, World!" is not a keyword or an identifier; it is just a text to be printed.

Keywords

As you can see, even a simple Java program consists of many elements,
including keywords that are parts of the language. In total, Java provides more than 50
keywords which you will gradually learn on this platform. The full list is here, though you
don't need to remember all of them at this moment.

Note, main is outside the given list because it is not a keyword.

Conclusion

We have discussed the simplest program you can write in Java. It has a single class with a
single  main  method. Every Java program must have a  main  method as it is the first to be executed
when the program runs. Don't worry about memorizing every single term used in the topic (syntax,
statement, block). These terms will reappear in further materials. Do not forget to use the
provided Hello World program as a template for your own programs.
a. keyword - is a word that has a special meaning in the programming language
b. name - is a word written by a programmer to identify something in a program
c. statement - is a single action terminated by a semi-colon
d. comment - is text that is not part of the program
e. syntax - is a set of rules that defines the combinations of symbols that are considered to be a
correctly structured program

Theory: Printing data

Displaying text using println() and print()

Standard output is a receiver to which a program can send information as text. It is supported by all
common operating systems. Java provides a special  System.out  object to work with the standard
output. We will often use it to print data.

The  println  method displays the passed string followed by a new line on the screen (print-line). For
example, the following code snippet prints four lines.

System.out.println("I ");
System.out.println("know ");
System.out.println("Java ");
System.out.println("well.");
Here is the output we get:

I
know
Java
well.
All the strings were printed as they are, without double quotes.

This method allows you to print an empty line when no string is given:

System.out.println("Java is a popular programming language
.");
System.out.println(); // prints empty line
System.out.println("It is used all over the world!");
And here is the output:

Java is a popular programming language.

It is used all over the world!
The  print  method displays the value that was passed in and places the cursor (the position where
we display a value) after it. For example, the code below outputs all strings in a single line.
System.out.print("I ");
System.out.print("know ");
System.out.print("Java ");
System.out.print("well.");
We receive the following output:

I know Java well.
Pay attention to the spaces between words. We pass them to methods for printing.

Printing numbers and characters

Both  println  and  print  methods allow a program to print not only strings and characters,
but also numbers.

Let's print two secret codes.

System.out.print(108);   // printing a number
System.out.print('c');   // printing a character that represents a letter
System.out.print("Q");   // printing a string
System.out.println('3'); // printing a character that represents a digit

System.out.print(22);
System.out.print('E');
System.out.print(8);
System.out.println('1');

Here is our output:

108cQ3
22E81
As is the case with strings, none of the characters contain quotes.

Conclusion

In Java, you can print data via standard output using the  System.out object. You can
use println method to display the passed string in a print-line and the print method to output all
passed strings in a single line. Both of these methods also allow for printing numbers as well as
characters.
Theory: Types and variables

Declaring and initializing

A variable is a placeholder for storing a value of a particular type: a string, a number, or something


else. Every variable has a name (also known as an identifier) to distinguish it from others. Before
you start using a variable, you must declare it.

The general form of declaration is the following:

DataType variableName = initialization;

The left part of this statement describes the variable, and the right part describes something that is
assigned to it.

 The type (or data type) of a variable determines what possible operations can be performed
on the variable and which values can be stored in it. Here we use a non-existing data type
(DataType) to demonstrate the general form of declaration.
 The name (or identifier) distinguishes the variable from others. The name of a variable
cannot start with a digit; it usually starts with a letter. Always try to choose meaningful and
readable names for variables to make your code easy to understand.
 The assignment operator denoted as = is used to assign a single value or a result of an
expression to a variable.
 The initialization is a value or a result of an expression that is assigned to the variable.

According to this declaration, we can declare a variable of the type String and assign the
word "java" to it:

String language = "java";

We can also declare a variable of the type int to store an integer number:

int numberOfApples = 5;
The case in the name of a variable makes a difference: language is not the same as Language.
Variables can store not only strings and numbers, but also characters and other data types which we
will learn about later in the next topics.
Accessing the value of a variable

Once a variable has been declared, its value can be accessed and modified using the name. In the
example below, we declare a variable and then print it:

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // Monday

It is also possible to assign a value of one variable to another one:

int one = 1;
int num = one;
System.out.println(num); // 1

One important feature of variables is that they can be changed. You don't need to declare a variable
again to change its value; just assign a new value to it using the = operator.

Let's declare a variable named dayOfWeek and print its value before and after changing:

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // Monday

dayOfWeek = "Tuesday";
System.out.println(dayOfWeek); // Tuesday

There is one restriction for variables: you can only assign a value of the same type as the type of the
initial variable. So, the following code is not correct:

int number = 10;
number = 11; // ok
number = "twelve"; // it does not work!

Alternative forms of declaration

There are several alternative forms of declaration which are less commonly used in practice. Here are
several of them in particular examples.

 Declaring several variables of the same type as a single statement:

String language = "java", version = "8 or newer";

 Separating declaration and initialization into statements:

int age; // declaration
age = 35; // initialization 

However, as we have already noted, these forms are rarely used.


Type inference

Since Java 10, you can write var instead of a specific type to force automatic type inference based on
the type of assigned value:

var variableName = initialization;

Here are two examples below:

var language = "Java"; // String
var version = 10; // int

This feature can be a bit controversial: on the one hand, it allows your code to be more concise. On
the other hand, since it doesn't indicate the type explicitly, it may affect the code readability in a bad
way. For now, it's enough to understand the basic idea. We will not use type inference in our theory
so that our educational platform is suitable for people who use earlier versions of Java. But if you
would like to practice it, you may use type inference in our exercises as they fully support Java 10.

Theory: Comments

Inside a Java program, you can write a special text that will be ignored by the java compiler — known
as the comment. Comments allow you to exclude code from the compilation process (disable it) or
clarify a piece of code to yourself or other developers. In our materials, we use comments in the
theory and practice lessons to explain how and why our code works.

The Java programming language supports three kinds of comments.

End-of-line comments

The java compiler ignores any text from // to the end of the line.

class Program {
    public static void main(String[] args) {
        // The line below will be ignored
        // System.out.println("Hello, World");
        // It prints the string "Hello, Java"
        System.out.println("Hello, Java"); // Here can be any comment
    }
}

In the example above the text after // is ignored by the compiler.


Multi-line comments

The compiler ignores any text from /* and the nearest */. It can be used as multiple and single-line
comments.

class Program {
    public static void main(String[] args) {
        /* This is a single-line comment */
        /*  This is an example of
            a multi-line comment */
  }
}

You can use comments inside other comments:

class Program {
    public static void main(String[] args) {
        /*
        System.out.println("Hello"); // print "Hello"
        System.out.println("Java");  // print "Java"
        */
    }
}

The part of the code above is ignored by the compiler because of /* ... */ comments.

Java documentation comments

The compiler ignores any text from /** to */ just like it ignores multi-line comments.

These kinds of comments can be used to automatically generate documentation about your source code by
using the javadoc tool. Usually, these comments are placed above declarations of classes, interfaces, methods
and so on. Some special labels such as @param or @return are often used for controlling the tool. However, they
are optional and we will not deal with them for now. Just don't be surprised in case you see one.

See the example below.

class Program {
    /**
     * The main method accepts an array of string arguments
     *
     * @param args from the command line
     */
    public static void main(String[] args) {
        // do nothing
    }
}

Do not be afraid if you have not understood the documentation comments completely. This will be
considered in other topics.
Theory: Coding style conventions

There's a question that you bump into when moving from simple single-line programs to more
complicated ones: how to write code that is clean and easy to read? This is trickier than it may seem
at the beginning, and this is quite important: in real life, programming is a process that involves a lot
of people that work together. In fact, you often spend more time reading code than writing it. Even
when you're working alone and writing a program "for yourself", after a while, it may become difficult
for you to understand your own program if it's badly written.

That is why you need to follow common best practices concerning programming style. This way,
other programmers and yourself can read your code easily. Writing good code may help you get
your first job and make a good impression on your colleagues.

Good coding style is like correct punctuation: you can manage without it,
butitsuremakesthingseasiertoread. – The Tidyverse Style Guide by Hadley Wickham

Java Conventions

A list of recommendations on how to write code for some particular language is usually called
a coding style guide or style conventions. The conventions help developers standardize and
support well-readable code. They are more like recommendations than strict rules, but by following
them a programmer creates code that is clean and consistent so that other developers will be happy
to work with it.

In most cases, companies and individual developers do not create their own style conventions. There
are two generally accepted Java conventions that are used all over the world:

 Oracle Code Conventions


 Google Style Guide

Sometimes they could be modified or extended by a particular company to meet their needs.

In all our code examples and exercises, we will follow the Oracle Code Conventions and we urge you
to do the same while learning here. After completing the course, you can follow any conventions you
want. Actually, it doesn't really matter which one to follow, the main challenge is to be consistent
across your code.

There is no need to learn all the conventions at once: just remember to open them from time to time
after learning some new syntactic concepts. We will provide the information throughout the course
when needed.

Now let's look at some of the most basic Java conventions according to the Oracle Code
Conventions.
The number of spaces

The first convention is to use 4 spaces as the unit of indentation in the whole program code. You
have already seen our code examples before and you might note that we used this value there.

Good:

public class NumberOfSpacesExample {

    public static void main(String[] args) {
        System.out.println("Hi!");
        System.out.println("I'm a Java program.");
    }
}

Very bad:

public class NumberOfSpacesExample {

  public static void main(String[] args) {
     System.out.println("Hi!");
   System.out.println("I'm a Java program.");
 }
}

As you can see, the second code example looks ugly and requires some effort to be read.

Sometimes tabulation is used to create an indentation. However, tab may correspond to 8 spaces


instead of 4 in some IDEs, that is why we recommend you stick to spaces in this course.

The location of curly braces

Some time ago, developers were arguing a lot about where to put opening and closing curly braces
in C-like programming languages. The next convention describes what to do in Java:

1. Put the opening curly brace at the end of the line where the block begins.
2. Put the closing curly brace at the beginning of the next line.

There are two examples below which illustrate these rules.

Good:

public class NumberOfSpacesExample {

    public static void main(String[] args) {
        System.out.println("Hi!");
        System.out.println("I'm a Java program.");
    }
}

Not that bad, but not Java-way:

public class NumberOfSpacesExample 
{
    public static void main(String[] args) 
    {
        System.out.println("Hi!");
        System.out.println("I'm a Java program.");
    }
}

Here, the second code example doesn't look ugly, but it is just not how it is generally done in Java.
Most of the common conventions follow the first example.

Avoid extra spaces

Sometimes you may add some spaces even if you don't really need them. This will reduce the readability of your
code.

 Avoid extra spaces within parentheses.

Good:

System.out.println("Hello!");
Bad:

System.out.println( "Hello!" );

 Avoid an extra space before an open parenthesis.

Good:

System.out.println("OK");
Bad:

System.out.println ("Shifted braces");

 Avoid extra spaces before a semicolon:

Good:

System.out.println("No extra spaces");
Bad:

System.out.println("It has an extra space") ;
The length of a line

The last recommendation concerns the maximum length of a line. The Oracle Code
Conventions propose avoiding lines longer than 80 characters. Plenty of developers consider this
restriction as outdated since modern monitors can easily display longer lines, whereas others would
go on following this rule, which is handy, for example, if laptops are used.

Keeping ourselves off this dispute, we will use 80 characters in the course to avoid scrollbars in our
examples and web code editor. We recommend that you do the same while learning here, but keep
in mind that you can violate this limitation after you start working on a real project or learning
elsewhere.

Other popular limit values are 100, 120, and sometimes even 140 characters.

Conclusion

Style guides provide the conventions to help create well-readable and consistent code. For Java, the
two most popular ones are the Oracle Code Conventions and Google style guide. One of their main
objectives is to provide an effective way for developers to work together on code. Because of that, it
is not as important to strictly follow one of the existing style guides as to stay consistent within the
project. Later on, you will learn a lot of things about Java and become a skillful programmer, but
maintaining the code style will always remain important. Do not worry, though: you do not need to
learn all the conventions at once. In all the following topics, we will follow the Oracle Code
Conventions and encourage you to do it with us!

Theory: Naming variables

Why is naming important?

As you may know, every variable has a name that uniquely identifies it among other variables.
Giving a good name to a variable may not be as simple as it seems. Experienced programmers put a
lot of care into naming to make their programs easy to understand. It is important because
programmers spend a lot of their time getting through the code written by other programmers. If
variables have bad names, even your own code will seem unclear to you in a few months.

Always try to give descriptive and concise names to all variables. As a result, any programmer will
enjoy your code for a long time.

In addition, there are two sets of rules that restrict the possible names for variables.

Rules for naming variables

Java has some rules for naming variables:

 names are case-sensitive;


 a name can include Unicode letters, digits, and two special characters ( $ ,  _ );
 a name cannot start with a digit;
 a name must not be a keyword ( class ,  static ,  int  are illegal names).

Based on these rules, you may conclude that whitespaces are not allowed in the name of a variable.
It is important not to break these rules; otherwise, the program will not work.

Here are some valid names of variables:

number, $ident, bigValue, _val, abc, k, var
Note that to keep backward compatibility the word  var  can be used as a variable name even after
Java 10 was released.

And here are some invalid ones:

@ab, 1c, !ab, class
Since Java 9 the single character  _  is an invalid name for a variable, but  _a  and  __  (a double  _  ) are
legal names.

Naming conventions for variables

Also, there are the following conventions for naming variables:

 if a variable name is a single word it should be in lowercase (for instance: number, price);


 if a variable name includes multiple words it should be in lowerCamelCase, i.e. the first word
should be in lowercase and each word after the first should have its first letter written in
uppercase (for instance: numberOfCoins);
 variable names should not start with _ and $ characters, although they are allowed;
 choose a name that makes sense, e.g. score makes more sense than s, although they are
both valid.

These conventions are optional, but it is strongly recommended to follow them. As we mentioned at
the beginning of this lesson, they make your code more readable for you and other Java
programmers.

Theory: Scanning the input

The standard input is a stream of data going into a program. It is supported by the operating
system. By default, the standard input obtains data from the keyboard input but it's possible to
redirect it from a file.

Actually, not all programs need to use the standard input. But we will often use it here to help you
master your programming skills! The typical way to solve programming problems is the following:

1. Read data from the standard input (System.in);


2. Process data to obtain a result;
3. Output the result to the standard output (System.out).

This type of code challenge can be easily tested by different formats of input data, and for this
reason, we will use them a lot.
Reading data with a scanner

The simplest way to obtain data from the standard input is to use the standard class  Scanner. It
allows a program to read values of different types (string, numbers, etc) from the standard input. In
this topic, we will consider reading data from the input.

To use this class you should add the following import statement to the top of your file with the
source code.

import java.util.Scanner;

Then you add the following construction after the import:

Scanner scanner = new Scanner(System.in);

With this line, we create an object of Scanner class, that enables us to use its methods. We will learn
more about creating objects in other topics. System.in indicates that the program will read text that
you type in the standard input. For now, you will always require this line exactly.

There are two ways to read strings with a Scanner class. If your input is an integer number or a single
word, you can read the data using next() method. As an example, the following code fragment
reads the user’s name and prints hello message:

String name = scanner.next();

System.out.println("Hello, " + name + "!");
For instance, the user's name is James. The output of the program will be the following:

Hello, James!

If the user's input is an integer number like 123, the program will output this number. Note that
the next() method will store 123 or another integer number as a string, even if we know that this
string consists of a number.

Hello, 123!
There are more specialized methods for reading other types of input values. In this topic, we only
consider reading strings.

But, if the user prints a compound name like Erich Maria, the program will output only the first word:

Hello, Erich!
In this case, you'll need another method, a nextLine() method, which reads and outputs the whole
line:
Hello, Erich Maria!
As you may notice, the next() method reads one word only and doesn't include any whitespace. By
contrast, the nextLine() method includes all space characters it encounters.

Note that in Java whitespace includes not only the space character, but mostly everything that looks
empty when printed: a tab, the newline character, and other non-printing characters.
In this article, we are dealing with space and newline characters: technically, we produce a
corresponding character when pressing Enter and starting a new line. The term "whitespace" is used
to refer to either of them. The more correct term to refer to what we’ve called “word” is token: it is a
piece of text surrounded by whitespace. We can say now that the next() method finds and returns
the next token, while the nextLine() reads all data till the end of the current line.

Now you can read a whole word and even a whole line invoking these two methods. To invoke both
of them correctly, it is important to know the difference between them.

Reading a multiline input

Reading multiline input may still be a bit tricky: you should take into account the position of the
cursor and the reading methods behavior.

Let’s investigate this process with an example:

|This is a simple

multiline input,

that is being read


| is a position of the cursor before reading the input.

If we invoke the next() method, the program will read the input till the whitespace, as indicated by
the color blue:

This| is a simple

multiline input,

that is being read


After invoking the nextLine() method the program reads the whole line starting from the
whitespace. This data is indicated by a green color. The nextLine() places the cursor at the
beginning of a new line (if there is such a line in your input):

This is a simple

|multiline input,

that is being read


Then, let's invoke the next() method two times. The first input is indicated by an orange color. You
may see that the position of the cursor is right after the word and before the whitespace:

This is a simple

multiline| input,

that is being read


Now we invoke the next() method again. The program outputs the second word in the
line without whitespace. It doesn't even matter how many space characters are there, because
the next() method will skip the whitespace until it finds the next token.

The second input is indicated by light blue color. As you may see, the position of the cursor is still at
the current line right before the new line and after the comma:

This is a simple

multiline input,|

that is being read

Here is a tricky thing about the nextLine() method that also shows a major difference between
the next() and the nextLine() methods. As you already know, the program will read input from the
position of the cursor till the new line (again, if there is such a line in your input). In this example the
cursor is located before the new line: thus, the nextLine() method will return an empty line ("") and
place the cursor at the beginning of a new line.

This is a simple

multiline input,

|that is being read


To sum up, let's look at the code as a whole and consider the variables we have just read:

import java.util.Scanner; 

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);  

        String word1 = scanner.next(); // "This"
        String line1 = scanner.nextLine();// "is a simple" 

        String word2 = scanner.next(); // "multiline"
        String word3 = scanner.next(); // "input,"
        String line2 = scanner.nextLine(); // "" 
        
    }
}
This example may seem artificial, but it should help you to catch the difference between these two
methods. Remember that usually the variables are named in a more expressive way.
Conclusion

We can read data from the standard input with a special Scanner class. The next() and
the nextLine() methods will help you to read strings. Both of them are used for getting input, but
they act differently. The next() method can read the input only till the whitespace while
the nextLine() method reads the input till the end of the whole line.

We recommend you to use the class Scanner when solving programming problems. It is one of the
simplest ways to get values from the standard input. More complex ways to read data will be
discussed in further topics.

Theory: Arithmetic operations

In real life, we often perform arithmetic operations. They help us to determine the change from a
purchase, calculate the area of a room, count the number of people in a queue, and so on. The same
operations are used in programs.

Binary arithmetic operators

The Java programming language provides operators to perform arithmetic operations:

 addition  +
 subtraction  -
 multiplication  *
 integer division  /
 remainder  %

The operators are called binary because they take two values as operands.

The following example prints results of addition, subtraction, and multiplication.

System.out.println(13 + 25); // prints 38
System.out.println(20 + 70); // prints 90

System.out.println(70 - 30); // prints 40
System.out.println(30 - 70); // prints -40

System.out.println(21 * 3);  // prints 63
System.out.println(20 * 10); // prints 200

The  /  operator returns the integer part of the division of two integer numbers, and any fractional
part is discarded.

System.out.println(8 / 3); // prints 2
System.out.println(41 / 5); // prints 8

The  %  in Java is the modulus or remainder operator. It returns the remainder of the division of two
numbers. Note, that when the dividend is less than the divisor, the quotient is zero and the
remainder equals the dividend. If you still feel uneasy about modulo operation, check out the wiki.
System.out.println(10 % 3) // prints 1, because 10 divided by 3 leaves a remainde
r of 1
System.out.println(12 % 4) // prints 0, because 12 divided by 4 leaves no remaind
er
System.out.println(5 % 9) // prints 5, because 5 divided by 9 leaves a remainder 
of 5

Writing complex expressions

The operations can be combined to write more complex expressions:

System.out.println(1 + 3 * 4 - 2); // prints 11

The calculation order coincides with arithmetic rules. Multiplication has a higher priority
level than addition and subtraction, so the operation 3 * 4 is calculated first.

To specify the order of execution we can use parentheses as in the following:

System.out.println((1 + 3) * (4 - 2)); // prints 8
As in arithmetic, parentheses can be nested. You can also use them for clarity.

Unary operators

A unary operator takes a single value as the operand.

 The unary plus operator indicates a positive value. It's an optional operator.

System.out.println(+5); // prints 5
 The unary minus operator negates a value or an expression.

System.out.println(-8);  // prints -8

System.out.println(-(100 + 4)); // prints -104

They both have a higher level of precedence than


the multiplication and division operators.
The precedence order

There is a precedence order of all arithmetic operators, including parentheses. The list below is
sorted from the highest to the lowest precedence level.

 parentheses
 unary plus/minus
 multiplication, division
 addition, subtraction

Theory: Integer types and operations

Basic information about integer types

Java provides several types which represent integer numbers including positive, negative
and zero. In practice, the most used types are int and long. The first type can store
numbers from a smaller range than the second one, but it is often enough (especially, in
this topic). You can perform all arithmetic operations ( +, -, *, /, %) with variables of integer
types.

Let's look at some examples below.

int two = 2;
int ten = 10;

int twelve = two + ten; // 12
int eight = ten - two;  // 8
int twenty = two * ten; // 20
int five = ten / two;   // 5
int zero = ten % two;   // 0, no remainder

int minusTwo = -two; // -2

This code demonstrates how to assign values to int variables as well as how to perform arithmetic
operations with them. We hope that you already understand all operations well.

To improve the readability of your code, the special underscore character _ can be used to separate
groups of digits within a number.

int million = 1_000_000;

You may also print a value of an int variable:

int number = 100;
System.out.println(number); // 100

All arithmetic operations work with the long type as well.


long one = 1L;
long twentyTwo = 22L; // L or l is a literal for longs
long bigNumber = 100_000_000_000L;

long result = bigNumber + twentyTwo - one; 
System.out.println(result); // 100000000021

If a number ends with the letter L or l it is considered as long, otherwise, it is int. We


recommended you to use the uppercase letter L because the lower case letter l is very
similar to the digit 1.

Note, use long's numbers only if it is really necessary (to process big values).

The forms of the assignment operator

Suppose, you want to add some value to a variable. You may write something like this:

int n = 10;
n = n + 4; // 14

The assignment operator = has several forms which combine it with an operation to avoid repeating
the variable twice:

int n = 10;
n += 4; // 14
As you may see, this form looks more concise. There are a few other possible forms  *=, /=, %= and
some others.

Reading numbers from the standard input

As a rule, to solve a problem you need to read some data from the outside world, process it, and
output the result. The following program reads two numbers from the standard input, adds them,
and prints the sum.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        int sum = a + b;

        System.out.println(sum);
    }
}
This simple code uses Scanner to read data.

If we know that the input numbers can be quite large, we can read long's instead of int's:

long a = scanner.nextLong();
long b = scanner.nextLong();

long sum = a + b;
No more lines need to be changed in this code.

Now you have enough knowledge to write useful programs that process data. You may use the
template above for solving code challenges in this lesson. Try to give meaningful names to variables
when solving problems.

Theory: Declaring a method

Built-in methods are a real deal when you manage routine tasks. Still, they are not a cure-all solution
since it's impossible to provide a standard method for each specific task. For example, you may need
to convert dollars to euros, count your monthly spendings, or even calculate a daily portion of seeds
for your parrot multiple times. That's when you create your own method to avoid repeating tons of
code!

In contrast to built-in methods, user-defined methods are created by the programmer. It is a


common practice to create a customized subprogram for a specific purpose.

But how to create it? Let's figure it out.

The syntax of the method

Technically, a method is just a structured part of code with a few components. In Java, a method is
always located inside a class. Let's take a closer look at a method that calculates a daily portion of
seeds for a parrot:
A method contains a set of modifiers, a type of the return value, a name, a list of parameters in
parentheses  ()  , and a body in curly brackets  {} . The combination of the name of the method and
the list of its parameters is known as a method signature. In our example, the signature
is  countSeeds(int, int) .

Some methods also have a list of exceptions – they define its behavior in case of some mistake in the
program. For now, we'll consider simple methods without exceptions.

Let's focus on the main components that we need to write simple methods from scratch.

Modifiers

The first words are so-called modifiers. There are two types of modifiers in Java: access
modifiers and non-access modifiers.

Access modifiers define the visibility of the method. For now, we're using a  public  access modifier,
which means there are no restrictions for invoking the method even from other classes.

Non-access modifiers provide information about the behavior of methods to JVM. The


modifier  static  means that the method belongs to the class and it can be accessed without creating
any object. This type of method is called a static method.

If the method is declared without the  static  modifier, it means that the method can be invoked only
through or with an object or instance of this class. Such methods are called instance methods.

Remember that there is a recommended order for the modifiers that you can find in the  Java
Language Specification . In our case, it is  public static .

Method parameters

In parentheses after the method name, we define the type, number, and order of the parameters. This reflects
how they will be passed to the method when it is invoked. Take a look at these signatures:

convertEurosToDollars(double dlrRate, long eur);

countMonthlySpendings(long food, long rent, long fun); 

replace(char a, char b);
As you know, there are also methods that don't have values passed to them. These methods are known as  non-
parameterized.

Body and return statement

Before a method completes its execution and exits, it returns a value known as a  return value. The

result of your method execution can be a value of primitive types like int, float, double, boolean, or


reference types like String. Take a look at our countSeeds method with a returning type int:
public static int countSeeds(int parrotWeight, int parrotAge) {   
    return parrotWeight / 5 + parrotAge; // it returns an int
}

What you see inside the curly brackets is known as the body of the method. The body holds

the logic we want to implement by our method: a set of statements to perform with the
passed values to obtain the result. Our method countSeeds takes two provided values,

performs certain calculations, and returns the result within a return statement.

Methods do not necessarily have to return a value. If we want a method not to return a

value but to perform operations only, the keyword void is used as a return type:

public static void countSeeds(int parrotWeight, int parrotAge) {
    System.out.println("give your parrot " + (parrotWeight / 5 + parrotAg
e) + 
    "g of seeds per day");
}

// this method just prints the line, so it returns 

no value

.        System.out.println("the number is positive");
    } else {
        return;
    }
}
Remember, that if you try to return a value from a method with a  void return type, a
compile error will be thrown.

What happens when we invoke a method

When invoking a method, we can write the returned value to some variable, print it out, or pass it on
to another method. This is how it looks in a program:

int myParrotWeight = 100;
int myParrotAge = 3;

int myParrotPortion = countSeeds(myParrotWeight, myParrotAge); 
// now myParrotPortion equals 23
There's another important thing to remember. When you pass a variable of a primitive type to a
method, a copy of this variable is created with the same value. Inside a method, only this copy is
processed. Any changes to this copy will not affect the variable that was passed.

Take a look:

public static void main(String[] args) {
    int portion = 100;   
    addSeeds(portion); // try to change portion 

    // now let's print a portion
    System.out.println(portion);
    // 100, because the method didn't change portion, only its copy
}

/**
 * The method increases the portion of seeds by 50 
 * and prints the resulting value
 */ 
public static void addSeeds(int portion) {
    portion += 50;
    System.out.println("The increased portion is " + portion); 
}
The output will look like:

The increased portion is 150
100
Although the addSeeds method changes the passed argument, it happens to a different
variable with its own value, leaving the value of the portion we've created intact.

Conclusion

As you see, a method is a block of code that contains a set of modifiers, a return type, a name, a list
of its parameters, and a body. A method may return a value or return nothing, which is indicated with
the void keyword.

If you know the syntax of methods, you can create your own and adjust them for your needs. This
practice will make your code more structured and reusable.

Server side

Spring Frame Work - IOC (Inversion of Control)


Spring ORM
Spring JDBC
Spring Web
Spring Struts
Spring MVC
Spring Security
Spring

Spring boot:

web services (RESTFUL API integration with Spring) - in demand


SOAP API - XML Based

Hibernate API framework/spring JDBC

Hibernate Projections

You might also like