Chapters in brief
Chapter 1- Breaking the Surface
While loop
A while loop runs everything within its block as long as the conditional test Is true.
If the conditional test is false , the while loop code block won’t run, and execution will move down to the code Immediately after the loop block.
we have to give the condition after the while keyword with brackets
(for ex: x>4 )
==:- equal operator
=:- assignment operator
if, else if ,else condition
In the if else condition firstly it checks the if condition and if it satisfied then it will print that statement if it is false then it will enter else if block and check the condition if it is true print the statement . if both condition are false then it enters the else condition and print the statement.
Chapter 2- A Trip to Objectville
Object
Object is an instance of a class
Employee employee = new Employee () -: this is how we create object in a class
Class
Class is not an object but blueprint of object is called as class .All java codes written inside the class .A class can inherit instance variables and methods from a more abstract superclass.
Student student= new Student();
student.IsEligible To Enroll();
student.Name(“John”);
Chapter 3-Know Your Variables
variables
There are two ways to assign a value to variable
- primitive type
2. reference type
Dog fido = new Dog();
fido.name =“johny” -: reference type variable
- variable must have name and type
- reference variable have null value when it is not referencing to any object
Array
- array is always an object
Declare array variable and Assign value
Books [ ] myBooks = new Books[3];
myBooks[0].title= “The Grapes of Java”;
myBooks[1].title =“The Java Cookbook”;
myBooks[2].title =“Head First Java ”;
Chapter 4 -How Objects Behave
- If a method declares a non-void return type, it must return a value according to the defined return type in the method.
- The number and type of values you pass in must match the order and type of the parameters declared by the method.
- A method can have parameters, which means you can pass one or more values into the method
For ex:
Encapsulation
- make instance variable private
- make getter setter methods public
here we didn’t call and didn’t assign value to instance variables but by default it still has value
- integers - 0
- floating - points 0.0
- boolean - false
- references - null
== used to see If two references are the same (which means they refer to the same object on the heap).
Chapter 5- Extra-Strength Methods
Three things we should consider before creating a class
- prep code — A form of pseudo code
- test code-: A class or methods that will test the real code and validate that it’s doing the right thing
- real code -: Actual java implementation
prep code /pseudo code sample
Step 1. Start
Step 2. Insert the number.
Step 3. If the number is Zero then print “The number is Zero”
Step4: If the number is greater than zero, then print, “The number is Positive”
Step 5. Else print, “The number is Negative”
Step 6. Stop
- Write test code before you implement the methods.
- real code — we are creating actual implementations
casting primitives
- Use Integer .parseInt() to get the int value of a String.
- Integer. parseInt () works only if the String represents a digit (“0”,“1”, “2”)
- x ++ -: x = x+1
- x--: x= x-1
chapter 6 — Using the Java Library
Array example
String [] myList = new String[2];
myList[1] = “ABC”;
mylist[2]= “CDE”;
Array List example
ArrayList<String> cars = new ArrayList<String>();
cars.add(“Volvo”);
cars.add(“BMW”);
cars.add(“Ford”);
cars.add(“Mazda”);
if we have to put something in arraylist using .add() method
if we have to remove then using .remove() method
if arraylist is empty IsEmpty() method we can check it .
‘AND’ ‘OR’ Operators (&&, ||)
And operator (&&)
This one used when the both conditions should be satisfied to get the expected output (returns true if both the conditions is true
if (num1 >= num2 && num1 >= num3)
{
System.out.println(num1+ “ is the largest number.”);
}
Or Operator (| |)
This used when either one of the conditions satisfied to get the expected output (returns true if one of the conditions is true)
if (value == ‘c’ || value == ‘C’)
{
System.out.println(value +“it is a vowel”);
}
Not equals
!= operator
if( model != “samsung”){
System.out.println(“this is iphone”);
}
this one prints when model is not equal to samsung .
==
checks if the reference to string objects are equal or not.equals()
checks if the content of the string object are equal. value are equal
comparing objects(.equals )
if (!brand.equals(“s”)){
// do non brand s things
}
Java Library
java. util .ArrayList
here java.util:- pavkage name
ArrayList:- class name
You use either an Import statement at the top of your source code, or you can type the full name every place you use the class in your code.
Chapter 7 — Better Living in Objectville
Inheritance
- A subclass extends a superclass.
- A subclass Inherits all public Instance variables and methods of the superclass.
- The IS-A relationship works in only one direction.
- If class B extends A, and C extends B, class B IS-A class A, and class C IS-A class B, and class C also IS-A class A.
Polymorphism
There are two main concepts in polymorphism
- Overriding
- Overloading
overriding and overloading
- When two or more methods in the same class have the same name but different parameters, it’s called Overloading.
- When the method signature (name and parameters) are the same in the superclass and the child class, it’s called Overriding.
- overriding- runtime
- overloading- compile time
- overriding- arguments same return type compatible , method can’t be less accessible .
Chapter 8 — Serious Polymorphism
- Abstract class means we can’t create new instance of that class .
- we can make a abstract class using “ abstract “ key word.
- Abstract class can have abstract and non abstract methods .
- Abstract class must be extended
- Abstract methods must be overridden
ex: public abstract void eat( );
- All abstract methods must be implemented in the first concrete subclass in the inheritance
- A Java interface is like a 100% pure abstract class.
- All methods in interface are abstract .
- We can use keyword ‘implements’ followed by the name of the interface to implement an interface
- class can have multiple interfaces
- multiple inheritance not allowed by java that’s why we are using interfaces
Interface vs Abstract
chapter 9 — Life and Death of an Object
- As per my previous jvm article all objects exist in garbage collectable heap area and variable and methods information stored in stack area .
- There are two kinds of variable
- Instance variables- declared inside a class but not inside the method
public class Apple{
int size;
}
2. Local variables-declared inside a method, including method parameters
public void foo(int x){
int i=x+3;
}
- Object reference variables work just like primitive variables-if the reference is declared as a local variable , it goes on the stack.
Constructors
- A constructor must have the same name as the class, and must not have a return type
- When we say new in class type constructor code will be run
- Constructor use to initialize the state of object being constructed
- if we don’t create any constructor the compiler will create default constructor.
- A default constructor always have no arguments
- overloaded constructors means there is more than one constructors exist
- super() keyword used to call the super constructor ( parent class’s constructor)
- super must be called as first statement in the constructor
- local variable stays alive until its stack frame exist
Garbage Collection
- Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
- Before removing an object from the memory garbage collection thread invokes finalize() method of that object and gives an opportunity to perform any sort of cleanup required.
- There are methods like System.gc() and Runtime.gc() which is used to send requests of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
Chapter 10 -Numbers Matters
- A static keyword let the method to run without any instance of that class .
- static methods can’t use any instance variables .
- Astatic method cannot access a non-static method, since non-static methods are usually associated with instance variable state.
- Static variables are initialized when the class is loaded. If you don’t explicitly initialize a static variable.
- If variable have final keyword then its value is constant .Constant variable names should be in all caps.
- A final method means you can’t override the method.
- A final class means we can’t extend the class.
Number Formatting
- we can format numbers using commas
- floating point formatting
format specifier
- decimal :- %d
- floating point:- %.2f
- hexadecimal :- %x
- character:- %c
- complete date and time : — String. format (“%tc”, new Date());
- just time :- String. format (“%tr”, new Date () ) ;
- day of week , month and day :-
Date today= new Date() ;
String. format (“%tA, %tB %td”, today, today, today);
- we can’t make the constructor as static.
Chapter 11-Risky Behavior
Exception handling
- method throws exception when something fails at run time
- An exception is always an object of type Exception.
- The compiler does not pay attention to exceptions that are of type Run time Exception. A Runtime Exception does not have to be declared or wrapped in a try/catch .
- All Exceptions the compiler cares about are called ‘checked exceptions’
Try - Catch — finally
try
{
int i = arr[7];
// this statement will not be executed
// as exception is raised by above statement
System.out.println(“Inside try block”);
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println(“Inside catch block!!”);
}
finally
{
System.out.println(“Inside finally block!!”);
}
Try-The try statement allows you to define a block of code to be tested for errors while it is being executed.
Catch- The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Finally-The finally statement lets you execute code, after try and catch, regardless of the result( if exception handled or not code segment in this block will get executed ).
Throw
- A method throws an exception with the keyword throw, followed by a new exception object:
throw new IOException();
- Methods that might throw a checked exception must announce it with a throws Exception declaration.
chapter 12 — A very Graphic Story
- create a jframe
JFrame frame = new JFrame () ;
- create a widget( text field , button)
JButton button = new JButton (“click ”);
- Add the widget to the frame
frame.getContentPane().add(button);
- set size for frame
frame.setSize(300,300);
- make the frame invisible(hide)
frame.setVisible(false);
- for button click we are using actionlistener .
button.addActionListener(this);
- Implement the listener interface by implementing all of the interface’s event-handling methods.
public void actionPerformed(ActionEvent event) {
button. setText (“you clicked! “) ;
}
- You can draw 2D graphics, gif or jpeg directly on to a widget by overriding paintComponent() method .
Inner class
class MyOuterClass {
private int x;
c1ass MylnnerClass{
void go () {
x = 42;
}
}
}
Chapter 13- Work On Your Swing
Swing
- A widget is technically a Swing Component. Almost every thing you can stick in a GUI extends from javax.swing.JComponent.
- interactive component- jButton , jCheckBox,jTextField ….
- background component -jFrame, jPanel
ex :
JPanel panel1= new JPanel () ;
JPanel panel 2 =new JPanel() ;
panel2.add(new JButton(“button 1”»;
panel2.add(new JButton(“button 2”);
panel2.add(new JButton(“button 3”));
panel1.add(panel2);
- The Border Layout manager lets you add a component to one of five regions. You must specify the region when you add the component, using the following syntax: add (Border Layout. EAST, panel);
- Flow Layout gives components their preferred size in both dimensions.
- Box Layout lets you align components stacked vertically, even If they could fit side-by-side.
- Border Layout is the default layout manager for a frame
- Flow Layout is the default for a panel.
- If you want panel to use something other than flow, you have to call set Layout () on the panel.
Chapter 14 -Saving Objects
- Serialized objects save the values of the instance variables. so that an identical instance (object) can be brought back to life on the heap.
- Objects on the heap have state-the value of the object’s instance variables.
- When an object is serialized, all the objects it refers to from Instance variables are also serialized.
- We can make a class serializable using implements serializable ( serializable is an interface )
ex: public class example implements Serializable{}
- To serialize an object, you need an ObjectOutputStream (from the java.io package)
- During deserialization, the class of all objects in the graph must be available to the JVM
- serialization — is a mechanism of converting the state of an object into a byte stream
- deserialization-is the reverse process where the byte stream is used to recreate the actual Java object in memory.
- To write a serialized object: ObjectOutputstream.writeObject(someObject);
Files
- To write a String: fileWriter. write (“My first String to save”) ;
- FileWriter writer = newFileWriter(“abc.txt”); ← if abc.txt doesn’t exist file writer creates it
- make a file object
File f = new File(mycode.txt);
- make new directory
File dir = new File(“chapters”);
dir.mkdir();
- Delete a file or directory (returns true If successful)
boolean isDeleted =f.delete()
reading from text file
- read a text file, start with a FileReader connection stream.
- Chain the FileReader to a BufferedReader for efficiency.
- To parse a text file. you need to be sure the file is written with some way to recognize the different elements .A common approach is to use some kind of character to separate the individual pieces.
- Use the String split() method 10 split a String up into individual tokens
Chapter 15-Make a Connection
client and server connection establishes with 3 steps
- Client connects to the server by establishing a Socket connection.
- Client sends a message to the server.
- Client gets a message response from the server.
- Client and server applications communicate over a Socket connection.
- A Socket represents a connection between two applications which may (or may not) be running on two different physical machines.
- A client must know the IP address (or domain name) and tcp port number of the server application.
- A tcp port isa 16-bit unsigned number assigned to a specific server application.
- The port numbers from 0 through 1023 are reserved for ‘well-known services’ Including HTTP, FTP, SMTP, etc.
- we have to read data from a Socket using a BufferedReader.
- we have to write data to a Socket using a PrintWriter .
Refer my threads articles to know more about threads .
Synchronizing threads
- we can synchronize threads using the keyword synchronized to modify a method declaration, when you want to prevent two threads from entering that method.
- Every object has a single lock, with a single key for that lock. Most of the time we don’t care about that lock. locks come into play only when an object has synchronized methods.
- When a thread attempts to enter a synchronized method, the thread must get the key for the object (the object whose method the thread is trying to run). If the key is not available (because another thread already has it), the thread goes into a kind of waiting lounge. until the key becomes available.
- Even If an object has more than one synchronized method, there is still only one key. Once any thread has entered a synchronized method on that object, no thread can enter any other synchronized method on the same object.
Chapter 16-Data Structures
collection classes
- ArrayList -class is a resizable array, which can be found in the
java.util
package.(Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.) - TreeSet- Keeps the elements sorted and prevents duplicates.
- HashMap- store and access elements as name/value pairs.
- LinkedList-consists of nodes where each node contains a data field and a reference(link) to the next node in the list.
- 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.
- ArrayList is-a List, because ArrayList implements the List interface.
- virtually all of the code you write that deals with generics will be collection-related code
- The sort( ) method can take only lists of Comparable objects
Generics
- creating instance of generics classes
new ArrayList<Example>( ) →here Example is the reference type .
- Declaring and assigning variables of generic types
List<Example> ExampleList = new ArrayList<Example>( )
- Declaring (and invoking) methods that take generic types
void foo(List<Example> list)
x.foo(ExampleList)
Two ways of using generic methods
- Using a type parameter defined in the class declaration.
When you declare a type parameter for the class
Ex: public class ArrayList<E> extends AbstractList<E>{
public boolean add(E ob){….}
}
2. Using a type parameter that was NOT defined in the class declaration
Ex: public<T extends Animal>void takeThing(ArrayList <T>list)
If the class itself doesn’t use a type parameter, you can still be specify one for a method, by declaring it in a really unusual (but available) space-before the return type.
Sortings in java
1.Sort an array
We can use Array.sort ( ) to sort an array .
2. Sort an Array List
We can use Collections.sort( ) to sort an arraylist
3. Sort an Object with comparator
According to above program we can sort an object using comparator .
4.Sorting a Map with TreeMap
5.Sorting a set using TreeSet
6. Sorting using comparable
Collection API
- Map doesn’t extend from java.util.collection,but they still considered as part of collection framework in java ,so map is still referred to as a collection .
Reference Equality
- Two references that refer to the same object on the heap are equal.
- If we use hashcode( ) method on both references will get same answer .
- we can check this using == operator if two references are really referring to same object .
Object equality
- Two references, two objects on the heap.
- we must also override equal( ) so that if you call non either object. passing in the other object, always returns true .
- if two objects are equal they must have matching hashcodes
- if two objects have same hashcode there is no rules that they are equal , but if they are equal they must have same hashcode value .
- so if we override equals() then we must override hashcode( )
Chapter 17-Release your code
- how to compile a java code
javac myFirstApp.java
- how to run a java code
java myFirstApp
How to make executable jar file in java
- Create a java program(First.java)
- compile the java program(javac First.java )
- Check whether the class file for First.java has been created
- create manifest file (myfile.mf)
- Define the main class coding in manifest file
Main-Class: First
6. Enter the below command to create the jar folder
jar -cvmf myfile.mf myjar.jar First.class
Run jar file
- enter the below command
java -jar myjar.jar
2. if it shows manifest attribute not found error then try below command
java -cp yourJarName.jar yourpackage.yourMainClass
I didn’t have package name so mentioned only the class name
Below I include the code and output after the above command executed
Project Structure
- In project structure we can have class files and source files separately by creating 2 new directories
- If we use two different directories then we should compile it using directory structure
Ex : javac -d ……/classes First.java
- after the d we have to give exact path where our project should create class file
- After creating the class file we have to go into the class file directory
Ex: cd My project/Classes
- In same class directory follow the above steps to create the jar folder (create and execute )
Packages
- packages can prevent name conflicts. but only if you choose package name that’s guaranteed to be unique.
ex: com.headfirstbooks.First
com.headfirstbooks → package name
First →class name
Making an executable JAR with packages
- Choose package name
- create java program with package statement included
package com.headfirstjava ;
- Setting up project structure like this
4. compile with -d (directory) flag
5. check whether .class file created in com/headfirstjava folder
6.run the code to check application is working
here run code in classes directory otherwise it won’t work .
output will be shown as earlier (image output) .
7.create manifest.txt file and include below statement in that file
manifest file should be created in classes directory
8. create jar file using below command
jar file name is package
here the jar file creation done . additional commands given below to check jar folder structure
9. list contents of jar
10.Extract contents of jar
this will create real (MANIFEST.MF) file .
11.using the above code we can run the application with package
java -cp yourJarName.jar yourpackage.yourMainClass
Java Web Start
How Java Web Start works
- The client clicks on a Web page link to your JWS application (a .jnlp file).
- The Web server (HTTP) gets the request and sends back a .jnlp file.
- Java Web Start (a small ‘helper app’ on the client) is started up by the browser. The JWS helper app reads the .jnlp file, and asks the server for the MyApp.jar file.
- The Web server ‘serves ‘ up the requested .jar file.
- Java Web Start gets the JAR and starts the application by calling the specified main( ) method (just like an executable JAR).
Steps for making and deploying a Java Web Start app
- Make an executable JAR for your application
- Write a .jnlp file .
- Place your JAR and .jnlp files on your Web server.
- Add a new mime type to your Web server.
application/x-java-jnlp-file
5. Create a Web page with a link to your .jnlp file
<HTML>
<BODY>
<a href = “MyApp2.jnlp”> Launch My Application</a>
</BODY>
</HTML>
Chapter 18-Distributed Computing
- Method calls are always between two objects on the same heap.
Remote Method calls
- we need to create four things
*client
*server
*server helper
*client helper
- At first 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.
- Then 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 communicating.
How the method call happens
- Client object calls Method1( )on the client helper object
- Client helper packages up information about the call (arguments, method name,etc.) and ships it over the network to the service helper.
- Server 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 server object.
- In Java, RMI builds the client and service helper objects for you.
- In RMI, the client helper is a ‘stub’ and the server helper is a ‘skeleton’.
Making the Remote Service
There are five steps we have to follow
Step1 : Make a Remote Interface ( Myremote.java)
Step2 : make a remote implementation (MyremoteImpl.java)
Step3 : Generate the stubs and skeletons using rmic( Generate .class files )
Step4 : Start the RMI registry (rmiregistry) → using command
Step5 : Start the remote service → using command
Step 1 :Make remote Interface
- Extend java.rmi.Remote
public interface MyRemote extends Remote { ….}
2. Declare that all methods throw a RemoteException
import java. rmi .*;
public interface MyRemote extends Remote {
{ public String sayHelloworld( ) throws RemoteException }
}
3.Be sure arguments and return values are primitives or Serializable
public String sayHelloworld( ) throws RemoteException; → String values are primitives
Step 2 : Make a Remote Implementation
- Implement the Remote interface
public class MyRemoteImpl implements MyRemote {…}
2. Extend UnicastRemoteObject.
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote { ….}
3.Write a no-arg constructor that declares a RemoteException
Public MyRemoteImpl ( ) throws RemoteException
4. Register the service with the RMI registry
try {
MyRemote Service = new MyRemoteImpl( );
Naming.rebind(“Remote Hello “ , Service );
}
catch (Exception ex){…..}
Step 3: generate stubs and skeletons
- Run rmic on the remote implementation class (not the remote Interface)
*command : rmic MyRemoteImpl
Step 4 : run rmiregistry
*command : rmiregistry
Step 5: start the service
*command java MyRemoteImpl
- When a client calls a method on a remote object, the client is really calling a method on a proxy of the remote object. The proxy is called a ‘stub’.
- A stub is a client helper object that takes care of the low level networking details (sockets, streams, serialization, etc) by packaging and sending method calls to the server.
- Your remote service must be instantiated, and the object registered with the RMI registry.
- To register a remote service, use the static Naming.rebind(‘Service Name”, service lnstance).
- The RMI registry must be running on the same machine as the remote service, before you try to register a remote object with the RMI registry.
Server code
How does the client get the stub object
- Client does a lookup on the RMI registry
Naming.lookup(“rmi://127.0.0.1/Remote Hello”);
- RMI registry returns the stub object
- Client Invokes a method on the stub, as though the stub IS the real service.
Complete client code
- The client looks up your remote service using the static Naming.lookup{‘rmi:/IMyHostNameJServiceName”);
- Almost everything related to RMI can throw a Remote Exception (checked by the compiler).This Includes registering or looking up a service In the registry, and all remote method calls from the client to the stub.
- The RMI registry must be running on the same machine as the remote service, before you try 10 register a remote object with the RMI registry.
Servlets
- Servlets are Java programs that run on 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.
- To run a servlet, you must have a web server capable of running servlets, such as the Tomcat server from apache.org.
- A typical servlet extends HttpServlet and overrides one or more servlet methods, such as doGet( ) or doPost( ).
- The web server starts the servlet and calls the appropriate method (doGet ( ) , etc.) based on the client’s request.
- The servlet can send back a response by getting a PrintWriter output stream from the response parameter of the doGet( ) method.
- Client fills out a registration form and clicks ‘submit’, The HTTP server (i.e. web server) gets the request, sees that it’s for a servlet, and sends the request to the servlet.
- Servlet (Java code) runs, adds data to the database, composes a web page (with custom info) and sends it back to the client where it displays in the browser.
Step for making and running a servlet
- Find out where your servlets need to be placed.
- Get the servlets.jar and add It to your classpath
- Write a servlet class by extending HttpServlet
public class MyServletA extends HttpServlet { … }
4. Write an HTML page that invokes your servlet
<a href = “servlets/MyServletA”> THis is servlet.</a>
5. Make your servlet and HTML page available to your server
The Universal Service browser
How this works
- Client starts up and does a lookup on the RMI registry for the service called “Service.Server”, and gets back the stub.
- Client calls getServiceListO on the stub. The ServiceServer returns an array of services.
- Client displays the list of services in a GUI.
- User selects from the list, so client calls the getService( ) method on the remote service. The remote service returns a serialized object that is an actual service that will run inside the client browser.
- Client calls the getGuiPanel( ) on the serialized service object it just got from the remote service. The GUI for that service is displayed inside the browser, and the user can interact with it locally. At this point, we don’t need the remote service unless/until the user decides to select another service .
The classes and interfaces
- interface Service.Server Implements Remote
- class ServiceServerImpl Implements serviceServer
- class ServiceBrowser
- Interface Service
- class DiceService implements Service
- class MiniMusicService implements Service
- class DayOfTheWeekService Implements Service