Java Exam Notes.pdf

November 12, 2018 | Author: GreatAkbar1 | Category: Java (Programming Language), Data Type, Java Virtual Machine, Subroutine, Integer (Computer Science)
Share Embed Donate


Short Description

Download Java Exam Notes.pdf...

Description

Core Java by www.ExamFear.com Introduction Introduction Introduction to Java world Setting up JAVA in computer Popular Java Editors Platform Independ Independence ence Java Virtual Machine Machine Object Oriented Programming  javadoc JAR Files PATH and CLASSPATH Common errors Comments My First JAVA program Compiling and Running an Application Variables Why variables? Why so many variables Using variables variables in i n JAV J AVA A Identifiers Global Variables AND Local Variables Datatypes Fundamental data types Int Char Float etc Compound data d ata types Struct Array Character sequence Other data types Typredef Enum Union Constants Instance Members Static Members Operators Assignment Arithmetic Increment, decrement Compound assignment Relational &&, ||, ?, ,

    1    e    g    a     P

Visit ExamFear.com ExamFear.com for  for Free Question Papers for almost all Exams.

Sizeof Precedence operator Control If else While Do while For Jump Continue Goto Exit Switch Try catch finally

Java A ccess Modifiers Modifiers Introduction to Java Access Modifiers public access modifie modifierr private access modifie modifierr protected protected access access modifier modifier default access modifier Function Declaring function Calling function Parameters with function Static method Overloaded f unction unction Inline function Recursion Classes & interface interface Constructor and destructor Overloading constructor Default constructor Interface AbstractClass Java package p ackage Import statement Inheritance Single Inheritacne Multi-Level inheritance this and super keywords Object Serialization Introduction to Object Serialization Transient Fields and and Serializat S erialization ion Input and Output Object Streams

Visit ExamFear.com ExamFear.com for  for Free Question Papers for almost all Exams.

    2    e    g    a     P

Sizeof Precedence operator Control If else While Do while For Jump Continue Goto Exit Switch Try catch finally

Java A ccess Modifiers Modifiers Introduction to Java Access Modifiers public access modifie modifierr private access modifie modifierr protected protected access access modifier modifier default access modifier Function Declaring function Calling function Parameters with function Static method Overloaded f unction unction Inline function Recursion Classes & interface interface Constructor and destructor Overloading constructor Default constructor Interface AbstractClass Java package p ackage Import statement Inheritance Single Inheritacne Multi-Level inheritance this and super keywords Object Serialization Introduction to Object Serialization Transient Fields and and Serializat S erialization ion Input and Output Object Streams

Visit ExamFear.com ExamFear.com for  for Free Question Papers for almost all Exams.

    2    e    g    a     P

Java String Comparison Compare String objects to determine Equality Java StringBuffer StringBuffer StringBuffer Class Creation of StringBuf StringBuffe fer's r's StringBuffer Functions Java Exception Handling Exceptions in Java Exception Exception Classes Exception Statement Syntax Rules for try, catch and finally Blocks try, catch and finally Defining new Exceptions throw, throws statement Handling Multiple Exceptions Others Polymorphism Type casting

Introduction to Core Java world Java Java is a robus rob ustt progr pro gramming amming language la nguage developed by Sun S un Microsyste Microsystems ms (Now (Now Oracle) in 1991.Ja va has b ecome a popular platfo platfo rm since then and hence java has provided lots of standard such as J2EE, JS JS R etc. O n 13  Novembe  Novemberr 2006, Sun released released mu much ch of Java as free free a nd open ope n so so urce urce so ftware ftware under the ter term ms of the GNU General General P ublic Lice Licens nsee (GPL) (GP L)..

Some of the the feature feature s of Java ar a re: Object Oriented : Everything is an object in Java world. Platform independent : java is platform independent. Java code complied in one machine can run in any other machine if JRE or JDK is installed in that machine.This is done by JVM (Java virtual Machine ) Simple : Java is designed to be easy to learn. If you understand the basic concept of OOP java would be easy to master. Open Source : Java is an open source product and thus we need not pay for using it. Also since it is open source, lots lots of o f support is available from open ope n so so urce community. community. a nd all a llows ows us to create secur sec ured ed appli app licat catiio n. Secure : Java is secure an makes a n effort effort to e liminate liminate error pron pro ne situati situat io ns b y emphasizing mainly on o n comp comp ile ile time Robust :Java makes error checking and runtime checking. Multi-threaded : Muti threading can easily be implemented in Java. Distributed :Java is designed for the distributed environment of the internet. O bjectss ha ve states states and beha viors. viors. Example: A do g has has states-col states-co lo r, name, breed as well as     3 Object - Object    e    g  behav  behaviors iors -wagging, -wag ging, barking, eating. An object is an instance instance o f a class.    a     P

Visit ExamFear.com ExamFear.com for  for Free Question Papers for almost all Exams.

class can ca n be defined as a tem te mp late/ late/ b lue lue print p rint that describe the behavi be havio o rs/states rs/states that object o f Class  - A class its its type t ype support. support.

Setting Setting up JAVA in comp com pute uterr  Sett  Settii ng up the the path for for wi wi ndo ndows 2000 2000//XP/ XP /Win7 Wi n7:: Assuming Assuming you have installed installed Ja va in c:\P c:\P rogram F iles\ja iles\ja va\jdk directory: directory: Right-click Right-click on o n 'My Com Co mp uter' and se lect 'Properti 'Proper ties'. es'. Click on the the 'Environm ' Environmen entt variables' variables' button under the 'Ad vanced' tab.  Now alter alter the 'Path' vari var iable so that it also cont co ntains ains the path to the Java executab executab le. Example, if the the path pat h is curre curren ntly set to 'C :\WINDOWS\SYSTEM32', then cha nge your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

 Sett  Settii ng up the the path for for wi wi ndo ndows 95/ 95/98/ 98/ME : Assuming Assuming you have installed installed Ja va in c:\P c:\P rogram F iles\ja iles\ja va\jdk directory: directory: Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

 Sett  Settii ng up the the path for for Li nux, UN I X, Sola Solari ri s, F ree reeB SD: Environmen Environmentt variable PATH should be set to point po int to to where where the java bin b inar ariies have bee n insta install lled. ed. Exampl Example, e, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors: To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. market. But B ut for no no w, you can consider one of the following: Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for this this tu t utorial), TextPad. Netbeans : it is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html. it is also a lso a java java IDE developed by b y the eclipse open source communi co mmunity ty a nd can ca n be downloaded Eclipse  : it from http://www.eclipse.org/ from http://www.eclipse.org/

Platform independent : Java Java is platf p latfo o rm independent. Java code complie comp lied d in o ne machine can run in any othe r mac mac hine if JRE o r JDK is installed in that machine. Java was conceived with the concept of WORA: "write once, run anywhere". This is done by JVM (Java virtual Machine )

Visit ExamFear.com ExamFear.com for  for Free Question Papers for almost all Exams.

    4    e    g    a     P

Java virtual Machine: Java Virtual Machine, or JVM as its name suggest is a ―virtual‖ computer that resides in the ―real‖ computer as a software process. JVM gives Java the flexibility of platform independence. JVM is java interpreter as it converts the byte code into machine code for the computer one wants to run. The programs written in Java or the source code translated by Java compiler into byte code a nd after that the JVM converts the byte code into machine code for the computer one wants to run. JVM is a part of Java Run Time Environment that is required by every operating system requires a d ifferent JRE . The architecture of the JVM is given below . This architecture tell us how the JVM works . Firstly we write the simple java program(source code) the java co mpiler converts the source code into t he bytecode , a fter that JVM reads this bytecode and converts this into t he machine code.

Object Oriented Programming : Object oriented programming or OOP is a way of writing programs using objects. An object is a data structure     5 in memor y that has attributes and methods. The attributes o f an object are the same as variables and the methods    e    g    a of an object are the same as functions or procedures. . Object-oriented programming is a method of     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

 programming based o n a hierarchy of c lasses, and well-de fined and cooperating objects. In java we create objects and c lasses. Also JAVA follows concepts of OOPS such as polymorphism, Inheritance, e ncapsulation.

Javadoc Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code . The Javadoc pro vides information about various methods such as 1. Purpose o f function 2. Parameters of function 3. Return type of function

JAR Files: JAR file is the compressed file format. You can store many files in a JAR file. JAR stands for the Java Archive. This file format is used to distribute a set of java classes. This file helps you to reduce the file size and collect many file in one by compressing files. Downloading the files are become completed in very short duration of time because of reducing the file size. You can make the jar file executable by collecting many class file of your  java application in it. The jar file can e xecute from the javaw (Java Web Start). The JAR file format is based on the popular ZIP file format. Usually these file format is not only used for archiving and distribution the files, these are also used for implementing various libraries, components and  plug-ins in java app lications. Compiler and JVMs (Java Virtual Machine) can understand and implement these formats for java application.

PATH and CLASSPATH Path is for OS : Executable Class path is for JVM : Class, jar files The classpath tells Ja va where to look on the filesystem for files defining these classes. The virtual machine searches for and loads classes in this order: 1.  bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional). 2. extension classes: packa ges that are in the extension directory of the JRE or  JDK, jre/lib/ext/ 3. user-defined packages a nd libraries

Commenting in Java: /* Multiple line comment */ :This is used for multiple line comment

Visit ExamFear.com for Free Question Papers for almost all Exams.

    6    e    g    a     P

// Single line comment: this is used for single line comment.

Common Errors with Java: About Java programs, it is very important to keep in mind the following points. Case Sensitivity  - Java is case sensitive which means identifier Hello and hello would have different meaning in Java. Class Names  - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class each inner words first letter should be in Upper Case.Example class MyFirstJavaClass Method Names  - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example  public void myMethodName() Program File Name  - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[])  - java program processing starts from the main() method which is a mandatory part of every java program..

My First Java Program: Let us look at a simple code that would print the words Hello World.  public class ExamFear{ /* This is the first Java program by Examfear.com This program will print ‗Hello ExamFear Users'

*/

 public static void main(String []args){ System.out.println("Hello ExamFear Users"); // pr ints Hello World } }

How to run a java program: 1. 2. 3. 4.

Open notepad and add the code as above. Save the file as: ExamFear.ja va. Please note that file name should be same as class name. Open a command prompt window and go to the directory where you saved the class. Assume its C :\. Type ' javac ExamFear.java ' and press enter to co mpile your code. If there are no errors in your code the     7    e    g command prompt will take you to the next line.( Assumption : The path variable is set).    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

5.  Now type ' java ExamFear ' to run your program. 6. You will be able to see ' Hello ExamFear USers ' printed on the window. C : > javac ExamFear.java C : > java ExamFear Hello ExamFear Users Lets understand what we have done: We have created a java file named ExamFear.java. In this file we have a class called ExamFear. This class has a main method. When we execute the program, main method‖ static void main (String []args)‖ is called. Here we have printed ―Hello ExamFear Users‖. Also note that we have used both single line and multi line comment.

Compiling and running Java Program: When JDK is installed on your machine, it provides two commands for you to compile and run Java programs. "javac class_name.java"  - Compiles a Java program stored a file named with the program class name. We compile Java file with extension *.java to create bytes code with extension *.class "java -cp . class_name"  - Runs a compiled Java program. "-cp . " specifies the current directory as the class path.

Why va riables? Variables are used to store values that can be used by program. Also it is used to pass value from user to computer. A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and var iables of type float store numbers with decima l places. Each o f these variable types char, int, and float - is each a keyword that you use when you declare a variable.

Why so many variable types? We use so many variable types to make your code efficient and readable. Using the right variable type can be important for making your code readable and for efficiency--some variables require more memory than others. E.g.: Char should not be used to store number. Float should be used only if you want to store dec imal.

Using Variables in Java To declare a variable you use the syntax "type ;". Here are some variable declaration examples : int x; char student_name; float cost_price; It is permissible to declare multiple variables of the same type on the same line; each one should be separa ted  by a comma. int a, b, c, d; If you were watching closely, you might have seen that declaration of a variable is always followed by a

    8    e    g    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

semicolon (note that this is the same procedure used when you call a function). Ok, so you now know how to tell the comp iler about variables, but what about using them? One application of variable is an addition program. Suppose you want to add two numbers, in that case you have to put number1 and number2 in memory and then add it. In such case you will need variable. int a = 6; int b = 3; int res ult = a + b;

Java Identifiers: All java components require names. Names used for classes, variables and methods are called identifiers. Java ide ntifiers should follow the rules below: All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: cost, $price, _ value, __1_va lue Examples of illegal identifiers : 567pqr, - india

Java Modifiers: Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers. Access Modifiers  : defualt, public , protected, private. These are keywords that help set the visibility and accessibility of a class, its member variables, and methods  Non-a ccess

Modif iers :

1. 2. 3. 4. 5.

There are five non access  Modif iers in Java.

static final transient abstract synchronized

Java Variables: We would see following type of variables in Java: Local Variables Class Variables (Static Variables)

Visit ExamFear.com for Free Question Papers for almost all Exams.

    9    e    g    a     P

Instance Variables (No n static variables)

Fundamental data types When we wish to store data in a Java program, such as a whole number or a character, we have to tell the compiler which type of data we want to store. The data type will have characteristics such as the range of values that can be stored a nd the operatio ns that can be per formed on variables of that type.

Fundamental types Java pro vides the following fundamental built-in data types: Boolean, character, integer and floating-po int.

Boolean Type The Boolean type can have the value true or false. For example: bool flag = false; If a Boolean value is converted to an integer value true becomes 1 and false beco mes 0 and vice versa.

Character Type The character type is used to store characters - typically ASCII c haracters but not a lways. For example: char alphabet = 'a'; char number = '52'; We can declare signed and unsigned characters, where signed characters can have positive and negative va lues, and unsigned characters can only contain positive values. A char is guaranteed to be at least 8 bits in size.

Integer Types The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer values as follows: signed int marks = -187; unsigned int vote = 12; int population = 998100;

Like characters, signed integers can hold positive or negative values, a nd unsigned integers can hold only  positive values. However, plain integer can always hold positive or negative values, they're always signed. Integer values come in three sizes, plain int, short int and long int. The range of values for these types will be defined by your compiler. A short integer is guaranteed to be at least 16 bits and a long integer at least 32 bits.     0     1    e

Floating-Point Types

   g    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float (single precision), double (double-precision) and long double (extended-precision). Some examples: float celsius = 37.623; double fahrenheit = 98.415; long double accountBa lance = 1897.23 ; The range of values that can be stored in each of these is defined by your compiler.

Name

Description

Size*

Range*

char

Character or small integer.

1byte

signed: -128 to 127 unsigned: 0 to 255

short int (short)

Short Integer.

2bytes

signed: -32768 to 32767 unsigned: 0 to 65535

4bytes

signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

int

Integer.

long int (long)

Long integer.

4bytes

signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

 bool

Boolean value. It can take one of two values: true or false.

1byte

true or false

float

Floating point number.

4bytes

+/- 3.4e +/- 38 (~7 digits)

double

Double precision floating point number.

8bytes

+/- 1.7e +/- 308 (~15 digits)

long double

Long double precision floating point number.

8bytes

+/- 1.7e +/- 308 (~15 digits)

wchar_t

Wide character.

2 or 4  bytes

1 wide character

* The values of the columns Size and Range depend on the system the program is compiled for.     1     1    e

Composite data type :

   g    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

A composite data type is any data type which can be constructed in a program using primitive data types and other composite types. Examples of composite data types are enum, struct, class, string etc

Structs or Structures There are many instances in programming where we need more than one variable in order to represent something. For example, to represent student, you might want to store name, age, address, phone number etc, or any other number of characteristics about student. You could do so like this: char strName[20]; int age;Char address[50]; int phoneNumber; However, you now have 4 independent variables that are not grouped in any way. If you wanted to pass information about yourself to a function, you‘d have to pass each variable individually. Furthermore, if you wanted to store information about more people, you‘d have to declare 4 more variables for each additional student. Fortunately, Java allows us to create our own user-defined aggregate data types. An aggregate data type is a data type that groups multiple individual variables together. One of the simplest aggregate data type is the struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit. Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can  begin using it. To do this, we declare our struct using the struct keyword. Here is a n example of a struct declaration: struct Student { char strName[20]; int age; char address; int phoneNumber; } This tells the compiler that we are defining a struct named Student. The Employee struct co ntains 4 variables inside of it: two ints and two char. These variables are called members (or fields). Keep in mind that the above is just a declaration —   even though we are telling the compiler that the struct will have variables, no memory is allocated at this time. In order to use the Employee struct, we simply declare a variable of type Employee: Student s1, s2; Using this command we create objects of student , S1 and S1 and hence memory is allocated.

Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

    2     1    e    g    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

That means that, for example, we can store 10 values of type int in an array without having to declare 10 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier. unt arrayStudentId[10]; // This can store 10 student ids.. arrayStudentId[0]= 123; arrayStudentId[1]= 124; etc.. int employeeId[5] = { 1,2,3,4,5}; // this is array of length 5, and it is similar to int employeeId[0] = 1; int employeeId[1] = 2; int employeeId[2] = 3; int employeeId[3] = 4; int employeeId[4] = 5;

Multi Dimensional array: int ExamFear[3][4]; It is represented internally as: 0

1

2

3

0 1 2

How to access the elements in the Multidimensional Array

0

1

2

3

0 1 2

Highlighted ce ll represent ExamFear[1][2]

Java Keywords:

    3     1    e    g    a     P

Visit ExamFear.com for Free Question Papers for almost all Exams.

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract

assert

boolean

break

 byte

case

catch

char

class

const

continue default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

 private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while

extends

Enumerated types An enumerated type is a data type where every possible value is defined as a s ymbolic constant (called an enumerator). Enumerated types are declared via the enum keyword. Let‘s look at an example: enum Color_list

{COLOR_BLACK, COLOR_RED, COLOR_BLUE};

Visit ExamFear.com for Free Question Papers for almost all Exams.

    4     1    e    g    a     P

Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is dec lared memory is allocated for that variable at that time. Enum variables are the same size as an int variable. This is because each enumerator is automatical ly assigned an integer value based on it‘s position in the enumeration list. By default, the first enumerator is assigned the integer va lue 0, and eac h subsequent enumerator has a value one greater than the previous enumerator:

Operators Operator is used to operate variables and constants. Lets discuss various kinds of operators in Java.

Assignment (=) This operator assigns a value to a variable. E.g : int i = 10; This statement assigns the integer value 10 to the variable i. The part at the left of the assignment operator (=) is variable whereas the one on right is constant. The assignment operation always takes place from right to left only.

Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the JAVA language are: + addition - subtraction * multiplication / division % modulo Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. Modulo is the operation that gives the remainder of a division of two values. For example, if we write: int b = 10 % 4; the variable a will contain the value 2, since 2 is the remainder from dividing 10 by 4.

Compound assignment (+=, -=, *=, /=, %=, >>=,
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF