Java Day1
Java Day1
Overview
Java programming language was originally developed by Sun
Microsystems which was initiated by James Gosling and released in 1995
as core component of Sun Microsystems’ Java platform (Java 1.0 [J2SE]).
The latest version of Java till date is Java SE 13.0.1 released on September
2019.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE
and Java ME, respectively. Java is guaranteed to be Write Once, Run
Anywhere.
Features of Java
• Object Oriented - In Java, everything is an Object.
• Platform Independent - byte code is distributed over the web and interpreted by
virtual Machine (JVM)
• Simple -
• Portable -
• Interpreted - Java byte code is translated on the fly to native machine instructions
• High Performance - With the use of Just-In-Time compilers, Java enables high
performance
• Dynamic - Java programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.
The Java Development Kit (JDK) is a software development environment used for developing
Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/
loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and
other tools needed in Java development.
A JAR (Java Archive) is a package file format typically used to aggregate many Java class files
and associated metadata and resources (text, images, etc.) into one file to distribute application
software or libraries on the Java platform.
Object - Objects have states and behaviors. Example: A dog has states-color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
• Class - A class can be defined as a template/blue print that describes the behaviors/
states that object of its type support.
• Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
• Instance Variables - Each object has its unique set of instance variables. An object's state
is created by the values assigned to these instance variables.
Eclipse:
Eclipse is an integrated development environment (IDE) for developing
applications using the Java programming language and other
programming languages such as C/C++, Python, PERL, Ruby etc.
Downloading Eclipse
Installing Eclipse
Launching Eclipse:
Opening a Perspective
To open a new perspective, click on the Windows menu and select Open Perspective → Other
Customizing a Perspective
The customize perspective dialog can be used to customize a perspective. Customizing a
perspective means −
• Determining the icons visible on the toolbar when a perspective is active.
• Determining the menu items visible when a perspective is active.
• Determine the menu items in New submenu, Show View submenu and Open Perspective
submenu.
• The Tool Bar Visibility tab can be used to determine which icons are visible on the toolbar
when a perspective is open.
• The Menu Visibility tab can be used to determine which menu items are visible when a
perspective is active.
• The Command Groups Availability tab can be used to control the visibility of toolbar icons
and menu items.
• The Shortcuts tab can be used to determine the menu items in New submenu, Show View
submenu and Open Perspective submenu.
About Eclipse Workspace
The eclipse workspace contains resources such as −
• Projects
• Files
• Folders
The File Wizard (File → New → File) can be used to create a new file.
The Folder Wizard (File → New → Folder) can be used to create a new folder.
Creating New Package:
The newly created class should appear in the Package Explorer view and a java editor instance
that allows you to modify the new class.
Basic Syntax:
•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.
•Method Names - All method names should start with a Lower Case
letter
•Program File Name - Name of the program file should exactly
match the class name.
•public static void main(String args[]) - The main method must
be public so it can be found by the JVM when the class is loaded.
Similarly, it must be static so that it can be called after loading the
class, without having to create an instance of it. All methods must
have a return type, which in this case is void. String[] args in
Java is an array of strings which stores arguments passed by
command line while starting a program. All the command line
arguments are stored in that array.
Java Identifiers:
All Java components require names. Names used
for classes, variables and methods are called
identifiers
Java Variables:
• Local Variables
• Class Variables (Static Variables)
• Instance Variables (Non-static variables)
Java Keywords:
volatile while
Basic Data Types
•Primitive Data Types
The String class represents character strings. All string literals in Java
programs, such as "abc" , are implemented as instances of this class. Strings
are constant; their values cannot be changed after they are created. String
buffers support mutable strings.
StringBuffer in java is used to create modifiable String objects. This means that we
can use StringBuffer to append, reverse, replace, concatenate and manipulate Strings
or sequence of characters. StringBuffer and StringBuilder are called mutable because
whenever we perform a modification on their objects their state gets changed. And
they were created as mutable because of the immutable nature of String class.
String Builder
The StringBuilder Class. StringBuilder objects are like String objects, except that they
can be modified. Internally, these objects are treated like variable-length arrays that
contain a sequence of characters.
Variable Types
variable provides us with named storage that our programs can manipulate.
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = ‘a’;
Local variables:
• Local variables are declared in methods, constructors, or blocks.
• There is no default value for local variables
•Class variable is also known as static variable are declared with the
static keyword in the class
• Static variables are created when the program starts and
destroyed when the program stops.
• Static variable are rarely declared as constant. Constants are
variables that are declared as private / public , final and static.
Constant variable never change from their initial values.
• Visibilities is similar to instance variables. However most static
variables are declared public since they must be available for
users of the class.
• Static variables can be accessed by calling with the class name.
ClassName.VariableName
• tinyurl.com/rlpfeeback
• Bhuvaneswari
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
s1.display();
s2.display();
}
}
Access Modifiers
A class contains private data member and private method. We are accessing these
private members from outside the class, so there is a compile-time error.
2) Default
//save by A.java
package pack;
class A{
void msg(){
System.out.println(“Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
We are accessing the A class from outside its package, since A class is not public,
so it cannot be accessed from outside the package.
3) Protected
• The protected access modifier is accessible within package and outside the
package but through inheritance only.
• The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
• It provides more accessibility than the default modifer.
//save by A.java
package pack;
public class A{
protected void msg(){
System.out.println(“Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
//save by B.java
//save by A.java
package mypack;
package pack; import pack.*;
public class A{
public void msg(){ class B{
System.out.println("Hello");} public static void main(String args[]){
} A obj = new A();
obj.msg();
}
}
Basic Operators
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators
- Subtraction - Subtracts right hand operand from left hand A - B will give -10
operand
* Multiplication - Multiplies values on either side of the A * B will give 200
operator
/ Division - Divides left hand operand by right hand operand B / A will give 2
a * b =200
System.out.println("d++= "+(d++)); / / p o s t i n c r e m e n t
System.out.println("++d= “+(++d));//pre increment
}
Relational Operators:
>= Checks if the value of right operand is greater than or equal to (A >= B) is not true.
the value
<= Checks if the value of left operand is greater than or equal to
the value (A <= B) is true.
public class Test{
Output:
a == b =false
a != b =true
a > b =false
a < b =true
b >= a =true
b <= a =false
The Bitwise Operators:
Called Logical AND operator. If both the operands are non-zero, then
&& the condition becomes true. (A && B) is false.
Called Logical NOT Operator. Use to reverses the logical state of its
! operand. If a condition is true then Logical NOT operator will make !(A && B) is true.
false.
class Main {
public static void main(String[] args) { Output:
// declare variables
int a = 12, b = 12; Value of a: 12
int result1, result2; After increment: 13
Value of b: 12
// original value After decrement: 11
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Misc Operators
class Simple1{
public static void main(String args[]){ Output:
Simple1 s=new Simple1(); true
System.out.println(s instanceof Simple1);//true
}
}
Bracket = ( )
Order = Square root , Power of
Division = /
Multiplication = *
Addition = +
Subtraction = -
Loop Control
•while Loop
•do...while Loop
•for Loop Output:
value of x :10
value of x :11
while Loop:
value of x :12
value of x :13
public class Test{
value of x :14
public static void main(String args[]){ value of x :15
int x =10; value of x :16
while( x <20){ value of x :17
System.out.println(“value of x : "+ x ); value of x :18
x++; Va l u e o f x : 1 9
//System.out.print(“\n”);
}
}
}
The do...while Loop:
Output:
value of x :10
Syntax:
value of x :11
do
value of x :12
{
//Statements
}while(Boolean_expression);
Sytax:
for(initialization;Boolean_expression; update)
{
//Statements
}
public class Test{
Output:
public static void main(String args[]){ value of x :10
value of x :11
for(int x =10; x <20; x = x+1){ value of x :12
System.out.print("value of x : "+ x );
System.out.print("\n");
}
}
}
Enhanced for loop in Java:
Syntax:
for(declaration : expression)
{
//Statements
}
for(int x : numbers ){
System.out.print(x);
System.out.print(“,");
}
System.out.print("\n");
String[] names ={“James","Larry","Tom","Lacy"};
for(String name : names ){
System.out.print( name );
System.out.print(“,");
}
} Output:
} 10,20,30,40,50,
James,Larry,Tom,Lacy,
The break Keyword:
for(int x : numbers){
if( x ==30){
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Decision Making
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
Syntax:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression3){
//Executes when the Boolean expression 3 is true
}else{
//Executes when the none of the above condition is true.
}
public class Test{
if( x ==10){
System.out.print("Value of X is 10");
}else if( x ==20){
System.out.print("Value of X is 20");
}else if( x ==30){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
} Output:
} Value of X is30
Nested if...else Statement:
Syntax:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true if(Boolean_expression2){
//Executes when the Boolean expression 2 is true Output:
}
X =30and Y =10
}
public class Test{
if( x ==30){
if( y ==10){
System.out.print("X = 30 and Y = 10");
}
}
}
The switch Statement:
switch(expression){
case value :
//Statements
break;//optional
case value :
//Statements
break;//optional
//You can have any number of case statements.
default://Optional
//Statements
}
import java.util.*;
public class Test{ Output:
public static void main(String args[]){ $ java Test a Invalid grade Your grade is a
Scanner scan=new Scanner(System.in); $ java Test A Excellent!
Your grade is a A
System.out.println(“Enter the grade:”);
$ java Test C Welldone
char ch=scan.next().charAt(0); Your grade is a C
$
switch(ch)
{
case'A': System.out.println("Excellent!");
break;
case'B':
case'C': System.out.println("Well done");
break;
case'D':
System.out.println("You passed");
case'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
System.out.println("Your grade is "+ ch);
}
}
Nested Loops
A nested loop is a (inner) loop that appears in the loop body of another
(outer) loop. The inner or outer loop can be any type: while, do while, or
for. For example, the inner loop can be a while loop while an outer loop can
be a for loop.
for(int x : numbers){
if( x ==30){
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Number Methods:
SN Methods with Description
xxxValue()
1
Converts the value of this Number object to the xxx data type and returned it.
compareTo()
2
Compares this Number object to the argument.
equals()
3
Determines whether this number object is equal to the argument.
valueOf()
4
Returns an Integer object holding the value of the specified primitive.
toString()
5
Returns a String object representing the value of specified int or Integer.
parseInt()
6
This method is used to get the primitive data type of a certain String.
abs()
7
Returns the absolute value of the argument.
ceil()
8
Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
SN Methods with Description
floor()
9
Returns the largest integer that is less than or equal to the argument. Returned as a double.
rint()
10
Returns the integer that is closest in value to the argument. Returned as a double.
round()
11
Returns the closest long or int, as indicated by the method's return type, to the argument.
min()
12
Returns the smaller of the two arguments.
max()
13
Returns the larger of the two arguments.
exp()
14
Returns the base of the natural logarithms, e, to the power of the argument.
log()
15
Returns the natural logarithm of the argument.
pow()
16
Returns the value of the first argument raised to the power of the second argument.
sqrt()
17
Returns the square root of the argument.
sin()
18
Returns the sine of the specified double value.
cos()
19
Returns the cosine of the specified double value.
tan()
20
Returns the tangent of the specified double value.
asin()
21
Returns the arcsine of the specified double value.
acos()
22
Returns the arccosine of the specified double value.
atan()
23
Returns the arctangent of the specified double value.
atan2()
24
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
toDegrees()
25
Converts the argument to degrees
toRadians()
26
Converts the argument to radians.
random()
27
Returns a random number.
Characters
char ch ='a';
// an array of chars
char[] charArray ={‘a’,'b','c','d','e'};
isLetter()
1
Determines whether the specified char value is a letter.
isDigit()
2
Determines whether the specified char value is a digit.
isWhitespace()
3
Determines whether the specified char value is white space.
isUpperCase()
4
Determines whether the specified char value is uppercase.
isLowerCase()
5
Determines whether the specified char value is lowercase.
toUpperCase()
6
Returns the uppercase form of the specified char value.
toLowerCase()
7
Returns the lowercase form of the specified char value.
toString()
8
Returns a String object representing the specified character valuethat is, a one-character string.
public class Test{
Concatena(ng Strings:
"My name is “.concat("Zara");
String fs;
fs =String.format("The value of the float variable
is "+ "%f, while the value of the integer “+
"variable is %d, and the string “+
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
12 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
The String class represents character strings. All string literals in Java
programs, such as "abc" , are implemented as instances of this class. Strings
are constant; their values cannot be changed after they are created. String
buffers support mutable strings.
String Builder
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}