0% found this document useful (0 votes)
236 views29 pages

Java Study Material

The document provides an introduction to Java programming including: (1) Data types like integer, floating point, and variables that can be instance, static, local, or parameters. (2) Operators and control structures like if/else, for loops, and switch statements. (3) Arrays for storing multiple values of the same type. (3) Classes define objects with properties and methods, and objects are instantiated from classes using the new keyword.

Uploaded by

Anuj Nagpal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
236 views29 pages

Java Study Material

The document provides an introduction to Java programming including: (1) Data types like integer, floating point, and variables that can be instance, static, local, or parameters. (2) Operators and control structures like if/else, for loops, and switch statements. (3) Arrays for storing multiple values of the same type. (3) Classes define objects with properties and methods, and objects are instantiated from classes using the new keyword.

Uploaded by

Anuj Nagpal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 29

Lecture 1

Topic- Introduction to Java, Data types, variables.

Introduction to java-> Java is Object oreiented programming language. It include four concept (i) (ii) (iii) (iv) class, (ii) object (iii) properties (iv) method.

Features of java Platform Independent The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. Object Oriented To be an Object Oriented language, any language must follow at least the four characteristics.

-> Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed. ->Encapsulation: : It is the mechanism of combining the information and providing the abstraction. -> Polymorphism: : As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods. -> Dynamic binding : Sometimes we don't have the knowledge of objects about their specific types while writing our code.

It is the way of providing the maximum functionality to a program about the specific type at runtime. Robust Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

Portable The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language. Dynamic While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet. Secure Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading Data type Fixed Point Data Types Fixed Point Data Types 8-bits, -127 to 127

(i) Byte - byte b = 16; (ii) Short - short s = -1543; 16-bits, -32767 to 32767 (iii) Int - int i = 100340; 32-bits, -2 billion to 2 billion (iv) Long - long l = -123456789123; 64-bits, absurdly large numbers Floating Point Data Types (i) Float

float f = 3.14159265; - i (ii) Double do e d = 5.6 4 *M h.pow , 5 ; 64-bits (max value ~10^308) e

Variable-> The Java programming language defines the following


kinds of variables:

Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind The Java programming language defines the following kinds of variables: of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There

is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields

Lecture 2
Topic- operators, Arrays, Control Statements, Classes & Methods Opeartors. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Operators Operator Precedence: Precedence

Postfix Unary Multiplicativ e additive Shift relational equality bitwise AND

expr++ expr-++expr --expr +expr -expr ~ ! */% +<< >> >>> < > <= >= instanceof == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>=

bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary assignment

Prefix/Postfix Arithmetic
(i)The operator negates a value: int y = -z; (ii) The + operator promotes: byte x = 32; int y = +x; (iii) The ++ and -- operators increment anddecrement by 1 int z = x++; int y = ++x;

ArraysAn array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration , numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. Types of array(i)1 D arrays (ii)2D array (iii) 3D Array Declaring a Variable to Refer to an Array The above program declares anArray with the following line of code: int[] anArray;

Control Statement-> The If then and IF then else

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if

a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows: If-then Statement-> void applyBrakes(){ if (isMoving){ currentSpeed--; } } if then else statementthe applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped. void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } } Switch Statementclass SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break

} } }

Iteration
i e , e he for con r c : System.out.println(i); { (ii) To repeat until a condition is met: while(i < 10) { System.out.println(i);

(i) To repeat a task a specified number of for(int i = 0; i < 10; i++) {

Class--> all the objects are categorized in a special group.


That group is termed as a class. All the objects are direct interacted with its class that mean almost all the properties of the object should be matched with it's own class. Object is the feature of a class which is used for the working on the particular properties of the class or its group. We can understand about the class and object like this : we are all the body are different - different objects of the human being class. That means all the properties of a proper person relates to the human being. Class has many other features like creation and implementation of the object, Inheritance etc. class square{ int sqarea(int side){ int area = side * side; return(area); } int sqpari(int side){ int pari = 4 * side; return(pari); } }

Creating an Object: Object is a instance of class.


new key word is used to create new objects.

There are three steps when creating an object from a class: Declaration . A variable declaration with a variable name with an object type.

Instantiation . The 'new' key word is used to create the object. Initialization . The 'new' keyword is followed by a call o a constructor. This call initializes the new object. Example-> class Puppy{ public Puppy(String name){ System.out.println("Passed Name is :" +

name ); } public static void main(String []args){

Puppy myPuppy = new Puppy( "tommy" ); }

Acessing Instance Variables and Methods:


Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows: /* First create an object */ ObjectReference = new Constructor(); /* Now call a variable as follows */ ObjectReference.variableName;

/* Now you can call a class method as follows */ ObjectReference.MethodName();

Creating a Method:
In general, a method has the following syntax: modifier returnValueType methodName(list of parameters) { // Method body; }

A method definition consists of a method header and a method body. Here are all the parts of a method: Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method. Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void. Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature. Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method Body: The method body contains a collection of statements that define what the method does.

Example=Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two: /** Return the max between two numbers */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Lecture-3
Topics: Inheritance, Exception Handling, Multithreading Inheritence-> Inheritance can be defined as the process where one object acquires the properties of another. With the use of

inheritance the information is made manageable in a hierarchical order.When we talk about inheritance the most commonly used key words would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object. IS-A Relationship: IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

Example-> public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ } public class Dog extends Mammal{ }

Now ased on the above example, In Object Oriented terms following are true:

Animal is the superclass of Mammal class. Animal is the superclass of Reptile class Mammal and Reptile are sub classes of Animal class. Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say: Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal

Hence : Dog IS-A Animal as well

Types of inheritance->
Single level Inheritance Multilevel Inheritance Multiple Inheritance Hybrid Inheritance Hierarchical Inheritance

Exception Handling->

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseenby the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the . As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.

Errors are typically ignored in your code you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation

What Happens When an Exception Occurs? When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system Creating an exception object and handing it to her n i e y e i c ed hrowing n e cep ion Exception object contains information about the error, including its type and the state of the program When the error occeured..

Benefits of Java Exception Handling Framework


Separating Error-H nd ing code fro reg code Propagating errors up the call stack Grouping and differentiating error type. rB ine ogic

Catching Exception With Try and Catch Bolck.

Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> { ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs>

Catching exception with finally Keyword.

Syntax:
try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> . .. { } finally { <code to be executed before the try block ends>

Multithreading->

Approach: (i)Multiple processing units (multiprocessor) (ii) Computer works on several tasks in parallel (iii) Performance can be improved

Perform Multiple Tasks Using Process:

Process:

Definition executable program loaded in memory Has own address space Variables & data structures (in memory) Each process may execute a different program Communicate via operating system, files, network

Thread

Definition sequentially executed stream of instructions Shares address space with other threads Has own execution context Program counter, call stack (local variables) Communicate via shared access to data Multiple threads in process execute same program A o known igh weigh process

Programming with Threads


Concurrent programming: (i)Writing programs divided into independent tasks Tasks may be executed in parallel on multiprocessors (ii)Multithreading Executing program with multiple threads in parallel Special form of multiprocessing

Creating Threads in Java


You have to specify the work you want the thread to do Define a class that implements the Runnaable interface

public interface Runnable { public void run(); { Put the work in the run method

Create an instance of the worker class and create a thread to run it or hand the worker instance to an example.

Thread Class
public class Thread { public Thread(Runnable R); // Thread R.run()

public Thread(Run able R, String name); public void start(); }

Threads Thread States


Java thread can be in one of these states New thread allocated & waiting for start() Run able thread can execute Blocked thread waiting for event (I/O) Terminated thread finished

Java Thread Example


public class ThreadExample implements Run able { public void run() { for (int i = 0; i < 3; i++)

System.out.println(i); { public static void main(String[] args) { new Thread(new ThreadExample()).start(); new Thread( new ThreadExample()).start() System.out.println("Done") } }

Lecturer-4
Topics- Collections, I/O streams, AVVT & Apolet Programming

Collections-> A collection is a group of data manipulate as a single object. o Corresponds to a bag.Insulate client programs from the implementation. (i) array, linked list, hash table, balanced binary tree Like C++'s Standard Template Library (STL) Can grow as necessary. Contain only Objects (reference types). Heterogeneous. Can be made thread safe (concurrent access) Can be made not-modifiable.

Collection Interfaces
Collections are primarily defined through a set of interfaces

Supported by a set of classes that implement the interfaces Interfaces are used of flexibility reasons (i) Programs that uses an interface is not tightened to a specific implementation of a collection. (ii) It is easy to change or replace the underlying collection class with another (more efficient) class that implements the same interface. The Collection Interface Example-> public interface Collection {

int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); Object[] toArray(); Object[] toArray(Object a[]); }

Collection Advantages and Disadvantages


Advantages: Can hold different types of objects. Resizable

Disadvantages: Must cast to correct type Cannot do compile-time type of checking.

I/O Stream->

(i)An I/O Stream represents an input source or anoutput destination. (ii)A stream can represent many different kinds ofsources and destinations disk files, devices, other programs, a network. (iii)Streams support many different kinds of data simple bytes, primitive data types, localized characters, and objects (iv) Some streams simply pass on data; others. (v)manipulate and transform the data in useful ways. Input Stream-> A program uses an input stream to read data from a source, one item at a time Output Stream.-> A program uses an output stream to write data to a destination, one item at time.

Types of streams-> General Stream Types (i)Character and Byte Streams Character vs. Byte

(ii)Input and Output Streams Based on source or destination

(iii)Node and Filter Streams Whether the data on a stream is manipulated or transformed or not

Byte Stream Programs use byte streams to perform input and output of 8-bit bytes All byte stream classes are descended from InputStream and OutputStream There are 2 byte stream classes FileInputStream and FileOutputStream.

AWT (abstruct window Toolkit) ->A class library is provided by the Java programming language which is known asAbstract Window Toolkit

(AWT).

AWT Components:

The class component is extended by all the AWT components. More of the codes can be put to this class to design lot of AWT components. Following are the AWT components: i. ii. iii. iv. v. Canvas Checkbox Label Scrollbar TextField

Events-> Events are the integral part of the java platform. You can see the concepts related to the event handling through the example and use methods through which you can implement the event driven application. AWTEvent Listener interface as Events subclass the AWTEvent class. However, PaintEvent and InputEvent don't have the Listener interface because only thepaint() method can be overriden with PaintEvent etc. Low-level Events A low-level input or window operation is represented by the Low-level events. Types of Low-level events are mouse movement, window opening, a key press etc. For example, three events are generated by typing the letter 'A' on the Keyboard one for releasing, one for pressing, and one for typing.

Applets-> An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment. Swing provides a special subclass of the Applet class calledjavax.swing.JApplet. The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs).

How do applets works? Step 1 o Down o d nd in S n J Sof w re Development Kit (SDK) to allow compilation and interpretation of compiled class files

Write the Java source code for the applet in any text editor. Compile the source code to obtain the necessary bytecodes known .c for in erpre ing

How do applets work? Step 2

Compile the source code to obtain the necessary bytecodes known as .class for interpreting

How do applets work? Step 3


Server Web page HTML controls image applet client client http server

How do applets work? Step 4

JVM http server

client

Adventure.class

31 October 2002

Nelson Young

Applet Example

Applet Example:
Applet0.html

Applet Example: (Contd)


Applet0.java

Applet Attributes

Applet's Attributes
Attribute Code Width height Codebase alt name
Align(top,left,right,bottom)

Explanation Name of class file Width of applet Height of applet Applets Directory Alternate text if applet not available Name of the applet

Example Code=applet0.class Width=300 Height=60 Codebase=/applets Alt=menu applet Name=appletExam

Justify the applet with text Align=right

Dissadvantages of Applets:

Applets cant run any local executable programs Applets cant with any host other than the originating server Applets cant read/write to local computers file system

Advantages of Applets

Automatically integrated with HTML; hence, resolved virtually all installation issues. Can be accessed from various platforms and various java-enabled web browsers. Can provide dynamic, graphics capabilities and visualizations Implemented in Java, an easy-to-learn OO programming language

You might also like