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

Chapter I - Intro

Uploaded by

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

Chapter I - Intro

Uploaded by

Temu Dereje
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Advanced Programming CH#1 - Intro By: Lecturer Abebe A.

(MSc, Computer Science)


CHAPTER ONE
INTRODUCTION TO JAVA PROGRAMMING
Overview
Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3
billion devices run Java.
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!
Why Use Java?
 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming language in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs and allows code to
be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
Java Terminology
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine (JVM): This is generally referred to as JVM. There are three execution phases of a
program. They are written, compile and run the program.
 Writing a program is done by a java programmer like you and me.
 The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes the Java program as input and generates bytecode as output.
 In the Running phase of a program, JVM executes the bytecode generated by the compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the
compiler. Every Operating System has a different JVM but the output they produce after the execution of
bytecode is the same across all the operating systems. This is why Java is known as a platform-independent
language.
2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the java source
code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the
bytecode, a disassembler like javap can be used.
3. Java Development Kit (JDK): While we were using the term JDK when we learn about bytecode and JVM.
So, as the name suggests, it is a complete Java development kit that includes everything including compiler, Java
Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to
install JDK on our computer in order to create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java
program to run; however, we cannot compile it. JRE includes a browser, JVM, applet supports, and plugins. For
running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM
has a program called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So
Java makes the life of a programmer easy by handling memory management. However, programmers should be

1 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
careful about their code whether they are using objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class files to load.
By default, JDK provides many libraries. If you want to include external libraries they should be added to the
classpath.
Primary/Main Features of Java
1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or macOS which means
if we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a
different JVM, but the output produced by all the OS is the same after the execution of bytecode. That is why we
call java a platform-independent language.
2. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a
way of object-oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator
overloading, multiple inheritances, and Explicit memory allocation.
4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort
into checking errors as early as possible, which is why the java compiler is able to detect even those errors that
are not easy to detect by another programming language. The main features of java that make it robust are
garbage collection, Exception Handling, and memory allocation.
5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or
buffer overflow are impossible to exploit in Java. Also java programs run in an environment that is independent of
the os(operating system) environment which makes java programs more secure .
6. Distributed: We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs
can be easily distributed on one or more systems that are connected to each other through an internet
connection.
7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of the CPU.
8. Portable: As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any platform for execution
makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and
at some time java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it
only compiles those methods that are called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new
methods to existing classes and even create new classes through sub-classes. Java even supports functions
written in other languages such as C, C++ which are referred to as native methods.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications
without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional
security as its role is to check the code for any violation of access.
12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which corresponds
to our applications (program) but contains code in binary format. It provides ease t architecture-neutral ease as
bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT
industry globally worldwide.

2 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
13. Power of compilation and interpretation: Most languages are designed with purpose either they are
compiled language or they are interpreted language. But java integrates arising enormous power as Java
compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent
executable code.
// Importing classes from packages
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Print statement
System.out.println("Welcome to GeeksforGeeks");
}
}
Output
Welcome to GeeksforGeeks
Explanation:
1. Comments: Comments are used for explaining code and are used in a similar manner in Java or C or C++.
Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple
lines.
Single line Comments:
Syntax:
// Single line comment
Multi-line comments:
Syntax:
/* Multi line comments*/
2. import java.io.*: This means all the classes of io package can be imported. Java io package provides a set of
input and output streams for reading and writing data to files or other input or output sources.
3. class: The class contains the data and methods to be used in the program. Methods define the behavior of the
class. Class GFG has only one method Main in JAVA.
4. static void Main(): static keyword tells us that this method is accessible without instantiating the class.
5. void: keywords tell that this method will not return anything. The main() method is the entry point of our
application.
6. System.in: This is the standard input stream that is used to read characters from the keyboard or any other
standard input device.
7. System.out: This is the standard output stream that is used to produce the result of a program on an output
device like the computer screen.
8. println(): This method in Java is also used to display text on the console. It prints the text on the console and
the cursor moves to the start of the next line at the console. The next printing takes place from the next line.
9. String []args: This is the argument passed to the main function which is an array of strings with the array name
args. One can choose their own flexible name but this name is used by many developers.
Everything in java, is represented in Class as an object including the main function.
Java Classes/Objects
Java is an object-oriented programming language. Everything in Java is associated with classes
and objects, along with its attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such as drive and brake. A Class
is like an object constructor, or a "blueprint" for creating objects.
Create a Class

3 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so
now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}}
Multiple Objects
You can create multiple objects of one class:
Example - Create two objects of Main:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Java Class Attributes/Fields
In the previous chapter, we used the term "variable" for x in the example (as shown below). It is
actually an attribute of the class. Or you could say that class attributes are variables within a
class:
Example
Create a class called "Main" with two attributes: x and y:
public class Main {
int x = 5;
int y = 3;
}
4 Gambella University, Department of Computer Science Academic Year – 2015 E.C
Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
Another term for class attributes is fields.
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax (.):
The following example will create an object of the Main class, with the name myObj. We use the x
attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Java Methods
A method is a block of code which only runs when it is called. You can pass data, known as parameters,
into a method. Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object of the Main class. You will
learn more about objects and how to access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn more about return values
later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

5 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
public static void main(String[] args) {
myMethod();
}
}
Java Basic Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to print
"Hello World" to the screen:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}}
Example explained
Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A
class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class name
and add ".java" to the end of the filename. To run the example above on your computer, make sure that
Java is properly installed:
The output should be:
Hello World
The main Method
The main() method is required and you will see it in every Java program:
public static void main(String[] args)
Any code inside the main() method will be executed. Don't worry about the keywords before and after
main. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and
that every program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
}
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output". The
println() method, short for "print line", is used to print a value to the screen (or a file). Don't worry too
much about System, out and println(). Just know that you need them together to print stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Environment Setting (Java Installation Procedures)
Some PCs might have Java already installed. To check if you have Java installed on a Windows PC,
search in the start bar for Java or type the following in Command Prompt (cmd.exe):

6 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
If Java is installed, you will see something like this (depending on version):

If you do not have Java installed on your computer, you can download it for free at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an
Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly
useful when managing larger collections of Java files.
Setup for Windows
To install Java on Windows:
1. Go to "System Properties" (Can be found on Control Panel > System and Security > System >
Advanced System Settings)
2. Click on the "Environment variables" button under the "Advanced" tab
3. Then, select the "Path" variable in System variables and click on the "Edit" button
4. Click on the "New" button and add the path where Java is installed, followed by \bin. By default,
Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you
installed it). In that case, You will have to add a new path with: C:\Program Files\Java\jdk-
11.0.1\bin
Then, click "OK", and save the settings
5. At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on
your machine
Java User Input
The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class,
create an object of the class and use any of the available methods found in the Scanner class documentation. In
our example, we will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}}
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at
the table below:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user

7 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message
(like "InputMismatchException").
Java Output / Print
Print Text
You learned from the previous chapter that you can use the println() method to output values or print text
in Java:
Example
System.out.println("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each method:
Example
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);
The Print() Method
There is also a print() method, which is similar to println().

8 Gambella University, Department of Computer Science Academic Year – 2015 E.C


Advanced Programming CH#1 - Intro By: Lecturer Abebe A. (MSc, Computer Science)
The only difference is that it does not insert a new line at the end of the output:
Example
System.out.print("Hello World! ");
System.out.print("I will print on the same line.");
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
System.out.println("Hello World");
This example uses a single-line comment at the end of a line of code:
Example
System.out.println("Hello World"); // This is a comment

9 Gambella University, Department of Computer Science Academic Year – 2015 E.C

You might also like