Java Programming language

Janaki Manathunga
13 min readJul 25, 2022

--

  1. Chapter 1

How Works java?

1. Source

Create a source document. Use an established protocol (in this case, the Java language).

2. Compiler

Run your document through a source code compiler. The compiler checks for errors and won’t let you compile until it’s satisfied that everything will run correctly.

3. Output

The compiler creates a new document, coded into Java bytecode. Any device capable of running Java will be able to interpret/translate this file into something it can run. The compiled bytecode is platform[1]independent.

4. Virtual Machine

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 virtual machine reads and runs the bytecode.

How to run the first java program?

1. Create code

2. Save code using the class name with .java file extension (frist.java)

3. Compile javac file name.(javac frist.java)

4. Run program java file name. (java frist.java)

Let’s learn with simple code.

Main method and main class

The main() method can appear in any class that is part of an application, but if the application is complex containing multiple files, it is common to create a separate class just for main(). The main class can have any name, although typically it will just be called “Main”.

Looping

Java has three standard looping constructs: while, do-while, and for.

While

  • Example program

int x = 4;

// assign 4 to x

while (x > 3)

{

// loop code will run because

// x is greater than 3

x = x — 1;

// or we’d loop forever

}

int z = 27;

while (z == 17) {

// loop code will not run because

// z is not equal to 17

}

2. Chapter 2

Class and Object

A class is a blueprint for an object. It tells the virtual machine how to make an object of that particular type. Each object made from that class can have its own values for the instance variables of that class. For example, you might use the Button class to make dozens of different buttons, and each button might have its own color, size, shape, label, and so on.

When you design a class, think about the objects that will be created from that class type.

  • things the object knows 
  • things the object does
  • *Instance variables

Things an object knows about itself are called instance variables. They represent an object’s state (the data) and can have unique values for each object of that type. Think of instance as another way of saying object.

Things an object can do are called methods. When you design a class, you think about the data an object will need to know about itself, and you also design the methods that operate on that data. It’s common for an object to have methods that read or write the values of the instance variables. For example, Alarm objects have an instance variable to hold the alarmTime, and two methods for getting and setting the alarmTime. So objects have instance variables and methods, but those instance variables and methods are designed as part of the class.

3. Chapter 3

primitives and references

Variables come in two flavors: primitive and reference. Variable must have type and name.

Ex: int count (int:type, count:type)

The 3 steps of object declaration, creation and assignment

  1. Declare a reference variable

Dog myDog = new Dog();

Tells the JVM to allocate space for a reference variable, and names that variable myDog. The reference variable is, forever, of type Dog. In other words, a remote control that has buttons to control a Dog, but not a Cat or a Button or a Socket.

2. Create an object

Dog myDog = new Dog();

Tells the JVM to allocate space for a new Dog object on the heap

3. Link the object and the reference

Dog myDog = new Dog(); Assigns the new Dog to the reference variable myDog. In other words, programs the remote control.

4. Chapter 4

methods use instance variables

Every instance of a particular class has the same methods, but the methods can behave differently based on the value of the instance variables. The Song class has two instance variables, title, and artist. The play() method plays a song, but the instance you call play() on will play the song represented by the value of the title instance variable for that instance. So, if you call the play() method on one instance you’ll hear the song “Politik”, while another instance plays “Darkstar”. The method code, however, is the same.

Encapsulation

Encapsulation describes the idea of bundling data and methods that work on that data within one unit, like a class in Java. This concept is also often used to hide the internal representation or state of an object from the outside. This is called information hiding

5. Chapter 5

writing a program

1 User starts

  • The game creates three Dot Coms
  • Game places the three Dot Coms onto a virtual grid

2 Play begins

Repeat the following until there are no more Dot Coms:

  • Prompt user for a guess (“A2”, “C0”, etc.)
  • Check the user guess against all Dot Coms to look for a hit, miss, or kill. Take appropriate action: if a hit, delete cell (A2, D4, etc.). If a kill, delete Dot Com.

3 Finish

  • Give the user a rating based on the number of guesses

As a programmer, you probably have a methodology/ process/approach to writing code. Well, so do we. Our sequence is designed to help you see (and learn) what we’re thinking as we work through coding a class. It isn’t necessarily the way we (or you) write code in the Real World. In the Real World, of course, you’ll follow the approach your personal preferences, project, or employer dictate. We, however, can do pretty much whatever we want. And when we create a Java class as a “learning experience”, we usually do it like this:

