Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
291 views

JAVA Notes

This document provides an overview of core Java concepts: 1. Java was developed by Sun Microsystems and is now owned by Oracle. It supports platform independence allowing code to run on any device. 2. The Java Development Kit (JDK) includes the Java language libraries, compiler, runtime environment (JRE), and virtual machine (JVM) which allows Java to run on different platforms. 3. Java supports both object-oriented concepts like classes, objects, and inheritance as well as non-OOP concepts like variables, data types, and control statements.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
291 views

JAVA Notes

This document provides an overview of core Java concepts: 1. Java was developed by Sun Microsystems and is now owned by Oracle. It supports platform independence allowing code to run on any device. 2. The Java Development Kit (JDK) includes the Java language libraries, compiler, runtime environment (JRE), and virtual machine (JVM) which allows Java to run on different platforms. 3. Java supports both object-oriented concepts like classes, objects, and inheritance as well as non-OOP concepts like variables, data types, and control statements.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

CORE JAVA/JAVA BASICS

 Java is a programing language.


 Developed by SUN (Standford University Network) microsystems and takeover by
ORACLE.
 Supports “Platform Independency”, so JAVA is called Platform Independent
Language.

Dependent conversions as per OS and bit size of processor


Platform= OS+ Device drivers+ bit size of processor+ …etc.
 Java language is available as JDK (Java development Kit) for installation. Here:
 JDK = Java language libraries (independent)+ Packages with built in Classes
(independent)+ JAVA compiler (independent)+ JRE (dependent).
 JRE = JVM (dependent)+ JRE libraries (independent).
 JVM = Just-in Time compiler (dependent)+ JVM libraries (independent).
From above formulas, ‘Just-in time compiler’ is dependent w.r.t platform. So, we can call
‘JVM’ as dependent. Because of this reason, we can call JRE as dependent. Due to this
reason, we need to download JDK software w.r.t platform.

Example:

1|Page JAVA NOTES


Case Study: (Compiler vs. Interpreter)
Compilation: ex: Java Compiler, C compiler, C++ compiler…. etc.
Interpretation: ex: browser, JavaScript, VbScript, Groovy Script….etc.

 Java is Object oriented language, means Java supports class, object, encapsulation,
abstraction, inheritance, polymorphism, coupling, cohesion, association, aggregation
and composition.
 Java supports non-oops concepts also like constants, variables, data types, control
statements, loops & arrays. Because of this, Java is not called as pure oop language.

a). Constants in JAVA:


 Constant is a storage (RAM) to store a value.
 Constant cannot allow changes.
 Syntax: final datatype constantname =value;
Example:
final int x=10;
final float y=2.7;
final boolean z=true;
final char c=‘Q’;
final string s=“abdul kalam”;

b). Variables in JAVA:


 Variable is also a storage (RAM) to store a value.
 Variable can allow changes.
 Syntax:
datatype variablename; // declaration
variablename = value; // assignment
(OR)
datatype variablename = value; //initialization
Example:
int x;
--------
--------
x=10;
-------
-------
x=20;
-------
-------
x=“kalam”; // wrong type of value

2|Page JAVA NOTES


Note: JAVA is strict language. Case sensitive language.
c). Datatypes in JAVA:

Program:
package javaTests;

import java.util.Scanner;

public class DataTypes1


{
public static void main(String[] args)
{
// Define an Variable using primitive data type
int x = 10;
System.out.println(x); // x is used as variable

// Define an object using derived data type


String y = "abdul kalam";
System.out.println(y); // y is used as variable
y.length(); // y used as object
int[] t = {23,54,65,78,98}; // t used as variable array
int l = t.length; // t used as object
System.out.println(l);

// define an object using class(user defined)


Scanner sc = new Scanner(System.in);
sc.nextLine(); // used as object
System.out.println(sc);
}
}

d). Primitive Datatypes:


 To declare variables and constants, we use primitive datatypes.
 In Java language, we will get below primitive datatypes:

