Learn Java From Basics - Bikram
Learn Java From Basics - Bikram
• If Java was successfully installed, you will see something like this (depending on version):
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:
@BikramMaharjan
public class FirstJavaProgram {
This is the first line of our java program. Every java
application must have at least one class definition
that consists of class keyword followed by class
name. When I say keyword, it means that it should
not be changed, we should use it as it is. However
the class name can be anything.
@BikramMaharjan
public static void main(String[] args)
{
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside the
class.
static: We do not need to create object for static methods to run. They can run itself.
main: It is the method name. This is the entry point method from which the JVM can run your program.
(String[] args): Used for command line arguments that are passed as strings. We will cover that in a
separate post.
@BikramMaharjan
System.out.println("This is my first program in java");
Note: The curly braces {} marks the beginning and the end
of a block of code.
Any text between // and the end of the line is ignored by Java (will not be executed).
Activity Time
@BikramMaharjan
Variables in Java
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String stores text, such as "Hello". String values are surrounded by double quotes
Int stores integers (whole numbers), without decimals, such as 123 or -123
Float stores floating point numbers, with decimals, such as 19.99 or -19.99
Char stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
Output :
John
@BikramMaharjan
Program Example of Data types (int)
To create a variable that should store a number, look at the following example:
You can also declare a variable without assigning the value, and assign the value later:
public class Main {
public static void main(String[] args) {
int myNum;
myNum = 15;
System.out.println(myNum);
}
}
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
@BikramMaharjan
Final Variables
However, you can add the final keyword if you don't want others (or yourself) to overwrite
existing values (this will declare the variable as "final" or "constant", which means
unchangeable and read-only):public
class Main {
public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
}
Output :
Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;
^
1 error
@BikramMaharjan
Other Data Types
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
@BikramMaharjan
Variables naming convention in java
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names can also begin with $ and _ (but we will not use it in this
tutorial)
• Names are case sensitive ("myVar" and "myvar" are different
variables)
• Reserved words (like Java keywords, such as int or boolean)
cannot be used as names
@BikramMaharjan
Display Variables
The println() method is often used to display variables.
Output :
11
@BikramMaharjan
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated list:
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable
code:
@BikramMaharjan
Example
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour = 60;
System.out.println(minutesPerHour);
System.out.println(m);
}
}
Output :
60
60
@BikramMaharjan
Activity
Create a variable named carName and assign the value Volvo to it.
=
@BikramMaharjan
Java Data Types
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types have all the same size.
• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
@BikramMaharjan
Activity
Add the correct data type for the following variables:
myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A’;
myBool = false;
myText = "Hello World";
@BikramMaharjan
Java Type Casting
Type casting is when you assign a value of one primitive data type to another type.
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
@BikramMaharjan
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
In the example below, we use the + operator to add together two values:
Example
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
}
@BikramMaharjan
Java Operators
Although the + operator is often used to add together two values, like in the example above, it can also
be used to add together a variable and a value, or a variable and another variable:
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
@BikramMaharjan
Java Operators
• Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
•
@BikramMaharjan
Arithmetic Operators
Operator Name Description Example
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
== Equal to x == y
!= Not equal x != y
! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
@BikramMaharjan
Example(Logical &&)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10); // returns true because 5
is greater than 3 AND 5 is less than 10
}
}
@BikramMaharjan
Example(Logical ||)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 || x < 4); // returns true because one of the conditions are true
(5 is greater than 3, but 5 is not less than 4)
}
}
@BikramMaharjan
Example(Logical !)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because ! (not) is used to reverse
the result
}
}
@BikramMaharjan
Activity
System.out.println(10 5);
@BikramMaharjan
Java Strings
Strings are used for storing text.
greeting = ;
@BikramMaharjan
Java Math (Math.max(x,y))
The Math.max(x,y) method can be used to find the highest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10));
}
}
@BikramMaharjan
Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.min(5, 10));
}
}
@BikramMaharjan
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:
Loops are handy because they save time, reduce errors, and they make code more
readable.
1. While loop
2. Do while loop
3. For loop
@BikramMaharjan
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
@BikramMaharjan
Java For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
@BikramMaharjan
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
do {
// code block to be executed
}
while (condition);
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
@BikramMaharjan
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Syntax:
for (type variable : arrayname) {
...
}
@BikramMaharjan
For each loop example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
@BikramMaharjan
Java Methods
A method is a block of code which only runs when it is called.
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.
@BikramMaharjan
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:
In the following example, myMethod() is used to print a text (the action), when it is
called:
@BikramMaharjan
Example (calling a method)
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
;
}
@BikramMaharjan
Java Method Parameters
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the
method.
Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
@BikramMaharjan
Java Method Parameters
The following example has a method that takes a String called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full
name:
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Verma");
}
Procedural programming is about writing procedures or methods that perform operations on the data,
while object-oriented programming is about creating objects that contain both data and methods.
To create an object of Main, specify the class name, followed by the object name, and
use the keyword new:
@BikramMaharjan
Object Example
public class Main {
int x = 5;
Remember that the name of the java file should match the class name. In this example, we
have created two files in the same directory/folder:
• Main.java
• Second.java
@BikramMaharjan
Using Multiple Classes
Main.java
int x = 5;
Main.java Second.java
Second.java
}
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
@BikramMaharjan
Continue…
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java
= new ();
@BikramMaharjan
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:
Note that the constructor name must match the class name, and it cannot have a return type (like
void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.
@BikramMaharjan
Constructure Example
// Create a Main class
public class Main {
int x;
The public keyword is an access modifier, meaning that it is used to set the access level for classes,
attributes, methods and constructors.
Modifier Description
final The class cannot be inherited by other classes
abstract The class cannot be used to create objects
For attributes and methods, you can use the one of the
following:
@BikramMaharjan
Non-Access Modifiers
For attributes and methods, you can use the one of the following:
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The
method does not have a body, for example abstract void run();. The body is
provided by the subclass (inherited from).
transient Attributes and methods are skipped when serializing the object containing
them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read from
the "main memory"
@BikramMaharjan
Final Example
If you don't want the ability to override existing attribute values, declare attributes as final:
public class Main {
final int x = 10;
final double PI = 3.14;
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:
@BikramMaharjan
Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
@BikramMaharjan
Example Explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable. The
this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside
this class:
@BikramMaharjan
Java Packages & API
A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are
divided into two categories:
Example:-
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of 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 a complete line:
@BikramMaharjan
Scanner Example
import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the java.util package:
@BikramMaharjan
Example of import the java package
import java.util.*; // import the java.util package
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyClass.java, and compile it: