Public Class ExampleProgram

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

public class ExampleProgram {

public static void main(String[ ] args) {


System.out.println("Hello World");
}
}

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

Java also supports comments that span multiple lines.


You start this type of comment with a forward slash followed by an
asterisk, and end it with an asterisk followed by a forward slash.
For example:/* This is also a
comment spanning
multiple lines */
Note that Java does not support nested multi-line comments.
However, you can nest single-line comments within multi-line
comments./* This is a single-line comment:

// a single-line comment

*/

Documentation Comments

Documentation comments are special comments that have the


appearance of multi-line comments, with the difference being that
they generate external documentation of your source code. These
begin with a forward slash followed by two asterisks, and end with
an asterisk followed by a forward slash.
For example:/** This is a documentation comment */
/** This is also a
documentation comment */
Javadoc is a tool which comes with JDK and it is used for
generating Java code documentation in HTML format from Java
source code which has required documentation in a predefined
format.

When a documentation comment begins with more than two


asterisks, Javadoc assumes that you want to create a "box"
around the comment in the source code. It simply ignores the
extra asterisks.
For example:/**********************

This is the start of a method

***********************/
This will retain just the text "This is the start of a method" for the
documentation.

variables

Variables store data for processing.


A variable is given a name (or identifier), such as area, age,
height, and the like. The name uniquely identifies each variable,
assigning a value to the variable and retrieving the value stored.

Variables have types. Some examples:


- int: for integers (whole numbers) such as 123 and -456
- double: for floating-point or real numbers with optional decimal
points and fractional parts in fixed or scientific notations, such as
3.1416, -55.66.
- String: for texts such as "Hello" or "Good Morning!". Text strings
are enclosed within double quotes.
You can declare a variable of a type and assign it a value.
Example:String name = "David";
This creates a variable called name of type String, and assigns it
the value "David".
It is important to note that a variable is associated with a type,
and is only capable of storing values of that particular type. For
example, an int variable can store integervalues, such as 123;
but it cannot store real numbers, such as 12.34, or texts, such as
"Hello".

Addition

The + operator adds together two values, such as two constants, a


constant and a variable, or a variable and a variable. Here are a few
examples of addition:int sum1 = 50 + 10;
int sum2 = sum1 + 66;
int sum3 = sum2 + sum2;

Subtraction

The - operator subtracts one value from another.int sum1 = 1000 - 10;
int sum2 = sum1 - 5;
int sum3 = sum1 - sum2;

Multiplication

The * operator multiplies two values.int sum1 = 1000 * 2;


int sum2 = sum1 * 10;
int sum3 = sum1 * sum2;
Division

The / operator divides one value by another.int sum1 = 1000 / 5;


int sum2 = sum1 / 2;
int sum3 = sum1 / sum2;
In the example above, the result of the division equation will be a
whole number, asint is used as the data type. You can use double to
retrieve a value with a decimal point.

The modulo (or remainder) math operation performs


an integer division of one value by another, and returns the
remainder of that division.
The operator for the modulo operation is the percentage (%)
character.
Example:
int value = 23;
int res = value % 6; // res is 5Try It Yourself

Dividing 23 by 6 returns a quotient of 3, with a remainder of 5.


Thus, the value of 5 is assigned to the res variable.

An increment or decrement operator provides a more


convenient and compact way to increase or decrease the value of
a variable by one.
For instance, the statement x=x+1; can be simplified to ++x;
Example:
int test = 5;
++test; // test is now 6Try It Yourself

The decrement operator (--) is used to decrease the value of a


variable by one.
int test = 5;
--test; // test is now 4

Prefix & Postfix


Two forms, prefix and postfix, may be used with both the
increment and decrement operators.
With prefix form, the operator appears before the operand, while
in postfix form, the operator appears after the operand. Below is
an explanation of how the two forms work:
Prefix: Increments the variable's value and uses the new value in
the expression.
Example:
int x = 34;
int y = ++x; // y is 35Try It Yourself

The value of x is first incremented to 35, and is then assigned to


y, so the values of both x and y are now 35.
Postfix: The variable's value is first used in the expression and is
then increased.
Example:
int x = 34;
int y = x++; // y is 34

Assignment Operators

You are already familiar with the assignment operator (=), which
assigns a value to a variable.int value = 5;
This assigned the value 5 to a variable called value of type int.

Java provides a number of assignment operators to make it easier


to write code.
Addition and assignment (+=):
int num1 = 4;
int num2 = 8;
num2 += num1; // num2 = num2 + num1;

// num2 is 12 and num1 is 4Try It Yourself


Subtraction and assignment (-=):
int num1 = 4;
int num2 = 8;
num2 -= num1; // num2 = num2 - num1;

// num2 is 4 and num1 is 4Try It Yourself

Similarly, Java supports multiplication and assignment (*=),


division and assignment (/=), and remainder and assignment
(%=)
String Concatenation

The + (plus) operator between strings adds them together to


make a new string. This process is called concatenation.
The resulted string is the first string put together with the second
string.
For example:
String firstName, lastName;
firstName = "David";
lastName = "Williams";

System.out.println("My name is " + firstName +" "+lastName);

// Prints: My name is David Williams


Getting User Input

While Java provides many different methods for getting user


input, the Scanner object is the most common, and perhaps the
easiest to implement. Import the Scanner class to use
theScanner object, as seen here:import java.util.Scanner;
In order to use the Scanner class, create an instance of the class
by using the following syntax:Scanner myVar = new
Scanner(System.in);
You can now read in different kinds of input data that the user
enters.
Here are some methods that are available through the Scanner
class:
Read a byte - nextByte()
Read a short - nextShort()
Read an int - nextInt()
Read a long - nextLong()
Read a float - nextFloat()
Read a double - nextDouble()
Read a boolean - nextBoolean()
Read a complete line - nextLine()
Read a word - next()

Example of a program used to get user input:


import java.util.Scanner;

class MyClass {
public static void main(String[ ] args) {
Scanner myVar = new Scanner(System.in);
System.out.println(myVar.nextLine());
}
}Try It Yourself

This will wait for the user to input something and print that input.
The code might seem complex, but you will understand it all in
the upcoming lessons.
Decision Making

Conditional statements are used to perform different actions


based on different conditions.
The if statement is one of the most frequently used conditional
statements.
If the if statement's condition expression evaluates to true, the
block of code inside the ifstatement is executed. If the expression
is found to be false, the first set of code after the end of
the if statement (after the closing curly brace) is executed.
Syntax:if (condition) {
//Executes when the condition is true
}
Any of the following comparison operators may be used to form
the condition:
< less than
> greater than
!= not equal to
== equal to
<= less than or equal to
>= greater than or equal to

For example:
int x = 7;
if(x < 42) {
System.out.println("Hi");
}Try It Yourself

Remember that you need to use two equal signs (==) to test for
equality, since a single equal sign is the assignment operator..
if...else Statements

An if statement can be followed by an optional else statement,


which executes when the condition evaluates to false.
For example:
int age = 30;

if (age < 16) {


System.out.println("Too Young");
} else {
System.out.println("Welcome!");
}
//Outputs "Welcome"Try It Yourself

As age equals 30, the condition in the if statement evaluates to


false and the elsestatement is executed.
else if Statements

Instead of using nested if-else statements, you can use the else
if statement to check multiple conditions.
For example:
int age = 25;

if(age <= 0) {
System.out.println("Error");
} else if(age <= 16) {
System.out.println("Too Young");
} else if(age < 100) {
System.out.println("Welcome!");
} else {
System.out.println("Really?");
}
//Outputs "Welcome!"Try It Yourself

The code will check the condition to evaluate to true and execute
the statements inside that block.
You can include as many else if statements as you need.

Logical Operators

Logical operators are used to combine multiple conditions.

Let's say you wanted your program to output "Welcome!" only


when the variable age is greater than 18 and the
variable money is greater than 500.
One way to accomplish this is to use nested if statements:
if (age > 18) {
if (money > 500) {
System.out.println("Welcome!");
}
}Try It Yourself

However, using the AND logical operator (&&) is a better way:


if (age > 18 && money > 500) {
System.out.println("Welcome!");
}Try It Yourself

If both operands of the AND operator are true, then the condition
becomes true.

The OR Operator

The OR operator (||) checks if any one of the conditions is true.


The condition becomes true, if any one of the operands evaluates
to true.
For example:
int age = 25;
int money = 100;

if (age > 18 || money > 500) {


System.out.println("Welcome!");
}
//Outputs "Welcome!"Try It Yourself

The code above will print "Welcome!" if age is greater than


18 or if money is greater than 500.

The NOT (!) logical operator is used to reverse the logical state of
its operand. If a condition is true, the NOT logical operator will
make it false.
Example:
int age = 25;
if(!(age > 18)) {
System.out.println("Too Young");
} else {
System.out.println("Welcome");
}
//Outputs "Welcome"Try It Yourself

!(age > 18) reads as "if age is NOT greater than 18".

The switch Statement

A switch statement tests a variable for equality against a list of


