Head First Java Edition II Article.
CHAPTER 1.
1.Breaking the Surface,
1.1,
*The way Java works,
*How Java Works,
*A program is converted (compiled) into machine language for the majority of programming languages. After that, you can run the machine language program (or run).
* Java is similar in that it compiles source code into bytecode first. The bytecode can subsequently be compiled into machine code by the Java Virtual Machine (JVM). Java’s bytecode can run on any device thanks to the JVM, which is why it’s characterized as a “write once, run anywhere” language.
* This is a simplified explanation of how Java works. There’s a lot more to it than that.
* Every operating system, as shown in the picture above, has a Java Virtual Machine on top of it, which is required to run a Java program. It is a platform independent environment that simply converts Java into code that a computer understands because every operating system has its own Java Virtual Machine.
* Let’s look at a simple example to see how this works. The idea is to create a single app (an interactive party invitation) that will function on any device your friends have.
*Source: Make a document that will be used as a source. Make use of a well-established procedure (In this case, the Java language).
*Compiler: Use a source code compiler to compile your document. The compiler checks for errors and won’t let you compile until It’s satisfied that everything will run correctly.
*Output/Byte code: The compiler creates a new document, coded into Java bytecode. Any device that can run Java will be able to interpret and translate this file into something that it can use. The compiled bytecode is platform Independent.
*JVM: Your friends don’t have a physical Java Machine, but they all have a virtual Java machine (implemented In software) running inside their electronic gadgets. The bytecode is read and executed by the virtual machine.
1.2,
*Code structure in Java,
*Source file: A java source file can have several classes. Not more than one of these classes may be declared public. If the source file contains a public class, the source file’s name must be the public class’s name with a .java suffix. The java compiler creates a .class file for each class found in the source file.
*Class file: A class has one or more methods.
*Statements: Method has multiple statements.
1.3,
*Anatomy of a Class,
1.4,
*The main() Method,
* public static void main(String[] args), is the most important Java method. When you start learning java programming, this is the first method you encounter. Remember the first Java Hello World program you wrote that runs and prints “Hello World”?
* public static void main(String[] args),
Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args). You can only change the name of String array argument, for example you can change args to myStringArgs.
Also String array argument can be written as String… args or String args[].
Let’s look at the java main method closely and try to understand each of its parts.
*Public,
*This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it’s not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public. Let’s see what happens if we define the main method as non-public.
public class Test {
static void main(String[] args){
System.out.println(“Hello World”);
}
}
$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
$
*Static,
*When java runtime starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present. Let’s see what happens when we remove static from java main method.
public class Test {
public void main(String[] args){
System.out.println(“Hello World”);
}
}
$ javac Test.java
$ java Test
Error: Main method is not static in class Test, please define the main method as:
public static void main(String[] args)
$
*Void,
*Java programming mandates that every method provide the return type. Java main method doesn’t return anything, that’s why it’s return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give compilation error as an unexpected return value. For example, if we have the main method like below.
public class Test {
public static void main(String[] args){
return 0;
}
}
*We get below error when above program is compiled.
$ javac Test.java
Test.java:5: error: incompatible types: unexpected return value
return 0;
^
1 error
$
*Main,
*This is the name of java main method. It’s fixed and when we start a java program, it looks for the main method. For example, if we have a class like below.
public class Test {
public static void mymain(String[] args){
System.out.println(“Hello World”);
}
}
*And we try to run this program, it will throw an error that the main method is not found.
$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
$
*String[] args,
*Java main method accepts a single argument of type String array. This is also called as java command line arguments. Let’s have a look at the example of using java command line arguments.
public class Test {
public static void main(String[] args){
for(String s : args){
System.out.println(s);
}
}
}
*Above is a simple program where we are printing the command line arguments. Let’s see how to pass command line arguments when executing above program.
$ javac Test.java
$ java Test 1 2 3
1
2
3
$ java Test “Hello World” “Pankaj Kumar”
Hello World
Pankaj Kumar
$ java Test
$
1.5,
*Looping,
*Loops in Java,
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loops in Java.
* Simple for Loop
* For-each or Enhanced for Loop
* Labeled for Loop
* Java Simple for Loop,
A simple for loop is the same as C
/C++
* We can initialize the variable
* check condition and increment/decrement value. It consists of four parts:
⦁ Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
⦁ Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
⦁ Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
⦁ Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Flowchart:
Example:
ForExample.java
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
*Java Nested for Loop,
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.
Example:
NestedForExample.java
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+” “+j);
}//end of i
}//end of j
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Pyramid Example 1:
PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print(“* “);
}
System.out.println();//new line
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Pyramid Example 2:
PyramidExample2.java
public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j — ){
System.out.print(“* “);
}
System.out.println();//new line
}
}
}
Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*
*Java for-each Loop,
The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example:
ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
*Java Labeled For Loop,
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.
Note: The break and continue keywords breaks or continues the innermost for loop respectively.
Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
Example:
LabeledForExample.java
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+” “+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
LabeledForExample2.java
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+” “+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
*Java Infinitive for Loop,
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
ForExample.java
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println(“infinitive loop”);
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
*Java for Loop vs while Loop vs do-while Loop,
* Java While Loop,
The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. When the condition becomes false, we exit the while loop.
Example:
i <=100
2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable.
Example:
i++;
Flowchart of Java While Loop
Here, the important thing about while loop is that, sometimes it may not even execute. If the condition to be tested results into false, the loop body is skipped and first statement after the while loop will be executed.
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
WhileExample.java
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}
Example:
WhileExample2.java
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
System.out.println(“infinitive while loop”);
}
}
}
Output:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
*Java do-while Loop,
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
The different parts of do-while loop:
41.6M
863
C++ vs Java
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop variable.
Example:
i++;
Note: The do block is executed at least once, even if the condition is false.
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
DoWhileExample.java
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Example:
DoWhileExample2.java
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println(“infinitive do while loop”);
}while(true);
}
}
Output:
infinitive do while loop
infinitive do while loop
infinitive do while loop
1.6,
* Conditional branching (if tests),
Conditional branching is a logical part of the program. Based on the specific condition we can tell to program which way the program should go.
if <it’s cold outside> then I will get my jacket
else I’m good with T-shirt
The above example shows a simple version of conditional branching in plain language. <it’s cold outside> this is a logical condition and it can be true or false. If it’s true then we will perform some action and if it’s false we can perform another action.
The logical condition can be stored in boolean type variable and can be used as part of the conditional branching statements(if-esle, ternary operator).
// class and main method is not displayed
boolean b = true;
if (b) {
System.out.println(“Java is great!”);
}else {
System.out.println(“Python is great!”);
}
in above the snippet we can see the simple if-else statement.
⦁ The output of this program is Java is great!
⦁ The if statement always takes boolean datatype as its condition, between the parenthesis. If the condition is true, if’s body will be executed and if it is false else’s body will be executed.
⦁ This code will always print Java is great! because we hardcoded the value of our boolean as true. Usually, we get boolean from some conditions (comparison, event, etc.).
Comparison Operators
Let’s talk about how we can get a logical boolean. One way to get it is by using comparison operators.
⦁ == equal to operator. We can use this operator to compare primitive data types on equality. For objects, it will compare if two references are pointing to the same object or not(we will talk more in the future).
⦁ != not equal to operator. Exactly the same as equal, but works in reverse.
⦁ > greater than operator. To compare if one number is greater than another.
⦁ >= greater than or equal to operator. To compare if one number is greater or equal to another number.
⦁ < less than
⦁ <= less than or equal to
Using == to compare numbers on equality.