* Figure out what the class is supposed to do.

*List the instance variables and methods.

*Write prepcode for the methods. (You’ll see this in just a moment.)

*Write test code for the methods.

*Implement the class.

* Test the methods.

*Debug and reimplement as needed.

*Express gratitude that we don’t have to test our so-called learning experience app on actual live users

for loop

Part One: initialization

Use this part to declare and initialize a variable to use within the loop body. You’ll most often use this variable as a counter. You can actually initialize more than one variable here, but we’ll get to that later in the book.

Part Two: boolean test

This is where the conditional test goes. Whatever’s in there, it must resolve to a boolean value (you know, true or false). You can have a test, like (x >= 4), or you can even invoke a method that returns a boolean.

Part Three: iteration expression

In this part, put one or more things you want to happen with each trip through the loop. Keep in mind that this stuff happens at the end of each loop.

7. Chapter 7

inheritance

When you design with inheritance, you put common code in a class and then tell other more specific classes that the common (more abstract) class is their superclass. When one class inherits from another, the subclass inherits from the superclass. In Java, we say that the subclass extends the superclass. An inheritance relationship means that the subclass inherits the members of the superclass. When we say “members of a class” we mean the instance variables and methods. For example, if PantherMan is a subclass of SuperHero, the PantherMan class automatically inherits the instance variables and methods common to all superheroes including suit, tights, specialPower, useSpecialPowers(), and so on. But the PantherMan subclass can add new methods and instance variables of its own, and it can override the methods it inherits from the superclass SuperHero.

so he doesn’t override any methods. The methods and instance variables in SuperHero are sufficient. PantherMan, though, has specific requirements for his suit and special powers, so useSpecialPower() and putOnSuit() are both overridden in the PantherMan class. Instance variables are not overridden because they don’t need to be. They don’t define any special behavior, so a subclass can give an inherited instance variable any value it chooses. PantherMan can set his inherited tights to purple, while FriedEggMan sets his to white.

polymorphism

In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee.

8. Chapter 8

interfaces and abstract classes

9. Chapter 9

constructors and garbage collection

10. Chapter 10

numbers and statics

11. Chapter 11

exception handling

12. Chapter 12

13. Chapter 13

using swing

Swing in java is part of the Java foundation class which is lightweight and platform-independent. It is used for creating window-based applications. Swing components can use a different look and feel. Swing components use the Model-View-Controller paradigm (MVC) and thus can provide a much more flexible UI. Swing components are lightweight (are less resource-intensive than AWT).

14. Chapter 14

serialization and file I/O

What is a serialization file?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

When an object is serialized, all the objects it refers to from instance variables are also serialized. And all the objects those objects refer to are serialized. And all the objects those objects refer to are serialized… and the best part is, it happens automatically!

15. Chapter 15

networking and threads

Connecting, Sending, and Receiving

The three things we have to learn to get the client working are :

  1. How to establish the initial connection between the client and server

2. How to send messages to the server

3. How to receive messages from the server

There’s a lot of low-level stuff that has to happen for these things to work. But we’re lucky because the Java API networking package (java.net) makes it a piece of cake for programmers. You’ll see a lot more GUI code than networking and I/O code. And that’s not all.

Make a network Socket connection

To connect to another machine, we need a Socket connection. A Socket ( java.net.Socket class) is an object that represents a network connection between two machines. What’s a connection? A relationship between two machines, where two pieces of software know about each other. Most importantly, those two pieces of software know how to communicate with each other. In other words, how to send bits to each other.

Writing a simple server

So what’s it take to write a server application? Just a couple of Sockets. Yes, a couple as in two. A ServerSocket, which waits for client requests (when a client makes a new Socket()) and a plain old Socket socket to use for communication with the client.

  1. Server application makes a ServerSocket, on a specific port

ServerSocket serverSock = new ServerSocket(4242);

This starts the server application listening for client requests coming in for port 4242.

2. Client makes a Socket connection to the server application

Socket sock = new Socket(“190.165.1.103”, 4242);

Client knows the IP address and port number (published or given to him by whomever configures the server app to be on that port)

3. Server makes a new Socket to communicate with this client

Socket sock = serverSock.accept();

