Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

CSC 2321

Computer Programming II
Java Lab

Al-Qalam University Katsina


What is Java?

Developed and created by John Gosling in 1995 in Sun Microsystems, Java is a general-
purpose, object-oriented programming language. It was developed and intended to follow
the WORA concept which means Write Once Run Anywhere i.e. compiled Java code can
run on all platforms that support Java without the need for recompilation.

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java
and its widespread popularity, multiple configurations were built to suit various types of
platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
Characteristics
It is popular among developers because of its following
characteristics:

 Object-Oriented  Interpreted
 Portable  High Performance
 Platform independent  Multithreaded
 Secured  Distributed
 Robust  Dynamic
 Architecture neutral
Java IDEs to Start Building Java Projects
There are plenty of Java IDEs and online editors for you to begin developing Java projects. The
following list covers some of the most popular editors and IDEs.

IDEs: Online Editors:


 MyEclipse  Codiva
 IntelliJ IDEA  JDoodle
 NetBeans  Rextester
 Dr. Java  Online GDB
 Blue J  Browxy
 Jdeveloper  IDE One
JVM | JDK | JRE
The Java Development Kit (JDK) is one of three core technology packages used in Java
programming, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment).
It's important to differentiate between these three technologies and understand how they're
connected:

• The JVM is the runtime that hosts running programs.


• The JRE is the on-disk part of Java that creates the JVM and loads programs into
them.
• The JDK provides the tools necessary to write Java programs that can be executed
and run by the JVM and JRE.
JVM | JDK | JRE cont…

Developers new to Java often confuse the Java Development Kit and the Java Runtime Environment.

The distinction is that the JDK is a package of tools for developing Java-based software, whereas the

JRE is a package of tools for running Java code.

The JRE can be used as a standalone component to simply run Java programs, but it's also part of the

JDK. The JDK requires a JRE because running Java programs is part of developing them.
JVM | JDK | JRE cont…
JVM | JDK | JRE cont…
JVM
The JDK and the Java compiler
In addition to the JRE, which is the environment used to run Java applications, every JDK contains a

Java compiler. The compiler is the software program capable of taking raw .java files—which are

plain text—and rendering them into executable .class files. We'll see the compiler in action soon.

First, I'll show you how to download and set up a JDK in your development environment.
Downloading the JDK for Java SE
To download the Java SE development kit, visit Oracle’s official download page. You'll see the
various JDK packages available

http://www.oracle.com/technetwork/java/javase/downloads/index.html
Two key Java commands: java and javac
The JRE inside your JDK adds the java command to your command line. You can verify this by
dropping into a command shell and typing java -version, which should return the Java version
you've just installed. (In some cases you'll have to restart your system for this change to your
system path to fully take.)

It's good to have java installed, but what about javac? You'll need this JDK component to compile
your Java files.

The javac command lives inside the /jdk directory, and in recent versions of the installer will
automatically be added to the path .... Some IDEs include a Java compiler by default. It is usually
possible to configure them to use a specific installed version if you wish.
Running a java program through CLI
 Open a command prompt window and go to the directory where you saved the java program

(MyFirstJavaProgram.java). Assume it's C:\.

 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your

code, the command prompt will take you to the next line (Assumption: The path variable is set).

 Now, type ' java MyFirstJavaProgram ' to run your program.

 You will be able to see the result printed on the window.

 The file is compiled and you can see MyFirstJavaProgram.class file generated in the same folder
Running & Compiling a java program through CP
While many programming environments allow us to compile and run a program within the environment, we can also compile and
run java programs using Command Prompt.
After successful installation of JDK in our system and set the path, we can able to compile and execute Java programs using the
command prompt.

•Step 1 - Need to create a java program either in Notepad or other IDE.


•Step 2 - Need to save this java file in a folder with "Demo.java" and it can be saved in a
folder.
•Step 3 - Need to compile this java file from the command prompt
using JAVAC command.
•Step 4 - "Demo.java" file is successfully compiled with a generation of ".class" file.
•Step 5 - Need to execute this java file using JAVA command without ".java" extension.
•Step 6 - Able to see "Welcome to Alqalam University Katsina" output in the console.
Java Compilation
During compile time, java compiler (javac) takes the source file .java file and convert it to
bytecode .class file
Key Definitions
When we consider a Java program, it can be defined as a collection of objects that communicate via invoking
each other's methods. Let us now briefly look into what do class, object, methods, and instance variables
mean.
•Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behavior such as wagging their tail, barking, eating. An object is an instance of a class.
•Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its
type supports.
•Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.
•Instance Variables − Each object has its unique set of instance variables. An object's state is created by the
values assigned to these instance variables.
Downloaded the JDK ?

