Sei sulla pagina 1di 20

CORE JAVA

Difference between c and java?



The main differences between Java and C are speed, portability, and object-
orientation.
Java was created for the purpose of making a language that could be implemented
on many different types of computers (cell phone, mac, PC, linux, etc.) C on the
other hand can only be run on a computer of the same type as the one that
compiled the program.

One of the costs of this portability in Java is speed. On numerous benchmarks Java
still lags behind C in terms of speed, but that gap is narrowing.

Java is also object-oriented, whereas C is not. Java allows a user to create classes
that contain data and methods. C is not capable of doing that.

Java is an object-oriented language, without pointers, garbage collected.
C is a procedural language, with pointers, not garbage collected.

Basically, the standard distribution of Java compiles to C and then to machine code.


Difference between Core JAVA and Advanced Java
Core Java has to do with the basic package of Java objects that are typically used
for general desktop applications. These objects come in the 'Standard Edition' of
Java.
Advanced Java could actually refer to any advanced topic having to do with Java
programming-- and there are many.
The other packages that you will typically see being referred to in opposition to
Core Java are Enterprise Java and Micro Edition. Enterprise Java is largely business
and network oriented, and Micro Edition is what is typically used for hand-held
devices.
The diffrence is that core java is the fundamental for java that will be used in any
java technology without this no one can jump on any advance java technology.
Where as advance java is specialisation in some domain, such as networking, web,
DCOM or database handling.
And more over core java packages are always started with "java"
e.g.java.lang.....
where as advance java are always with "javax"
e.g.
javax.servlet....

Core Java uses the console for Input and output i.e - DOS Prompt

Advanced Java is more on the GUI side with a Window,Buttons,Frames,TitleBar,etc.
and is used to create more client-server based applications and applets.

What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes.
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class.
These are:
* Public
* Protected
* Private
* Defaults



Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains,
or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void


What is the class variables
When we create a number of objects of the same class, then each object will share a common
copy of variables. That means that there is only one copy per class, no matter how many
objects are created from it. Class variables or static variables are declared with the static
keyword in a class, but mind it that it should be declared outside a class. These variables are
stored in static memory. Class variables are mostly used for constants, variable that never
change its initial value. Static variables are always called by the class name. This variable is
created when the program starts i.e. it is created before the instance is created of class by using
new operator and gets destroyed when the programs stops. The scope of the class variable is
same a instance variable. The class variable can be defined anywhere at class level with the
keyword static. It initial value is same as instance variable. When the class variable is defined
as int then it's initial value is by default zero, when declared boolean its default value is false
and null for object references. Class variables are associated with the class, rather than with
any object.

Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.

Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object.
Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the
data into a single entity. This keeps the data safe from outside interface and misuse. One way
to think about encapsulation is as a protective wrapper that prevents code and data from being
arbitrarily accessed by other code defined outside the wrapper.

Explain the Polymorphism principle
The meaning of Polymorphism is something like one name many forms. Polymorphism enables
one entity to be used as as general category for different types of actions. The specific action is
determined by the exact nature of the situation. The concept of polymorphism can be explained
as "one interface, multiple methods".
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

* Method overloading
* Method overriding through inheritance
* Method overriding through the Java interface

What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a
Serializable class and the class is written to an ObjectStream, the value of the variable can't be
written to the stream instead when the class is retrieved from the ObjectStream the value of the
variable becomes null.



Overriding
y upplles ONLY to lnherlted methods
y ls reluted to polymorphlsm
y ob|ect type (NOT reference vurluble type) determlnes whlch overrlden method wlll be used ut
runtlme
y overrldlng method MUST huve the sume urgument llst (lf not, lt mlght be u cuse of overloudlng)
y overrldlng method MUST huve the sume return type; the exceptlon ls covariant return (used us of
Juvu 5) whlch returns u type thut ls u subcluss of whut ls returned by the overrlden method
y overrldlng method MUST NOT huve more restrlctlve uccess modlfler, but MAYhuve less restrlctlve
one
y overrldlng method MUST NOT throw new or brouder checked exceptlons, butMAY throw fewer or
nurrower checked exceptlons or uny unchecked exceptlons
y ubstruct methods MUST be overrldden
y flnul methods CANNOT be overrldden
y stutlc methods CANNOT be overrldden
y constructors CANNOT be overrldden