The accept() method blocks (just sits there) while it’s waiting for a client Socket connection. When a client finally tries to connect, the method returns a plain old Socket (on a different port) that knows how to communicate with the client (i.e., knows the client’s IP address and port number). The Socket is on a different port than the ServerSocket, so that the ServerSocket can go back to waiting for other clients.

16. Chapter 16

collections and generics

ArrayList is not the only collection

Although ArrayList is the one you’ll use most often, there are others for special occasions. Some of the key collection classes include:

  • TreeSet

Keeps the elements sorted and prevents duplicates.

  • HashMap

Lets you store and access elements as name/value pairs.

  • LinkedList

Makes it easy to create structures like stacks or queues.

  • HashSet

Prevents duplicates in the collection, and given an element, can find that element in the collection quickly.

  • LinkedHashMap

Like a regular HashMap, except it can remember the order in which elements (name/value pairs) were inserted, or it can be configured to remember the order in which elements were last accessed.

17. Chapter 17

package, jars, and deployment

To put your class in a package:

  1. Choose a package name

We’re using com.headfirst java as our example. The class name is PackageExercise, so the fully-qualified name of the class is now: com.headfirst java.PackageExercise.

2. Put a package statement in your class

It must be the first statement in the source code file, above any import statements. There can be only one package statement per source code file, so all classes in a source file must be in the same package. That includes inner classes, of course.

3.Set up a matching directory structure

It’s not enough to say your class is in a package, by merely putting a package statement in the code. Your class isn’t truly in a package until you put the class in a matching directory structure. So, if the fully-qualified class name is com.headfirstjava.PackageExercise, you must put the PackageExercise source code in a directory named headfirstjava, which must be in a directory named com. It is possible to compile without doing that, but trust us — it’s not worth the other problems you’ll have. Keep your source code in a directory structure that matches the package structure, and you’ll avoid a ton of painful headaches down the road.

18. Chapter 18

remote deployment with RMI

  1. Create client and server apps. The server app is the remote service that has an object with the method that the client wants to invoke.

2. Create client and server ‘helpers’. They’ll handle all the low-level networking and I/O details so your client and service can pretend like they’re in the same heap.

  • The ‘helpers’ are the objects that actually do the communication. They make it possible for the client to act as though it’s calling a method on a local object. The client calls a method on the client helper as if the client helper were the actual service. The client helper is a proxy for the Real Thing.
  • Your client object gets to act like it’s making remote method calls. But what it’s really doing is calling methods on a heap-local ‘proxy’ object that handles all the low-level details of Sockets and streams.

How does the method call happen?

  1. Client object calls doBigThing() on the client helper object

2. Client helper packages up information about the call (arguments, method name, etc.) and ships it over the network to the service helper.

3. Service helper unpacks the information from the client helper, finds out which method to call (and on which object) and invokes the real method on the real service object.

Making the Remote Service

Steps:

  1. Make a Remote Interface

The remote interface defines the methods that a client can call remotely. It’s what the client will use as the polymorphic class type for your service. Both the Stub and actual service will implement this!

2. Make a Remote Implementation

This is the class that does the Real Work. It has the real implementation of the remote methods defined in the remote interface. It’s the object that the client wants to call methods on.

3. Generate the stubs and skeletons using rmic

These are the client and server ‘helpers’. You don’t have to create these classes or ever look at the source code that generates them. It’s all handled automatically when you run the rmic tool that ships with your Java development kit.

4. Start the RMI registry (rmiregistry)

The rmiregistry is like the white pages of a phone book. It’s where the user goes to get the proxy (the client stub/helper object).

5. Start the remote service

You have to get the service object up and running. Your service implementation class instantiates an instance of the service and registers it with the RMI registry. Registering it makes the service available to clients

What about Servlets?

Servlets are Java programs that run on (and with) an HTTP web server. When a client uses a web browser to interact with a web page, a request is sent back to the web server. If the request needs the help of a Java servlet, the web server runs (or calls, if the servlet is already running) the servlet code. Servlet code is simply codes that run on the server, to do work as a result of whatever the client requests (for example, saving information to a text file or database on the server). If you’re familiar with CGI scripts written in Perl, you know exactly what we’re talking about. Web developers use CGI scripts or servlets to do everything from sending user-submitted info to a database, to running a website’s discussion board.

--

--