values. Each value is called acase, and the variable being
switched on is checked for each case.
Syntax:switch (expression) {
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
- When the variable being switched on is equal to a case, the
statements following that casewill execute until
a break statement is reached.
- When a break statement is reached, the switch terminates,
and the flow of control jumps to the next line after
the switch statement.
- Not every case needs to contain a break. If no break appears,
the flow of control will fall through to subsequent cases until
a break is reached.

The example below tests day against a set of values and prints a
corresponding message.
int day = 3;

switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
// Outputs "Wednesday"Try It Yourself

You can have any number of case statements within a switch.


Each case is followed by the comparison value and a colon.

The default Statement

A switch statement can have an optional default case, which


must appear at the end of the switch.
The default case can be used for performing a task when none of
the cases is matched.

For example:
int day = 3;

switch(day) {
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Weekday");
}
// Outputs "Weekday"Try It Yourself
No break is needed in the default case, as it is always the last
statement in the switch.

while Loops

A loop statement allows to repeatedly execute a statement or


group of statements.

A while loop statement repeatedly executes a target statement


as long as a given condition is true.

Example:
int x = 3;

while(x > 0) {
System.out.println(x);
x--;
}
/*
Outputs
3
2
1
*/Try It Yourself

The while loops check for the condition x > 0. If it evaluates to


true, it executes the statements within its body. Then it checks for
the statement again and repeats.
Notice the statement x--. This decrements x each time the loop
runs, and makes the loop stop when x reaches 0.
Without the statement, the loop would run forever.
for Loops
Another loop structure is the for loop. A for loop allows you to
efficiently write a loop that needs to execute a specific number of
times.
Syntax:for (initialization; condition; increment/decrement) {
statement(s)
}
Initialization: Expression executes only once during the
beginning of loop
Condition: Is evaluated each time the loop iterates. The loop
executes the statement repeatedly, until this condition returns
false.
Increment/Decrement: Executes after each iteration of the
loop.

The following example prints the numbers 1 through 5.


for(int x = 1; x <=5; x++) {
System.out.println(x);
}

/* Outputs
1
2
3
4
5
*/Try It Yourself

This initializes x to the value 1, and repeatedly prints the value of


x, until the condition x<=5 becomes false. On each iteration, the
statement x++ is executed, incrementing x by one.
Notice the semicolon (;) after initialization and condition in the
syntax.

Arrays

An array is a collection of variables of the same type.


When you need to store a list of values, such as numbers, you can
store them in an array, instead of declaring separate variables for
each number.

To declare an array, you need to define the type of the elements


with square brackets.
For example, to declare an array of integers:int[ ] arr;
The name of the array is arr. The type of elements it will hold
is int.

Now, you need to define the array's capacity, or the number of


elements it will hold. To accomplish this, use the keyword new.int[
] arr = new int[5];
The code above declares an array of 5 integers.
In an array, the elements are ordered and each has a specific and
constant position, which is called an index.

To reference elements in an array, type the name of


the array followed by the index position within a pair of square
brackets.
Example:arr[2] = 42;
This assigns a value of 42 to the element with 2 as its index.
Note that elements in the array are identified with zero-
based index numbers, meaning that the first element's index is 0
rather than one. So, the maximum index of the array int[5] is 4.

Initializing Arrays

Java provides a shortcut for instantiating arrays of primitive types and strings.
If you already know what values to insert into the array, you can use
an array literal.
Example of an array literal:

String[ ] myNames = { "A", "B", "C", "D"};


System.out.println(myNames[2]);
// Outputs "C"Try It Yourself

Place the values in a comma-separated list, enclosed in curly braces.


The code above automatically initializes an array containing 4 elements, and stores
the provided values.
Sometimes you might see the square brackets placed after the array name, which
also works, but the preferred way is to place the brackets after the array's data
type.

Array Length

You can access the length of an array (the number of elements it stores) via
its lengthproperty.
Example:
int[ ] intArr = new int[5];
System.out.println(intArr.length);

//Outputs 5

Arrays

Now that we know how to set and get array elements, we can calculate the sum of
all elements in an array by using loops.
The for loop is the most used loop when working with arrays, as we can use
the length of thearray to determine how many times to run the loop.

int [ ] myArr = {6, 42, 3, 7};


int sum=0;
for(int x=0; x<myArr.length; x++) {
sum += myArr[x];
}
System.out.println(sum);

// 58Try It Yourself

In the code above, we declared a variable sum to store the result and assigned it 0.
Then we used a for loop to iterate through the array, and added each element's
value to the variable.
The condition of the for loop is x<myArr.length, as the last element's index
ismyArr.length-1.

Enhanced for Loop

The enhanced for loop (sometimes called a "for each" loop) is used to traverse
elements in arrays.
The advantages are that it eliminates the possibility of bugs and makes the code
easier to read.
Example:

int[ ] primes = {2, 3, 5, 7};

for (int t: primes) {


System.out.println(t);
}

/*
2
3
5
7
*/Try It Yourself

The enhanced for loop declares a variable of a type compatible with the elements
of the arraybeing accessed. The variable will be available within the for block, and
its value will be the same as the current array element.
So, on each iteration of the loop, the variable t will be equal to the corresponding
element in thearray.
Notice the colon after the variable in the syntax.

Multidimensional Arrays

Multidimensional arrays are array that contain other arrays. The two-
dimensional array is the most basic multidimensional array.
To create multidimensional arrays, place each array within its own set of square
brackets. Example of a two-dimensional array:int[ ][ ] sample = { {1, 2, 3}, {4, 5,
6} };
This declares an array with two arrays as its elements.
To access an element in the two-dimensional array, provide two indexes, one for
the array, and another for the element inside that array.
The following example accesses the first element in the second array of sample.

int x = sample[1][0];
System.out.println(x);

// Outputs 4Try It Yourself

The array's two indexes are called row index and column index.

Multidimensional Arrays

You can get and set a multidimensional array's elements using the same pair of
square brackets.
Example:

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


myArr[0][2] = 42;
int x = myArr[1][0]; // 4Try It Yourself

The above two-dimensional array contains three arrays. The first array has three
elements, the second has a single element and the last of these has three
elements.
In Java, you're not limited to just two-dimensional arrays. Arrays can be nested
within arrays to as many levels as your program needs. All you need to declare
anarray with more than two dimensions, is to add as many sets of empty brackets
as you need. However, these are harder to maintain.
Remember, that all array members must be of the same type.

Object-Orientation

Java uses Object-Oriented Programming (OOP), a programming style that is


intended to make thinking about programming closer to thinking about the real
world.
In OOP, each object is an independent unit with a unique identity, just as objects
in the real world are.
An apple is an object; so is a mug. Each has its unique identity. It's possible to
have two mugs that look identical, but they are still separate, unique objects.
Objects also have characteristics, which are used to describe them.
For example, a car can be red or blue, a mug can be full or empty, and so on. These
characteristics are also called attributes. An attribute describes the current state
of an object.
In the real world, each object behaves in its own way. The car moves, the phone
rings, and so on.
The same applies to objects: behavior is specific to the object's type.
In summary, in object oriented programming, each object has three
dimensions:identity, attributes, and behavior.
Attributes describe the object's current state, and what the object is capable of
doing is demonstrated through the object's behavior.

Classes

A class describes what the object will be, but is separate from the object itself.
In other words, classes can be described as blueprints, descriptions, or definitions
for an object. You can use the same class as a blueprint for creating multiple
objects. The first step is to define the class, which then becomes a blueprint for
object creation.

Each class has a name, and each is used to define attributes and behavior.
Some examples of attributes and behavior:
Methods

Methods define behavior. A method is a collection of


statements that are grouped together to perform an
operation. System.out.println() is an example of a method.
You can define your own methods to perform your desired
tasks.
Let's consider the following code:

class MyClass {

static void sayHello() {


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

public static void main(String[ ] args) {


sayHello();
}
}
// Outputs "Hello World!"Try It Yourself

The code above declares a method called "sayHello", which


prints a text, and then gets called in main.
To call a method, type its name and then follow the name
with a set of parentheses.

Method Parameters

You can also create a method that takes some data,


called parameters, along with it when you call it. Write
parameters within the method's parentheses.
For example, we can modify our sayHello() method to take
and output a String parameter.

class MyClass {

static void sayHello(String name) {


System.out.println("Hello " + name);
}

public static void main(String[ ] args) {


sayHello("David");
sayHello("Amy");
}
}
// Hello David
// Hello AmyTry It Yourself

The method above takes a String called name as a


parameter, which is used in the method's body. Then, when
calling the method, we pass the parameter's value inside the
parentheses.
Methods can take multiple, comma-separated parameters.
The advantages of using methods instead of simple
statements include the following:
- code reuse: You can write a method once, and use it
multiple times, without having to rewrite the code each time.
- parameters: Based on the parameters passed in, methods
can perform various actions.

The Return Type

The return keyword can be used in methods to return a value.


For example, we could define a method named sum that returns the sum of its two
parameters.static int sum(int val1, int val2) {
return val1 + val2;
}
Notice that in the method definition, we defined the return type before we defined
the methodname. For our sum method, it is int, as it takes two parameters of the
type int and returns their sum, which is also an int.
The static keyword will be discussed in a future lesson.
Now, we can use the method in our main.

class MyClass {

static int sum(int val1, int val2) {


return val1 + val2;
}

public static void main(String[ ] args) {


int x = sum(2, 5);
System.out.println(x);
}
}
// Outputs "7"Try It Yourself

As the method returns a value, we can assign it to a variable.


When you do not need to return any value from your method, use the
keyword void.
Notice the void keyword in the definition of the main method - this means that
main does not return anything.

The Return Type

Take a look at the same code from our previous lesson with explaining
comments, so you can better understand how it works:// returns an int
value 5
static int returnFive() {
return 5;
}

// has a parameter
static void sayHelloTo(String name) {
System.out.println("Hello " + name);
}

// simply prints"Hello World!"


static void sayHello() {
System.out.println("Hello World!");
}
Having gained knowledge of method return types and parameters, let's take
another look at the definition of the main method. public static void
main(String[ ] args)
This definition indicates that the main method takes an array of Strings as
its parameters, and does not return a value.

You might also like