Overloading
y overloudlng cun tuke pluce ln the sume cluss or ln the subcluss
y overlouded methods MUST huve u dlfferent urgument llst
y overlouded methods MAY chunge the return type (ln cuse urgument llst ls dlfferent)
y overlouded methods MAY chunge the uccess modlfler
y overlouded methods MAY throw new or brouder checked excpetlons
y reference type determlnes whlch overlouded method wlll be used ut complle tlme
y constructors MAY be overlouded
y methods ud|ustment ln connectlon wlth overlouded methods urguments:
o you cannot wlden und then box (lnt -> Long)
o you can box und then wlden (lnt -> Ob|ect, vlu Integer)
o you can comblne vur urgs wlth elther wldenlng (byte -> lnt) or boxlng (lnt -> Integer):
wldenlng ls over boxlng
wldenlng ls over vur urgs
boxlng ls over vur urgs

the concept of Method Overloading:

-- In a class, the concept of method overloading does not allow the external user to be aware
about the internal processing of the system.

-- It just allows to user to use the different implementations of same name collected together
and react appropriately to the supplied parameters to get the desired output.

-- Method Overloading, allows the user to achieve the compile time polymorphism.

-- Overloaded methods are always the part of the same class. These methods have the same
name, but they may take different input parameters.

-- The arguments passed to a overloaded method may differ in type or in number, or both.

-- Overloaded methods may have the same or different return types.
)lnully, u few notes on polymorphlsm:
y u refenrence vurluble ls of un unchungeuble type, but cun refer to u subtype ob|ect
y u slngle ob|ect cun be referred to by reference vurluble of muny dlffernet types (however,
they MUST be the of sume type or supertype of the ob|ect)
y reference type determlnes whlch method wlll be culled.

Important:
Reference type determines which overloaded method is used at compile time.
Object type determines which overriden method is used at runtime.



Java Hello World Program

The following is the Hello World Application as written in Java. Type it into a text file or copy it
out of your web browser, and save it as a file named HelloWorld.java. This program
demonstrates the text output function of the Java programming language by displaying the
message "Hello world!". Java compilers expect the filename to match the class name.

A java program is defined by a public class that takes the form:
public class program-name {

optional variable declarations and methods

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

optional variable declarations and methods

}

Source Code
In your favorite editor, create a file called HelloWorld.java with the following contents:
/** Comment
* Displays "Hello World!" to the standard output.
*/
class HelloWorld {

public static void main (String args[]) {

System.out.println("Hello World!"); //Displays the enclosed
String on the Screen Console

}

}

To compile Java code, we need to use the 'javac' tool. From a command line, the command
to compile this program is:

javac HelloWorld.java

To run the program, you just run it with the java command:

java HelloWorld

Java Comments

The Java programming language supports three kinds of comments:

/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this
kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc
comments when preparing automatically generated documentation.
// text

The compiler ignores everything from // to the end of the line.

Java denotes comments in three ways:

1. Double slashes in front of a single line comment:

int i=5; // Set the integer to 5

2. Matching slash-asterisk (/*) and asterisk-slash (*/) to bracket multi-line comments:

/*
Set the integer to 5
*/
int i=5;

3. Matching slash-double asterisk (/**) & asterisk-slash(*/) for Javadoc automatic hypertext
documentation, as in

/**
This applet tests graphics.
*/
public class testApplet extends applet{...



Java Data and Variables

There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the
eight primitive data types are:
byte short int long float double char boolean

There are both integer and floating point primitive types. Integer types have no fractional part;
floating point types have a fractional part. On paper, integers have no decimal point, and floating
point types do. But in main memory, there are no decimal points: even floating point values are
represented with bit patterns. There is a fundamental difference between the method used to
represent integers and the method used to represent floating point numbers.
Integer Primitive Data Types
Type Size Range
Byte 8 bits -128 to +127
Short 16 bits -32,768 to +32,767
Int 32 bits (about)-2 billion to +2 billion
Long 64 bits (about)-10E18 to +10E18
Floating Point Primitive Data Types
Type Size Range
Float 32 bits -3.4E+38 to +3.4E+38
Double 64 bits -1.7E+308 to 1.7E+308

Examples
int yr = 2006;
double rats = 8912 ;
For each primitive type, there is a corresponding wrapper class. A wrapper class can be
used to convert a primitive data value into an object, and some type of objects into primitive
data. The table shows primitive types and their wrapper classes:
Primitive Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

Variables only exist within the structure in which they are defined. For example, if a variable is
created within a method, it cannot be accessed outside the method. In addition, a different
method can create a variable of the same name which will not conflict with the other variable. A
java variable can be thought of as a little box made up of one or more bytes that can hold a
value of a particular data type:
Syntax: variabletype variablename = data;

Source Code ( demonstrating declaration of a variable )
class example
{
public static void main ( String[] args )
{
long x = 123; //a declaration of a variable named x with a datatype of long

System.out.println("The variable x has: " + x );
}
}


Source Code
public class MaxDemo {
public static void main(String args[]) {
//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;

//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;

//other primitive types
char aChar = 'S';
boolean aBoolean = true;

//Display them all.
System.out.println("largest byte value is " + largestByte + ".");
System.out.println("largest short value is " + largestShort + ".");
System.out.println("largest integer value is " + largestInteger + ".");
System.out.println("largest long value is " + largestLong + ".");
System.out.println("largest float value is " + largestFloat + ".");
System.out.println("largest double value is " + largestDouble + ".");
}
}

Sample Run
The largest byte value is 127.
The largest short value is 32767.
The largest integer value is 2147483647.
The largest long value is 9223372036854775807.
The largest float value is 3.4028235E38.
The largest double value is 1.7976931348623157E308.

Java Arithmetic Operators


The Java programming language has includes five simple arithmetic operators like are +
(addition), - (subtraction), * (multiplication), / (division), and % (modulo).The following table
summarizes the binary arithmetic operators in the Java programming language.

Use Returns true if
op1 + op2 op1 added to op2
op1 - op2 op2 subtracted from op1
op1 * op2 op1 multiplied with op2
op1 / op2 op1 divided by op2
op1 % op2 Computes the remainder of dividing op1 by op2

The following java program, ArithmeticProg , defines two integers and two double-precision
floating-point numbers and uses the five arithmetic operators to perform different arithmetic
operations. This program also uses + to concatenate strings. The arithmetic operations are
shown in boldface.





public class ArithmeticProg {
public static void main(String[] args) {

//a few numbers
int i = 10;
int j = 20;
double x = 10.5;
double y = 20.5;
//adding numbers
System.out.println("Adding");
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));

//subtracting numbers
System.out.println("Subtracting");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));

//multiplying numbers
System.out.println("Multiplying");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));

//dividing numbers
System.out.println("Dividing");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));

//computing the remainder resulting
//from dividing numbers
System.out.println("Modulus");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));

}
}

Java Assignment Operators

It's very common to see statement like the following, where you're adding something to a
variable. Java Variables are assigned, or given, values using one of the assignment operators.
The variable are always on the left-hand side of the assignment operator and the value to be
assigned is always on the right-hand side of the assignment operator. The assignment operator
is evaluated from right to left, so a = b = c = 0; would assign 0 to c, then c to b then b to a.

i = i + 2;
Here we say that we are assigning i's value to the new value which is i+2.