Check wether it is installed :

C:\Users\Your Name>java -version


Example
class Demo{

public static void main(String args[]){

System.out.println("Welcome to Alqalam University Katsina"); }}

Output:
Welcome to Alqalam University Katsina
Example
public class Dog {

String breed;
int age;
String color;

void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Example

String firstName = "John ";

String lastName = "Doe";

String fullName = firstName + lastName;

System.out.println(fullName);
Naming Variables
The general rules for naming variables are:

•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
Type Casting
Widening Casting Narrowing Casting

Widening casting is done automatically when passing a Narrowing casting must be done manually by placing the type
smaller size type to a larger size type: in parentheses in front of the value:

public class Main {


public class Main {
public static void main(String[] args) {
public static void main(String[] args) {
int myInt = 9;
double myDouble = 9.78d;
double myDouble = myInt; // Automatic casting: int to
int myInt = (int) myDouble; // Manual casting: double to int
double
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
}
}
Strings
String in Java is actually an object, which contain methods that can perform certain operations on strings.
For example, the length of a string can be found with the length() method:

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


System.out.println("The length of the txt string is: " + txt.length());

Casing Index
String txt = "Hello World"; String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.toUpperCase()); // Outputs "HELLO
WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world" System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatination String Methods
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
https://www.programiz.com/java-programming/library/string

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Java Math
Math.max(x,y)

Math.min(x,y)

Math.sqrt(x)

Math.abs(x)

Math.random()
Classes & Objects

class Bicycle {
we have created a class named Bicycle. It contains a
// state or field field named gear and a method named braking().
private int gear = 5; Here, Bicycle is a prototype. Now, we can create any
number of bicycles using the prototype. And, all the
// behavior or method
public void braking() { bicycles will share the fields and methods of the
prototype.
System.out.println("Working of Braking"); } }
Classes & Objects

className object = new className(); An object is called an instance of a class. For example, suppose
Bicycle is a class,
// for Bicycle class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be
Bicycle sportsBicycle = new
Bicycle(); considered as objects of the class.

Bicycle touringBicycle = new


Bicycle();
Accessing members of a class
We can use the name of objects along with
class Bicycle {
the . operator to access members of a class
// field of class int gear = 5;

// method of class void braking() { In the above example, we have created a class
...
} named Bicycle. It includes a field named gear and a method
}
named braking().
// create object
Bicycle sportsBicycle = new Bicycle(); we have created an object of Bicycle named sportsBicycle. We
then use the object to access the field and method of the class.
// access field and method
sportsBicycle.gear;  sportsBicycle.gear - access the field gear
sportsBicycle.braking();  sportsBicycle.braking() - access the method braking()
Example: Methods (from class exercise on Lamp)
In that program, we have created a class named Lamp. It contains a variable: isOn and two
methods: turnOn() and turnOff().
Inside the Main class, we have created two objects: led and halogen of the Lamp class. We then used the
objects to call the methods of the class.
 led.turnOn() - It sets the isOn variable to true and prints the output.
 halogen.turnOff() - It sets the isOn variable to false and prints the output.
The variable isOn defined inside the class is also called an instance variable. It is because when we
create an object of the class, it is called an instance of the class. And, each instance will have its own
copy of the variable.
That is, led and halogen objects will have their own copy of the isOn variable.
Example Methods cont…
class Lamp { public static void main(String[] args) {

// stores the value for light // create an object of Lamp


// true if light is on Lamp led = new Lamp();
// false if light is off
boolean isOn; // access method using object
led.turnOn();
// method to turn on the light }
void turnOn() { }
isOn = true;
System.out.println("Light on? " + isOn);

}
Example Methods cont…
class Lamp { // method to turnoff the light
void turnOff() {
isOn = false;
// stores the value for light System.out.println("Light on? " + isOn);
// true if light is on }
// false if light is off }
boolean isOn; class Main {
// method to turn on the light public static void main(String[] args) {
void turnOn() { // create objects led and halogen
isOn = true; Lamp led = new Lamp();
Lamp halogen = new Lamp();
System.out.println("Light on? " + isOn);
// turn on the light by
} // calling method turnOn()
led.turnOn();
// turn off the light by
// calling method turnOff()
halogen.turnOff();
}
}
Class Activity 1.0

1. Write a java program that gets a string of your Surname first, then your Name . Use the

concat() method to merge them together, then print your name in reverse to the conslole.

2. Write and compile a program that has a Class Car, an Object Engine, and a state EngineOn,

EngineOff. Mimic the example of the Class Lamp and create your own program that either

turns on or turns off the car.

3. Learn about Method Overloading and write one program as an example of Method

Overloading

4. Brush up on Java Flow control before our next class

You might also like