3|Page JAVA NOTES


Note 1: When we declare variables and constants using primitive datatypes, memory will be
allocated for those variables and constants in RAM. Due to this reason, variables and
constants are having lifetime.
Example:

Note 2: When we initialize variable with a value, we need to enclose that value with single
quote for ‘char’, need to enclose that the value with double quotes for “String”, and no need
to use any quotes for remaining types like byte, short, int, long, float, double and boolean.

e). Derived Datatypes:


 This datatype is a composition of primitive datatypes.
Example 1:
char[] x=new char[20];
String x; // as derived datatype
Example 2:
int[] x=new int[20]; // as derived datatype
Example 3:
float[] x=new float[20]; // as derived datatype
Example 4:
String x= “abdul kalam”;
int[] y={5, -27, 45, 68};
float[] z={2.8, -13.4, 27.6, 7.8}; ….etc.
Example 5:
String x= “abdul kalam”; // here x behaves like variable
System.out.print(x.length()); // here x behaves like object

f). User defined Datatypes:


 A class/User defined data type is a template, which consists of data members and
methods.
 Syntax – 1: (default class)

It is a class in default focus, means it will be accessible in current package in current project.
 Syntax – 2:

It is a class in public focus, means it will be accessible in any package of current project.

4|Page JAVA NOTES


Note 1: To use public classes of one project in another project, we have to fallow any one of
below two ways:
Way – 1:
 Open our Eclipse IDE.
 File Menu.
 Import.
 General.
 Existing projects into workspace.
 Browse path of project folder.
 Select “copy projects into workspace”.
 Finish.
Way – 2:
 Open our project in Eclipse IDE.
 Right click on project/specific class.
 Export.
 Java.
 jar file.
 Next.
 Select 2nd, 3rd and 4th check boxes.
 Enter a name to jar file.
 Finish.
We have to use corresponding jar file in other projects via
 Right click on another project.
 Properties.
 Java build path.
 Libraries.
 Add external jars.
 Browse jar file path.
(OR)
 Go to mvnrepository.
 Register our jar file.
 Generate dependency code.
 Use that dependency code in other project pom.xml file for jar association.
Program:
package javaTests;

import java.util.Scanner;

public class DataTypes2


{
public static void main(String[] args)
{
// Define constant and variable using Primitive Data Type
final int fi = 111;
System.out.println(fi); // used as constant
int vi = 111;
System.out.println(vi); // used as variable

// Define new object using Class/user defined data type


Scanner sc = new Scanner(System.in);
sc.nextLine(); // used as object only to call methods
System.out.println("Enter Number");
sc.close();

// Define new object using derived data type (String, array[])


String y = "jagath chandra"; // used as object
System.out.println(y.length()); //used as object to call method
int[] z = {2345,123,45,6,987,12}; // used as variable array
5|Page JAVA NOTES
System.out.println(z.length); // used as object to call methods
}
}

g). Operators in Java:


 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Miscellaneous Operators
 Bitwise Operators

g.1). Arithmetic Operators:


 +  10+2=12
 -  10-2=8
 X  10x2=20
 /  10/2=5

 % (modules)  10%2=0
 ++  increment by 1
 --  decrement by 1
 //  comment
Example 1:
int x=10;
int y=++x; // pre increment (increase and then release)
here x=11 and then y=11.
Example 2:
int x=10;
int y=x++; // post increment (release and then increase)
here x=11 and then y=10.
Example 3:
int x=10;
int y=--x; //pre decrement (decrease and then release)
here x=9 and then y=9.
Example 4:
int x=10;
int y=x--; // post decrement (release and then decrease)
here x=9 and then y=10.
Example 5:
int x=10; int x=10;
++x; // individual statement x++;// individual statement
int y=x; int y=x;
both programs output is same
Example 6:
int x=10; int x=10;
--x; // individual statement x--;// individual statement
int y=x; int y=x;
both programs output is same