A shortcut way to write assignments like this is to use the += operator. It's one operator symbol
so don't put blanks between the + and =.
i += 2; // Same as "i = i + 2"
The shortcut assignment operator can be used for all Arithmetic Operators i.e. You can use this
style with all arithmetic operators (+, -, *, /, and even %).

//assign 1 to
//variable a
int a = 1;

//assign the result
//of 2 + 2 to b
int b = 2 + 2;
//assign the literal
//"Hello" to str
String str = new String("Hello");

//assign b to a, then assign a
//to d; results in d, a, and b being equal
int d = a = b;

Java Increment and Decrement Operators

There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in
that they can be written both before the operand they are applied to, called prefix
increment/decrement, or after, called postfix increment/decrement. The meaning is different in
each case.
Example
x = 1;
y = ++x;
System.out.println(y);

prints 2, but

x = 1;
y = x++;
System.out.println(y);

prints 1

Source Code
//Count to ten

class UptoTen {

public static void main (String args[]) {
int i;
for (i=1; i <=10; i++) {
System.out.println(i);
}
}

}
When we write i++ we're using shorthand for i = i + 1. When we say i-- we're using shorthand for
i = i - 1. Adding and subtracting one from a number are such common operations that these
special increment and decrement operators have been added to the language. T
There's another short hand for the general add and assign operation, +=. We would normally
write this as i += 15. Thus if we wanted to count from 0 to 20 by two's we'd write:

Source Code
class CountToTwenty {

public static void main (String args[]) {
int i;
for (i=0; i <=20; i += 2) { //Note Increment Operator by 2
System.out.println(i);
}

} //main ends here

}
As you might guess there is a corresponding -= operator. If we wanted to count down from
twenty to zero by twos we could write: -=
class CountToZero {

public static void main (String args[]) {
int i;
for (i=20; i >= 0; i -= 2) { //Note Decrement Operator by 2
System.out.println(i);
}
}

}



Java Relational Operators

A relational operator compares two values and determines the relationship between them. For
example, != returns true if its two operands are unequal. Relational operators are used to test
whether two values are equal, whether one value is greater than another, and so forth. The
relation operators in Java are: ==, !=, <, >, <=, and>=. The meanings of these operators are:
Use Returns true if
op1 > op2 op1 is greater than op2
op1 >= op2 op1 is greater than or equal to op2
op1 < op2 op1 is less than to op2
op1 <= op2 op1 is less than or equal to op2
op1 == op2 op1 and op2 are equal
op1 != op2 op1 and op2 are not equal

Variables only exist within the structure in which they are defined. For example, if a variable is
created within a method, it cannot be accessed outside the method. In addition, a different
method can create a variable of the same name which will not conflict with the other variable.
The main use for the above relational operators are in CONDITIONAL phrases The following
java program is an example, RelationalProg, that defines three integer numbers and uses the
relational operators to compare them.
public class RelationalProg {
public static void main(String[] args) {

//a few numbers
int i = 37;
int j = 42;
int k = 42;
//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false
//(they are equal)

//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true

//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false

//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true

//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true

//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}


Java Boolean Operators
The Boolean logical operators are : | , & , ^ , ! , || , && , == , != . Java supplies a primitive data
type called Boolean, instances of which can take the value true or false only, and have the
default value false. The major use of Boolean facilities is to implement the expressions which
control if decisions and while loops.
These operators act on Boolean operands according to this table
A B A|B A&B A^B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false
| the OR operator
& the AND operator
^ the XOR operator
! the NOT operator
|| the short-circuit OR operator
&& the short-circuit AND operator
== the EQUAL TO operator
!= the NOT EQUAL TO operator

class Bool1{
public static void main(String args[]){

// these are boolean variables
boolean A = true;
boolean B = false;

System.out.println("A|B = "+(A|B));
System.out.println("A&B = "+(A&B));
System.out.println("!A = "+(!A));
System.out.println("A^B = "+(A^B));
System.out.println("(A|B)&A = "+((A|B)&A));
}
}

Boolean-expression ? expression-1 : expression-2

The JVM tests the value of Boolean-expression. If the value is true, it evaluates expression-
1; otherwise, it evaluates expression-2. For

Example
if (a > b) {
max = a;
}
else {
max = b;
}

Setting a single variable to one of two states based on a single condition is such a common use
of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the
conditional operator you can rewrite the above example in a single line like this:

max = (a > b) ? a : b;

Java If-Else Statement
The if-else class of statements should have the following form:

if (condition) {
statements;
}

if (condition) {
statements;
} else {
statements;
}

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
All programming languages have some form of an if statement that allows you to test
conditions. All arrays have lengths and we can access that length by referencing the
variable arrayname.length. We test the length of the args array as follows:
Source Code
// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

/* Now let's say hello */
System.out.print("Hello ");
if (args.length > 0) {
System.out.println(args[0]);
}
}

}




