Public Class ExampleProgram
Public Class ExampleProgram
Public Class ExampleProgram
class MyClass {
public static void main(String[ ] args) {
System.out.println("Hello World");
}
}
// a single-line comment
*/
Documentation Comments
***********************/
This will retain just the text "This is the start of a method" for the
documentation.
variables
Addition
Subtraction
The - operator subtracts one value from another.int sum1 = 1000 - 10;
int sum2 = sum1 - 5;
int sum3 = sum1 - sum2;
Multiplication
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.
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
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
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
If both operands of the AND operator are true, then the condition
becomes true.
The OR Operator
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 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
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
Example:
int x = 3;
while(x > 0) {
System.out.println(x);
x--;
}
/*
Outputs
3
2
1
*/Try It Yourself
/* Outputs
1
2
3
4
5
*/Try It Yourself
Arrays
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:
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.
// 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.
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:
/*
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);
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:
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
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
class MyClass {
Method Parameters
class MyClass {
class MyClass {
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);
}