6|Page JAVA NOTES


g.2). Relational/Comparison Operators:
 ==  equals to
 Works for primitive datatype constants and variables, to compare values.
 Works for objects of various classes, to compare address of memory locations.

Example:
int x=10;
int y=10;
if (x==y) // compare values of variables
{
-----
-----
}
Example:
RemoteWebDriver driver1;
ChromeDriver driver2;
if (driver1==driver2) // compare addresses of memory locations of objects
{
-----
-----
}
Case Study:

StringBuilder x=new StringBuilder(“kalam”);


StringBuilder y=new StringBuilder(“kalam”);
x y
Kalam Kalam
1001 2001

7|Page JAVA NOTES


x == y // compare memory address (not same)
String x=new StringBuilder(“kalam”);
String y=new StringBuilder(“kalam”);

x y
Kalam Kalam
1001 2001

x == y // compare memory address (not same)


!=  not equals to
<  less than
>  greater than
<=  less than or equals to
>=  greater than or equals to
g.3) Logical Operators:
&&  and
||  or
!  not
g.4) Assignment Operators:
=  assign to
+=  x+=y means x=x+y.
-=  x-=y means x=x-y.
*=  x*=y means x=x*y.
/=  x/=y means x=x/y.
%=  x%=y means x=x%y.
g.5) Miscellaneous Operators in Java:
 Ternary Operator:

if (condition)
{
x=a;
}
else
{
x=b;
}

8|Page JAVA NOTES


 Instance of Operator:
We can use this operator to verify the class of given
object/instance/reference/pointer.

Note:
Unary Binary Ternary
-, ++, --, ~, …etc. +, -, *, /, %, instance of, (condition)? a:b
Operator with one …etc.
operand Operator with two Operator with three
Ex: operands operands
-10, Ex:
x++, 10+20,
--y a+b,
e instanceof WebElement

 g.6) Bitwise Operators in Java:


&  Bitwise AND
|  Bitwise OR
^  Bitwise XOR
<<  Left shift
>>  Right shift
>>>  Zero with Right shift
~  Negation (unary)
&=  x&=y means x= x&y
|=  x|=y means x= x|y
^=  x^=y means x=x^y
<<=  x<<=y means x=x<<y
>>=  x>>=y means x=x>>y

 here, bitwise AND (&) means:

x y x&y
0 0 0
0 1 0
1 0 0
1 1 1
binary - 0 and 1, 0 - false, 1 - true, when both are 1 only output is 1.

 here, bitwise OR (|) means:


9|Page JAVA NOTES
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
Anyone is 1 result is 1 and both are 1 then 1.

 here, bitwise XOR (^) means:

x y X^y
0 0 0
0 1 1
1 0 1
1 1 0
Both are same then result is 0, if different result is 1.
 here, negation or complement (~) means:

x ~x
0 1
1 0
 here, left shift operator (<<) means:
ex: 10<<3
step 1: binary code of 10:

step 2: make as 8 digits code by adding “0” s left side.


0 0 0 0 1 0 1 0
step 3: left shit to 3

0 0 0 0 1 0 1 0
0 1 0 1 0 0 0 0
Remove 3 digits left side and add three 0’s on right side.
step 4: convert to decimal number.
0 1 0 1 0 0 0 0
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0

0 + 64 + 0 + 16 + 0 + 0 + 0 + 0 = 80
 here, Right shift operator (>>) means:
ex: 10>>3
step 1: get binary code for 10
1 0 1 0
step 2: make as 8 digits code by adding “0” s left side.

10 | P a g e JAVA NOTES
0 0 0 0 1 0 1 0
step 3: Remove 3 digits right side and no adding

0 0 0 0 1 0 1 0
0 0 0 0 1
step 4: convert to decimal number.

0 0 0 0 1
2^4 2^3 2^2 2^1 2^0

0+0+0+0+1=1
 here, zero with Right shift operator (>>>) means:
ex: 10 >>> 3
step 1: get binary code for 10
1 0 1 0

step 2: make as 8 digits code by adding “0” s left side.


0 0 0 0 1 0 1 0
step 3: Remove 3 digits right side and add three 0’s at left side

0 0 0 0 1 0 1 0
0 0 0 0 0 0 0 1
step 4: convert to decimal number.

0 0 0 0 0 0 0 1
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0

0 + 0 + 0 + 0 + 0 + 0 + 0 +1 = 1
Note:
<< Left shift Remove digits at left side and add 0’s on
right side
>> Right shift remove digits at right side
>>> Zero with right shift Remove digits at right side and add 0’s
on left side
>> , >>> can give same output.

Example: Swapping 2 numbers.


 way-1:
x y
10 20
z=x; //10
x=y; //20
y=z; //10
here y is 10 and x is 20.
 way-2:
x y
10 20
x=x+y; //30
y=x-y; //30-20=10
11 | P a g e JAVA NOTES
x=x-y; //30-10=20
here y is 10 and x is 20.
 way-3:
x y
10 20
x=x*y; //200
y=x/y; // 200/20=10
x=x/y; // 200/10=20
here y is 10 and x is 20.
 way-4:

Note 1: (Operator’s precedence in Java)


 Like in mathematics, all computer languages can allow us to work with
operator’s precedence. Here precedence means order in execution.
 In Java:
Category Operators Associativity
1.unary (POST) operand++, operand-- Left to Right
2.unary (Remaining) ++operand, --operand, -operand, ~, ! Right to Left
3.Multiplicative *,/,% Left to Right
4.Addictive +,- Left to Right
5.Shift << , >> , >>> Left to Right
6.Relational <, >, <=, =>, instanceof Left to Right
7.Equality ==, != Left to Right
8.Bitwise &, ^, | Left to Right
9.Logical &&, || Left to Right
10.Ternary ?: Right to Left
11.Assignment =, +=, -=, /=, *=, %=, $=, |=, ^=, <<=, Right to Left
>>=.

 While running Java code, JRE can follow above (1 to 11) precedence while
running lengthy expressions.
12 | P a g e JAVA NOTES
If any brackets or method calls in expressions, those will run first before going
to above precedence.
Note 2: In Java language, “+” is overloaded operator. Here “+” works for addition
and concatenation.

Example:
10+2=12 // addition
“10” + “2” =102 // concatenation
Case Study:
int + int // addition
int + float // addition
float + int // addition
float + float // addition
 addition for numeric values in byte, short, int, long, float, double.
char + char // addition
 addition of ASCII values of chars
boolean + boolean // error
String + String //concatenation
boolean + any other type // error
any other type + boolean // error
numeric type + char // addition
char + numeric type // addition
 addition of numeric type value with ASII value of char
String + numeric type //concatenation as String
numeric type + String //concatenation as String
String + char //concatenation as String
char + String //concatenation as String

Note 3: In “chars” addition, Java can use ASCII equivalents.


0 – 9  48 to 57
a – z  97 to 122
A – Z  65 to 90

h). “Scanner” class:


 “Scanner” is a built-in interface class in “java.util” package in JDK.
 This class can provide methods to get data from keyboard in different types.

Scanner sc=new Scanner(System.in);


System.out.println(“enter a number”);
int x=sc.nextInt();//nextByte(), nextShort(), nextLong(), nextBigInteger()
System.out.println(“enter a decimal number”);
float y= sc.nextFloat();//nextDouble(), nextBigDecimal()
System.out.println(“enter a boolean number”);
boolean z=sc.nextBoolean();
System.out.println(“enter a String”);
String x=sc.nextLine();
Note 1: No direct method in Scanner class to take a char from keyboard. For it we have to
use:

13 | P a g e JAVA NOTES
Note 2:
 When we used nextInt() and then nextLine() in code, we can get chance to enter
number only but won’t get chance to give next string value.
 It’s because when we enter a number then press Enter, nextInt() consumes only the
number, not the “end of line”. When nextLine() executes, it consumes the “end of line”
still in the buffer from the first input.

i). Type casting vs. Type conversion vs. Data parsing:


 1. Type casting:
 In typing casting, a data type is converted into another data type by the
programmer (by us) using the casting operator during the program writing
(while writing code in Eclipse IDE).
 In typing casting, the destination data type may be smaller than the source data
type when converting the data type to another data type, that’s why it is also
called as “narrowing conversion”.
 Type casting example:
float x;
byte y;
y= (byte)x;
here, () is a casting operator. “byte” is a data type in which we want to convert
the source data type “float”.
 There is a possibility of data or information being lost in type casting because
one larger data type(float) converts to a smaller data type(byte).

 2. Type conversion:
 In type conversion, a data type is automatically converted into another data type
by a compiler at the compiler time (while writing code in Eclipse IDE).
 In type conversion, the destination data type cannot be smaller than the source
data type, that’s why it is also called “widening conversion”.
 One more important thing is that it can only be applied to compatible data types.
 Type conversion examples:
Example:
int x=30;
float y;

14 | P a g e JAVA NOTES
y=x; //y==30.000000
Example:
int n1=31;
int n2=031; // octal
int n3=0x31; // hexadecimal
int n4=0b1001; // binary
System.out.println(n1); //31
System.out.println(n2); //25
System.out.println(n3); //49
System.out.println(n4); //9
Example:
long x=1000*60*60*24*365;
long y=1000*60*60*24*365L;
System.out.println(x);
// wrong output due to correct output size is more than 8 bytes.
System.out.println(y);
// correct output because of memory expansion due to “L” suffix.
Here L for long type and F for float type. If these are creating any confusion, we are able to
go to “BigInteger” and “BigDecimal” classes, which classes objects can allow us to work with
large values.

 3.Parsing:

Telling the program to interpret (on runtime) a string into
integer/decimal/octal/binary/hexadecimal, etc.
 Parsing is to read the value of one object and then convert it to another type.
For example:
String s= “10”; // “10” is string
int i=Integer.parseInt(s); // 10 is int
here, we may have a string with a value of “10”, Internally that string contains the characters
‘1’ and ‘0’. The method “parseInt()” takes that string value and returns a real number 10.
Example:
String x=driver.findElement(locator).getAttribute(“maxlength”);
int y=Integer.parseInt(x);

j). “formatter” class:


 Java “Formatter” is a utility class that can handle formatting stream output in java.
 It is built to operate similarly to the C/C++ “printf()” function.
 It is used to format and output data to specific destination, such as a string or a file
output stream.
 A few common format specifiers are:
 %S or %s Specifies String.
 %X or %x Specifies hexadecimal integer.
 %o specifies Octal Integer.
 %d specifies Decimal Integer.
 %c specifies character.
 %T or %t specifies Time and date.
 %n Inserts newline character
 %B or %b specifies Boolean.
 %A or %a specifies floating point hexadecimal.
 %f specifies Decimal floating point.
 %% specifies inserts a% sign
15 | P a g e JAVA NOTES
%e or %E specifies scientific notification

%g specifies causes formatter to use either %f or %e, whichever is shorter

%h or %H specifies Hash code of the argument. (Hash code is also numbering

system like ASCII)
 Like “Formatter” class, we will get different facilities in java language for output
formatting or output streaming.
 way-1: (only to display formatted output in console)
System.out.printf(“my name is: %s%n”,“abdul kalam”);
 way-2: (get output into string variable)
Formatter f=new Formatter();
f.format(“My name is: %s”, “abdul kalam”);
String x=f.toString();
System.out.println(x);
 way-3: (get output into String variable)
String output=String.format(“%s=%d”, “joe”,35);
System.out.println(output);
 way-4: (get output into String variable)
StringBuilder sbuf=new StringBuilder();
Formatter fmt=new Formatter(sbuf);
fmt.format(“PI=%f%n”,Math PI);
String y=sbuf.toString();
System.out.println(y);
 here, the classes like StringBuilder, Formatter and Math are built-in classes in JDK.
 In above 4 ways, “Formatter” class methods are more effective.
 As an SDET, we have to decorate output messages to convey to managers and
developers.
 For messages decoration, we have to use below ways by including format specifiers.
 way-1: (only to display formatted output in eclipse console)
// via “System.out.printf()” method
System.out.printf(“My name is %s and age is %d”,“abdul kalam”, 83);
 way-2: (Get output into String variable)
// via “format()” method “Formatter” class
Formatter f=new Formatter();
f.format(“My name is %s and age is %d”,“abdul kalam”, 83”);
String x=f.toString();
System.out.println(x);
 way-3: (Get output into String variable)
// via “format()” method in “String” class
String y=String.format(“My name is %s and age is %d”,“abdul
kalam”, 83);
System.out.println(y);
 way-4: (Get output into String variable)
// via “StringBuilder” class
StringBuilder sbuf=new StringBuilder();
Formatter fmt=new Formatter(sbuf);
fmt.format(“My name is %s and age is %d”,“abdul kalam”, 83);
String z=sbuf.toString();
System.out.println(z);

 while formatting output text, the format specifiers for general strings, characters, and
numeric types are applied according to the following syntax:

16 | P a g e JAVA NOTES
% [argumentindex$] [flags] [width] [.pricision] Conversion
% |$ + 7 .2 f

k) Control statements in Java:


 to define alternation in code execution, we can use control statements.
Ex: Run either block1 or block2.
 In Java language, control statements are two types such as “condition” based and
“value” based.
 “condition” based statements are:
1. if
2. if-else
3. if-else if-else
4. Nested if
 “value” based statements are:
1. switch case
 Syntaxes:

 “else” block and “default” block are not mandatory.

Note: In Java language, we can get additional format specifiers like:


17 | P a g e JAVA NOTES
%n (for new line)
%% (to get % in result)
%ty (year in 2 digit)
%tY (year in 4 digit)
%tB (month in complete name)
%tb (month in short name)
%td (day in two digits) …etcetera.
Note: some times, we need to display output as per given format along with country,
language, region… etcetera.

Here, “locale” and “calendar” are classes in JDK.

l. loops:
 To execute a block of code for multiple times, we can use loops/iterations.
 Java can support 4 loops in 3 categories:
Condition Based Count Based List Based
while For for each
do while
 “while” loop is used to run a block of code as long as given condition is true. If
condition is false at any time, loop should be terminated and controller will go to next
statement which is outside of loop.

 “do-while” loop is used to run a block of code as long as given condition is true. but
here, block of code will be executed at least once when given condition is false initially.
 while loop – pre condition
do-while loop – post condition

 “for” loop is used to run a block of code for given no: of times.
for (initialization; condition; increment/decrement;)
{
18 | P a g e JAVA NOTES
----------
----------
}
Example 1:
for(int i=1; i<=10; i++)
{
--------
--------
} //10 iterations
Example 2:
for(int i=0; i<10; i++)
{
--------
--------
} //10 times
Example 3:
for(int i=1; i>=10; i--)
{
--------
--------
} //10 times
Example 4:
for(int i=0; i<10; i=i+2)
{
--------
--------
} //5 iterations
Example 5:
for(int i=0; ; i++)
{
--------
--------
} //infinite loop

Example 6:

Exercises:
1). Find Odd or Even Number:
 A number divided by 2 (reminder is 0) called as Even.
 A number not divided by 2 (reminder is 1) called as Odd.