Java Loops (while, do-while and for loops)

A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical
loop may look like:

while there's more data {
Read a Line of Data
Do Something with the Data
}
There are many different kinds of loops in Java including while, for, and do while loops.
They differ primarily in the stopping conditions used.
For loops typically iterate a fixed number of times and then exit. While loops iterate
continuously until a particular condition is met. You usually do not know in advance how many
times a while loop will loop.
In this case we want to write a loop that will print each of the command line arguments in
succession, starting with the first one. We don't know in advance how many arguments there
will be, but we can easily find this out before the loop starts using the args.length. Therefore
we will write this with a for loop. Here's the code:



Source Code
// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

int i;

/* Now let's say hello */
System.out.print("Hello ");
for (i=0; i < args.length; i = i++) {
System.out.print(args[i]);
System.out.print(" ");
}
System.out.println();
}

}
We begin the code by declaring our variables. In this case we have exactly one variable, the
integer i. i
Then we begin the program by saying "Hello" just like before.
Next comes the for loop. The loop begins by initializing the counter variable i to be zero. This
happens exactly once at the beginning of the loop. Programming tradition that dates back to
Fortran insists that loop indices be named i, j, k, l, m and n in that order.
Next is the test condition. In this case we test that i is less than the number of arguments.
When i becomes equal to the number of arguments, (args.length) we exit the loop and go
to the first statement after the loop's closing brace. You might think that we should test
for i being less than or equal to the number of arguments; but remember that we began
counting at zero, not one.
Finally we have the increment step, i++ (i=i+1). This is executed at the end of each iteration
of the loop. Without this we'd continue to loop forever since i would always be less
than args.length.



Methods (Includes Recursive Methods)

A method is a group of instructions that is given a name and can be called up at any point in a
program simply by quoting that name. Each calculation part of a program is called a method.
Methods are logically the same as C's functions, Pascal's procedures and functions, and
Fortran's functions and subroutines.
When I wrote System.out.println("Hello World!"); in the first program we were using
the System.out.println() method. The System.out.println() method actually
requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than
including that code every time we need to print, we just call the
System.out.println() method.

You can write and call your own methods too. Methods begin with a declaration. This can
include three to five parts. First is an optional access specifier which can be public, private or
protected. A public method can be called from pretty much anywhere. A private method can
only be used within the class where it is defined. A protected method can be used anywhere
within the package in which it is defined. Methods that aren't specifically declared public or
private are protected by default.access specifier. We then decide whether the method is or is
not static.
Next is the name of the method.
Source Code
class FactorialTest { //calculates the factorial of that number.

public static void main(String args[]) {

int n;
int i;
long result;

for (i=1; i <=10; i++) {
result = factorial(i);
System.out.println(result);
}

} // main ends here


static long factorial (int n) {

int i;
long result=1;

for (i=1; i <= n; i++) {
result *= i;
}

return result;

} // factorial ends here


}

Potrebbero piacerti anche