19 | P a g e JAVA NOTES
Example:
public class OddEvenFinder
{
public static void main(String[] args)
{
int x=567487; // initialize the variable value
if(x%2==0) // condition for find Odd or Even Number
{
System.out.println("x Even Number");
}
else
{
System.out.println("x odd number");
}
}
}
2). Find Prime Number:
 A number divided by 1 and itself only, means that number can’t be divided by 2
to that (number – 1).
Example:
 x is prime when x is not divided by 2 to (x-1).
 7 is prime number because 7 not divided by 2, 3, 4, 5 and 6 (7-1).
Program:
public class PrimeNumberFinder
{
public static void main(String[] args)
{
// take a number from key board
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number ");
int x = sc.nextInt();
sc.close();
// check for Prime Number or Not
int flag = 0;
for (int i=2;i<x;i++) // 2 to x-1
{
if (x%i==0)
{
flag = 1;
break;
}
} // loop will be terminated either "at end" of because of "break"
if (flag==0)

20 | P a g e JAVA NOTES
{
System.out.printf("%d is a prime number",x);
}
else
{
System.out.printf("%d is not a prime number",x);
}
}
}

3). Get list of prime numbers within given Range:


Program:
public class PrimeNumbersWithinGivenRange
{
public static void main(String[] args)
{
// Take Limits from Key board
Scanner sc = new Scanner(System.in);
System.out.println("Enter Lower Limit");
long LowerLimit = sc.nextLong();
System.out.println("Enter Upper Limit");
long UpperLimit = sc.nextLong();
sc.close();
// print all Prime Numbers under given range
int count = 0;
for(long i=LowerLimit;i<=UpperLimit;i++)
{
// check each "i" value for prime or not in given range of values
int flag = 0;
for (int j=2;j<i;j++)
{
if (i%j==0) // 2 to i-1
{
flag = 1;
break;
}// loop will be terminated either "at end" of because of
"break"
if (flag==0)
{
System.out.printf("%d is a prime number %n",i);
21 | P a g e JAVA NOTES
count++;
}
}
}
System.out.printf("count of prime numbers under given range is
%d",count);
}
}
4). Display multiplication tables for given range of numbers:
Program:
public class MultiplicationOfTables
{
public static void main(String[] args)
{
// Takes Limits from keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter Lower Limit");
long LowerLimit = sc.nextLong();
System.out.println("Enter Upper Limit");
long UpperLimit = sc.nextLong();
// Print Multiplication tables under given limit
for(long i=LowerLimit;i<=UpperLimit;i++)
{
// Take each "i" to Multiplication of tables
System.out.println("Multiplication Table for"+i);
System.out.println("--------------");
for(int j=1;j<=10;j++)
{
System.out.printf("%d X %d = %d%n",i,j,i*j);
}
System.out.println("--------------");
}
}
}
5). Display sum of harmonic series of given limit:
Program:

22 | P a g e JAVA NOTES
6). Find Factorial on Numbers:
Program:
public class FactorialOnNumbers
{
public static void main(String[] args)
{
//Take a number from keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
int n = sc.nextInt();
sc.close();
// Calculate Factorial (4! is 4*3*2*1)
long f = 1; //initial o/p is 0 for sum and 1 for multiplications
for (int i=n;i>=1;i--) // n to 1
{
f = f * i;
}
System.out.printf("%d factorial value is %d",n,f);
}
}
7). Print Fibonacci series up to given limit:

Program:
public class FibonacciSeries
{
public static void main(String[] args)
{
// Take the Limit from Keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter Limit");
int l = sc.nextInt();
sc.close();
// form the series
int x = 0;
int y = 1;
System.out.printf("%d %d",x,y);
do
{
int z = x+y;
System.out.printf(" %d",z);
x = y;

23 | P a g e JAVA NOTES
y = z;
}while((x+y)<=1);
}
}
8). Find number of digits in given number:

Program:
public class FindCountOfDigitsInGivenNumber
{
public static void main(String[] args)
{
// take a number from keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
int n = sc.nextInt();
sc.close();
// find count digits in given number
int count = 0; // initial count is "0"
long temp = n; // declaring number as temp
while(temp!=0) // if temp not equal to "0"
{
temp = temp/10; // cut last digit
count++; // repeat above statement
}
System.out.printf("%d has %d digits",n,count);
System.out.printf(+n+" has "+count+" digits"); //Concatenation
}
}
9). Find Sum of digits of a given number:
public class SumOfDigitsOfGivenNumber
{
public static void main(String[] args)
{
// take a number from keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
long number = sc.nextLong();
sc.close();
// sum of digits of given number
int sum = 0; // initial Sum is '0'
long temporary=number;
// copy original number into temporary number
24 | P a g e JAVA NOTES
while(temporary!=0)
// when temporary value not equals to '0' loop will generate
{
int lastdigit=(int)(temporary%10); //get last digit
sum = sum + lastdigit; //add that last digit to sum
temporary =(long)temporary/10;
// cut that last digit from number
} // loop will terminated when temporary value gets '0'
System.out.printf(sum+" is the sum of digits of "+number,sum,number);
}
}

10). Find Sum of digits of a given number until that sum become a single digit:

public static void main(String[] args)


{
// take a number from Keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
long number = sc.nextLong(); // original number-7224
sc.close();
// sum of digits until get single digit
long temporary = number;
//copy original number into temporary variable-7224
while(temporary>9)//temporary value is above 9 loop will continue
{
int sum = 0; // initially sum of digits is '0'
while(temporary!=0)
{
25 | P a g e JAVA NOTES
int lastdigit = (int) (temporary%10);
// get last digit-4,2,2,7 5,1
sum = sum + lastdigit;
// add last digit to the sum-4,6,8,15 5,1
temporary = (long)temporary/10;
//cut last digit from number-722,72,7, 1
}
temporary = sum;
if(temporary<9)
{
break;
}
}
System.out.printf(temporary+" is the final sum of "+number,temporary,number);
}
}
11). Reverse the given number:

12). Find Armstrong number:

13). Get list of Armstrong numbers in given range:


Pending program

26 | P a g e JAVA NOTES
14). binary to decimal:

Pending program
Note 1: “Math” class is related to “java.lang” package in JDK. “pow()” is a static
method in “Math” class.
If we are interested, the below method is alternative to math.pow() to use in scripts:

Note 2: “Integer.parseInt()” method converts binary value to decimal by taking that


binary code as “String”.

Note 3:

15). Decimal to binary:

Pending program
16). Display pattern:

27 | P a g e JAVA NOTES
17).

18).

28 | P a g e JAVA NOTES
19).

20).

21).

29 | P a g e JAVA NOTES
22).

23).

30 | P a g e JAVA NOTES
Logic for 23:

24).

25).

26).

31 | P a g e JAVA NOTES
Side by side program

27).

28).

29).

32 | P a g e JAVA NOTES
30). Draw a box:
//upper line // edges

33 | P a g e JAVA NOTES
31). Draw a Ship:

m). “String” class:


 “String” is a class in “java.lang” package.
 It works like a derived data type:

 “String” is “immutable” type:


Ex:

 From the above example, “String” class object can display “value” because it
behaves like variable. But any other class’s object can display details of
corresponding class, package and allocated memory.
Ex:

34 | P a g e JAVA NOTES
 From the above examples, Hashing is the process of mapping the data to some
representative integer value using the concept of hashing algorithms.
 In Java, a hash code is an integer value that is linked with each object. If two
objects are equal, then their hash code will be identical. If there are two
different objects at two different memory locations, they will have strictly
different hashcodes.
(Or)

 In general,
1) When we create an object to any class, object gets memory in heap area.

35 | P a g e JAVA NOTES
2) But when we create a String variable/ object, it gets memory in String
Pool in heap area.

Here both objects refer same memory because values are same and String is
immutable.

36 | P a g e JAVA NOTES

You might also like