SlideShare une entreprise Scribd logo
1  sur  31
JAVA FUNDAMENTALS……..
By- Shalabh Chaudhary [GLAU]
Initially Called Oak, Renamed as Java in 1995.
Java Bytecode(portable code or p-code) file (.class ) <- LISP lang(AI)
JVM reads byte codes and translates into machine code for execution.
Java is a compiled programming language.
Compiler - create .class file[contain bytecodes - is in binary form]
Compiler translate Java prog into intermed lang called bytecodes, understood by Java interpreter
Class loader - To read bytecodes from .class file into memory.
JVM uses a combination of interpretation and just-in-time compilation to translate
bytecodes into machine language.
Interpreted code runs much slower compared to executable code.
Bytecode enables Java run time system to execute programs much faster.
Java class file is designed for 
 Platform independence
 Network mobility
Compilation & Execution Order 
1. Java Source Code
2. Compilation
3. Class Loader
4. Byte Code Verification
5. Interpretation
6. Execution
JRE: Java Runtime Environment. It is basically the Java Virtual Machine where your
Java programs run on. It also includes browser plugins for Applet execution.
JDK: It's the full featured Software Development Kit for Java, including JRE, and the
compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs.
JDK used to compile servlets also in JSP.
 Running Java programs => JRE
 For Java programming => JDK
PATH tells OS which directories(folders) to search for executable files. [Till /JDK/bin]
CLASSPATH is a parameter which tells the JVM or the Compiler, where to locate
classes that are not part of JDKS. [For Temporary setting <- In Environment Var]
The Java API 
 An Application Programming Interface, in the framework of java, is collection of
prewritten packages ,classes, and interfaces with the irrespective methods, fields and
constructors.
 The Java API, included with the JDK, describes the function of each of its components.
By- Shalabh Chaudhary [GLAU]
Java Keywords 
abstract break catch const
continue double extends float
for implements int native
new protected short super
switch throw try while
assert byte char
default else final
goto import interface
package public static
synchronized throws void
boolean case class
do enum finally
if instanceof long
private return strictfp
this transient volatile
Primitive DataTypes(8) 
DataType Size Default Value
1. Boolean 1 Bit false
2. Byte 1 Byte 0
3. Char 2 Bytes ‘u0000’
4. Short 2 Bytes 0
5. Int 4 Bytes 0
6. Float 4 Bytes 0.0f
7. Long 8 Bytes 0L
8. Double 8 Bytes 0.0d
 class Main {
public static void main(String ar[]) {
float f=1.2; // float f=(float)1.2; ‘or’ float f = 1.2f;
boolean b=1; // boolean b=true;
System.out.println(f);
System.out.println(b);
}
}
 class Test {
public static void main(String ar[]) {
double d=1.2D; // ‘or’ double d=1.2d; <= Both Correct.
System.out.println(d);
}
}
By- Shalabh Chaudhary [GLAU]
 class Test {
public static void main(String [ ] ar) {
int a=10,b=017,c=0X3A;
System.out.println(a+","+b+","+c); // >> 10,15,58
}
}
 Variable name can’t start with digits(0-9).
 class Test {
public static void main(String [] args) {
int x;
System.out.println(x); // >> = Error Variable initialization necessary
}
}
Types of Variables 
1. Local Variables:
 Tied to a method
 Scope of a local variable is within the method
2. Instance Variables (Non-Static):
 Tied to an object
 Scope of an instance variable is the whole class
3. Static Variables
 Tied to a class
 Shared by all instances of a class
Comparing Strings 
class Test {
public static void main(String [ ] args) {
String s1="Wipro";
String s2="Wipro";
System.out.println(s1.equals(s2)); // >> true
}
}
Logical Operators  [ Logical AND(&&) + OR(||) + NOT(!) ]
class Test{
public static void main(String[] args){
boolean a = true;
boolean b = false;
System.out.println(a&&b); // >> false <= Both true  true
By- Shalabh Chaudhary [GLAU]
System.out.println(a||b); // >> true <= Either/Both true  true
System.out.println(!(a && b)); // >> true <= Reverse value of bool expr
}
}
Shift Operators  [ Right(>>) + Left(<<) Shift ]
1. (>>) operator = To divide no. in multiples of 2.
Eg: int x = 16;
x = x>>3;
Output: 16/2^3  16/8  2
2. (<<) operator = To multiply no. in multiples of 2.
Eg: int y = 8;
y = y<<4;
Output: 8*2^4  8*16  128
Bitwise Operator [ Bitwise AND(&) + Inclusive OR(|) + Exclusive OR(^) ]
First Convert in Binary Form then,
1. & = Both bits are 1 => 1
2. | = EitherBoth bits 1 => 1
3. ^ = Different bits => 1
Passing command line arguments 
#1. Write a Program that accepts two Strings as command line arguments
and generate the output in a specific way as given below.
Example:
If the two command line arguments are Wipro and Bangalore then the
output generated should be Wipro Technologies Bangalore.
If the command line arguments are ABC and Mumbai then the output
generated should be ABC Technologies Mumbai
[Note: It is mandatory to pass two arguments in command line]
>>
public class CmdLineString {
public static void main(String[] args) {
System.out.println(args[0]+" Technologies "+args[1]);
}
}
By- Shalabh Chaudhary [GLAU]
#2. Write a Program to accept a String as a Command line argument and
the program should print a Welcome message.
Example :
C:> java Sample John
O/P Expected : Welcome John
>>
public class WelcomeMsg {
public static void main(String[] args) {
System.out.println("Welcome "+args[0]);
}
}
#3. Write a Program to accept two integers through the command line
argument and print the sum of the two numbers
Example:
C:>java Sample 10 20
O/P Expected : The sum of 10 and 20 is 30
Write a Program to accept two integers through the command line
argument and print the sum of the two numbers
Example:
C:>java Sample 10 20
O/P Expected : The sum of 10 and 20 is 30
>>
public class CmdLineValue {
public static void main(String[] args) {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
System.out.println("The sum of 10 and 20 is "+(n1+n2));
}
}
By- Shalabh Chaudhary [GLAU]
Flow Control 
1. Selection stmt. [ if + if..else + switch ]
2. Iteration stmt. [ for + while + do..while ]
3. Jumping stmt. [ break + continue + return ]
 public class DoWhile {
public static void main(String[]args){
int i=5;
do{
System.out.println("i:"+i); // >> 5
i++; // i=6
}while(i<5); // cond. False 6<5
}
}
 class BreakContinue {
public static void main(String args[]){
for(int i=1;i<=5;i++) {
if(i==4) break; // execution stops when i becomes 4
System.out.println(i); // >> 1 2 3
}
for(int i=1;i<=5;i++) {
if(i==1) continue; // execution skip when i becomes 1
System.out.println(i); // >> 2 3 4 5
}
}
}
 class Sample {
public static void main(String[]args) {
while(false) // while(true) then Infinite looping
System.out.print("whileloop"); // >> Error - Unreachable stmt.
}
}
 public class Sample {
public static void main(String[]args) {
for( ; ; )
System.out.println("For Loop"); // Infinite Looping
}
}
By- Shalabh Chaudhary [GLAU]
#1. Write a program to check if the program has received command line
arguments or not. If the program has not received the values then
print "No Values", else print all the values in a single line
separated by ,(comma).
Eg1) java Example
O/P: No values
Eg2) java Example Mumbai Bangalore
O/P: Mumbai,Bangalore
[Note: You can use length property of an array to check its length
>>
public class CountCmdLineArg {
public static void main(String[] args) {
if(args.length==0)
System.out.println("No Values");
else {
for(int i=0;i<args.length;i++) // for(String values:args)
System.out.print(args[i]+", "); // S.o.p(values+", ");
}
}
}
#2. Initialize two character variables in a program and display the
characters in alphabetical order.
Eg1) if first character is s and second is e
O/P: e,s
Eg2) if first character is a and second is e
O/P:a,e
>>
import java.util.Scanner;
public class AlphabetOrder {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
By- Shalabh Chaudhary [GLAU]
char c1=scan.next().charAt(0);
char c2=scan.next().charAt(0);
if(c1>c2)
System.out.print(c2+","+c1);
else
System.out.println(c1+","+c2);
}
}
 next() function returns the next token/word in the input as a string and
 charAt(0) function returns the first character in that string.
#3. Initialize a character variable in a program and if the value is
alphabet then print "Alphabet" if it’s a number then print "Digit" and
for other characters print "Special Character"
>>
import java.util.Scanner;
public class CheckAplhaDigSpec {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
char c=scan.next().charAt(0);
if((c>='a' && c<='z') || (c>='A' && c<='Z'))
System.out.println("Alphabet");
else if(c>='0' && c<='9')
System.out.println("Digit");
else
System.out.println("Special Sym");
}
}
By- Shalabh Chaudhary [GLAU]
#4. WAP to accept gender ("Male" or "Female") & age (1-120) from
command line arguments and print the percentage of interest based on
the given conditions.
Interest == 8.2%
Gender ==> Female
Age ==>1 to 58
Interest == 7.6%
Gender ==> Female
Age ==>59 -120
Interest == 9.2%
Gender ==> Male
Age ==>1-60
Interest == 8.3%
Gender ==> Male
Age ==>61-120
>>
public class GenderInterest {
public static void main(String[] args) {
String gender=args[0];
int age=Integer.parseInt(args[1]);
if(gender.equalsIgnoreCase("Female")) { // Compare Strings
if(age>=1 && age<=58)
System.out.println("Interest= 8.2%");
else if(age>58 && age<=120)
System.out.println("Interest= 7.6%");
}
else {
if(age>=1 && age<=60)
System.out.println("Interest= 9.2%");
else if(age>60 && age<=120)
System.out.println("Interest= 8.3%");
} }
}
By- Shalabh Chaudhary [GLAU]
#5. Write a program to convert from upper case to lower case and vice
versa of an alphabet and print the old character and new character as
shown in example (Ex: a->A, M->m).
>>
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
char c=scan.next().charAt(0);
int temp;
/*if (Character.isLowerCase(c))
System.out.println(c+"->"+Character.toUpperCase(c));
else
System.out.println(c+"->"+Character.toLowerCase(c)); */
if(c>='a' && c<='z') {
System.out.print(c+"->");
temp=(int)c;
c=(char)(temp-32);
System.out.println(c);
}
else {
System.out.print(c+"->");
temp=(int)c;
c=(char)(temp+32);
System.out.println(c);
}
}
}
By- Shalabh Chaudhary [GLAU]
#6. Write a program to print the color name, based on color code. If
color code in not valid then print "Invalid Code". R->Red, B->Blue, G-
>Green, O->Orange, Y->Yellow, W->White.
>>
public class ColorCode {
public static void main(String[] args) {
char ch=args[0].charAt(0); // Input character using Cmd Line
switch(ch) {
case 'R': System.out.println("R->Red");
break;
case 'B': System.out.println("B->Blue");
break;
case 'G': System.out.println("G->Green");
break;
case 'O': System.out.println("O->Orange");
break;
case 'Y': System.out.println("Y->Yellow");
break;
case 'W': System.out.println("W->White");
break;
default: System.out.println("Invalid");
}
}
}
By- Shalabh Chaudhary [GLAU]
#7. Write a program to check if a given number is prime or not
>>
public class CheckPrime {
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int count=0;
for(int i=1;i<=n;i++) {
if(n%i==0)
count++;
}
scan.close();
if(count==2)
System.out.println("prime");
else
System.out.println("Not prime");
}
}
#8. Write a Java program to find if the given number is prime or not.
Example1:
C:>java Sample
O/P Expected : Please enter an integer number
Example2:
C:>java Sample 1
O/P Expected : 1 is neither prime nor composite
Example3:
C:>java Sample 0
O/P Expected : 0 is neither prime nor composite
Example4:
By- Shalabh Chaudhary [GLAU]
C:>java Sample 10
O/P Expected : 10 is not a prime number
Example5:
C:>java Sample 7
O/P Expected : 7 is a prime number
>>
public class CheckPrimeComp {
public static void main(String[]args) {
int n=Integer.parseInt(args[0]);
int c=0;
if(args.length==0)
System.out.println("Please Enter int number");
else if(n==0 || n==1)
System.out.println(n+" is neither prime nor composite");
else {
for(int i=1;i<=n;i++) {
if(n%i==0)
c++;
}
}
if(c==2)
System.out.println(n+" is a Prime number");
else
System.out.println(n+" is not a Prime number");
}
}
By- Shalabh Chaudhary [GLAU]
#9. Write a program to print prime numbers between 10 and 99.
>>
public class PrimeBetween {
public static void main(String[]args) {
int temp,i;
for(i=10;i<=99;i++) {
temp=0;
for(int j=2;j<i;j++) {
if(i%j==0) {
temp=1;
break;
}
}
if(temp==0)
System.out.println(i);
}
}
}
#10. Write a program to add all the values in a given number and
print. Ex: 1234->10
>>
public class AddDigitNum {
public static void main(String[] args) {
int n=12345;
int rem,val=0;
while(n!=0) {
rem=n%10;
val=val+rem;
n=n/10;
By- Shalabh Chaudhary [GLAU]
}
System.out.println(val);
}
}
#11. Write a program to print * in Floyds format (using for and while
loop)
*
* *
* * *
Example1:
C:>java Sample
O/P Expected : Please enter an integer number
Example1:
C:>java Sample 3
O/P Expected :
*
* *
* * *
>>
public class FloydsForm {
public static void main(String[]args) {
int n=Integer.parseInt(args[0]);
for(int i=0;i<n;i++) {
for(int j=0;j<=i;j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
By- Shalabh Chaudhary [GLAU]
#12. Write a program to reverse a given number and print
Eg1)
I/P: 1234
O/P:4321
Eg2)
I/P:1004
O/P:4001
>>
public class ReverseNum {
public static void main(String[] args) {
int n=12345;
int rem;
while(n!=0) {
rem=n%10;
System.out.print(rem);
n=n/10;
}
}
}
#13. Write Java program to find if given number is palindrome or not
Example1:
C:>java Sample 110011
O/P Expected: 110011 is a palindrome
Example2:
C:>java Sample 1234
O/P Expected: 1234 is not a palindrome
>>
public class PalindromeNum {
public static void main(String[] args) {
By- Shalabh Chaudhary [GLAU]
int n=Integer.parseInt(args[0]);
int temp=n;
int cur=0,rem;
while(temp!=0) {
rem=temp%10;
cur=cur*10+rem;
temp=temp/10;
}
if(n==cur)
System.out.println(n+" is a Palindrome");
else
System.out.println(n+" is not a Palindrome");
}
}
#14. Write a program to print first 5 values which are divisible by 2,
3, and 5.
>>
public class First5Div {
public static void main(String[]args) {
int count=0,i=1;
while(count<5) {
if(i%2==0 && i%3==0 && i%5==0) {
System.out.println(i);
count++;
}
i++;
}
} }
By- Shalabh Chaudhary [GLAU]
Handling Arrays 
An array is a container object that holds a fixed number of values of a single type.
Syntax:
int[] ar = new int[ar_size]; // new allocates mem. for all ar int
 Example using foreach Loops :
public class UseForEach {
public static void main(String[] args) {
double[] ar = {1.9, 2.9, 3.4, 3.5};
for (double ele:ar)
System.out.println(ele); // Print all elements
}
}
 Passing Arrays to Methods :
mthdName(new int[]{3, 1, 2, 6, 4, 2});
 To Find Array Size :
int ar_len = ar.length;
Array Copy 
arraycopy static method from System class -To copy arr ele from one arr
to another array.
Syntax :
public static void arraycopy(obj src, int srcIndx, obj dest, int destIndx, src.length)
 Eg:
int[] src = {1,2,3,4,5,6};
int[] dest = newint[10];
System.arraycopy(src,0,dest,0,src.length);
Two-Dimensional Arrays 
Two-dimensional arrays are arrays of arrays.
 Initialization :
int[][] ar = new int[row_size][col_size];
 row_size is mandatory, col_size can be empty else get err.
 Eg:
1. int[][] y = { {1,2,3}, {4,5,6}, {7,8,9} };
2. int[][] y = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
By- Shalabh Chaudhary [GLAU]
OUTPUT BASED -
int[] a = new int[5]{1,2,3,4}; // INVALID - Highlighted wrong
int a[5] = new int[5]; // INVALID - Highlighted wrong
 class Test {
public static void main(String[] args) {
while(false)
System.out.println("while loop"); // Err – Unreachable stmt.
}
}
 class Test {
public static void main(String[] args) {
int[] x=new int[10];
System.out.println(x[4]); // Output- 0 {Every ele of arr=0}
}
}
 class Test {
public static void main(String [ ] args) {
int x[][]=new int[10] [ ];
System.out.println(x[4][0]); // Output- Run Time Error NullPtrExcp
}
}
#1. Write a program to initialize an integer array and print the sum
and average of the array
>>
public class ArraySumAvg {
public static void main(String [ ] args) {
int ar[]=new int[]{1,2,3,4,5};
int sum=0;
float avg=0.0f;
for(int ele:ar)
sum=sum+ele;
avg=(float)sum/ar.length;
System.out.println(sum+" "+avg);
}
}
By- Shalabh Chaudhary [GLAU]
#2. Write a program to initialize an integer array & find the maximum
and minimum value of an array
>>
Import java.util.Scanner;
public class MaxMin {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
//System.out.println("Enter Size of Array");
int n=scan.nextInt();
int ar[]=new int[n];
//System.out.println("Enter Array Ele");
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
int max=ar[0];
int min=ar[0];
for(int i:ar)
if(i>max)
max=i;
else if(i<min)
min=i;
System.out.println("Max "+max);
System.out.println("Min "+min);
}
}
By- Shalabh Chaudhary [GLAU]
#3. WAP to initialize integer array with values & check if given no is
present in the array or not. If the number is not found, it will print
-1 else it will print the index value of the given number in array.
Ex1) Array elements are {1,4,34,56,7} and the search element is 90
O/P: -1
Ex2) Array elements are {1,4,34,56,7} and the search element is 56
O/P: 4
>>
import java.util.Scanner;
public class FindEle {
public static void main(String [ ] args) {
Scanner scan=new Scanner(System.in);
//System.out.println("Enter no. of Ele in Array");
int n=scan.nextInt();
int ar[]=new int[n];
//System.out.println("Enter Array Ele");
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
System.out.println("Enter ele to Search");
int ele=scan.nextInt();
int flag=0,i;
for(i=0;i<n;i++)
if(ar[i]==ele) {
flag=1;
break;
}
if(flag==1)
System.out.println(ele+" at pos "+(i+1));
else
System.out.println(-1);
}
}
By- Shalabh Chaudhary [GLAU]
#4. Initialize an integer array with ascii values and print the
corresponding character values in a single row.
>>
import java.util.Scanner;
public class ASCII2Symb {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
//System.out.println("Enter no. of Ele in Array");
int n=scan.nextInt();
int ar[]=new int[n];
//System.out.println("Enter Array Ele");
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
char ch=0;
int i;
for(i=0;i<n;i++) {
ch=(char)ar[i];
System.out.print(ar[i]+"->"+ch+", ");
}
}
}
#5. Write a program to find the largest 2 numbers and the smallest 2
numbers in the given array
>>
import java.util.Scanner;
public class Larget2Smallest {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int ar[]=new int[n];
By- Shalabh Chaudhary [GLAU]
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
int max1,max2,min1,min2;
max1=max2=Integer.MIN_VALUE;
min1=min2=Integer.MAX_VALUE;
for(int i=0;i<n;i++) {
if(ar[i]>max1) {
max2=max1;
max1=ar[i];
}
else if(ar[i]>max2)
max2=ar[i];
}
System.out.println("Largest: "+max1+" & "+max2);
for(int i=0;i<n;i++) {
if(ar[i]<min1) {
min2=min1;
min1=ar[i];
}
else if(ar[i]<min2)
min2=ar[i];
}
System.out.println("Smallest: "+min1+" & "+min2);
}
}
 Integer.MIN_VALUE specifies - Integer variable can’t store any value below this limit i.e., limit of int.
 Integer.MAX_VALUE – Max value a variable can hold.
By- Shalabh Chaudhary [GLAU]
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Eg:
I-Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Compares first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), No swap.
II-Pass:
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
III-Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
 Algorithm:
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(ar[j]>ar[j+1]) {
int temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
#6. Write a program to initialize an array and print them in a sorted
fashion.
>>
import java.util.Scanner;
public class ArraySort {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
By- Shalabh Chaudhary [GLAU]
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(ar[j]>ar[j+1]) {
int temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
for(int i=0;i<n;i++)
System.out.print(ar[i]+" ");
}
}
 Arrays.sort(ar); ==> To sort any Array. ar-Array to sort.
7
Write a program to remove the duplicate elements in an array and
print
Eg) Array Elements--12,34,12,45,67,89
O/P: 12,34,45,67,89
>>
import java.util.Scanner;
public class RemoveDuplictes {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
By- Shalabh Chaudhary [GLAU]
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(ar[j]>ar[j+1]) {
int temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
System.out.println("Sorted Array:");
for (int i=0; i<n; i++)
System.out.print(ar[i]+" ");
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++)
if (ar[i] != ar[i+1])
temp[j++] = ar[i]; // Store ele if curr_ele!=next_ele
temp[j++] = ar[n-1]; // Store last_ele unique/repeated, not stored prev
// Modify original array
for (int i=0; i<j; i++)
ar[i] = temp[i];
System.out.println("nArray without Duplicates:");
for (int i=0; i<j; i++)
System.out.print(ar[i]+" ");
}
}
By- Shalabh Chaudhary [GLAU]
8
Write a program to print the element of an array that has occurred
the highest number of times
Eg) Array -> 10,20,10,30,40,100,99
O/P:10
>>
import java.util.Arrays;
import java.util.Scanner;
public class HighestFrequency {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
Arrays.sort(ar);
int max_count=1,cur_count=1;
int res=ar[0];
for(int i=1;i<n;i++)
if(ar[i]==ar[i-1])
cur_count++;
else {
if(cur_count>max_count) {
max_count=cur_count;
res=ar[i-1];
}
cur_count=1;
}
if(cur_count>max_count) {
max_count=cur_count;
By- Shalabh Chaudhary [GLAU]
res=ar[n-1];
}
System.out.println("Max Occured ele: "+res);
}
}
 Efficient solution – If Use Hashing - O(n). [For Above Q.]
9
Write a program to print the sum of the elements of the array with
the given below condition. If the array has 6 and 7 in succeeding
orders, ignore 6 and 7 and the numbers between them for the
calculation of sum.
Eg1) Array Elements - 10,3,6,1,2,7,9
O/P: 22
[i.e 10+3+9]
Eg2) Array Elements - 7,1,2,3,6
O/P:19
Eg3) Array Elements - 1,6,4,7,9
O/P:10
>>
import java.util.Scanner;
public class SumExceptBetween67 {
public static void main(String [] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=scan.nextInt();
int flag=0;
int sum=0;
for(int i:ar) {
By- Shalabh Chaudhary [GLAU]
if(i==6)
flag=1;
if(flag==1) {
if(i==7)
flag=0;
continue; // Above code to skip val b/w 6 to 7
}
else {
// If first get 7 then add 6, next time 6 come then skipped from above code
if(i==7)
sum+=i+6;
else
sum+=i;
}
}
System.out.println("Total: "+sum);
}
}
#10. Write a program to reverse the elements of a given 2*2 array.
Four integer numbers needs to be passed as Command Line arguments.
Example1:
C:>java Sample 1 2 3
O/P Expected : Please enter 4 integer numbers
Example2:
C:>java Sample 1 2 3 4
O/P Expected :
The given array is :
1 2
By- Shalabh Chaudhary [GLAU]
3 4
The reverse of the array is :
4 3
2 1
1 2 3 4
5 6 7 8
9 10 11 12
>>
#11. Write a program to find greatest number in a 3*3 array. The
program is supposed to receive 9 integer numbers as command line
arguments.
Example1:
C:>java Sample 1 2 3
O/P Expected : Please enter 9 integer numbers
Example2:
C:>java Sample 1 23 45 55 121 222 56 77 89
O/P Expected :
The given array is :
1 23 45
55 121 222
56 77 89
The biggest number in the given array is 222
>>
Self
By- Shalabh Chaudhary [GLAU]
IMPORTANT QUESTIONS 
1. What is JIT compiler?
2. What is Adaptive optimizer?
3. What is Byte Code Verifier?
4. What is the difference between a Compiler and Interpreter?
5. What are the components of JVM?
6. How do you assign values for PATH and CLASSPATH Variable?
7. What are all the characteristic features of Java Programming language?

Contenu connexe

Tendances (20)

Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
core java
core javacore java
core java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java operators
Java operatorsJava operators
Java operators
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdfJAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdf
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Similaire à Java Fundamentals

JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Java performance
Java performanceJava performance
Java performanceSergey D
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 

Similaire à Java Fundamentals (20)

00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Java performance
Java performanceJava performance
Java performance
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java programs
Java programsJava programs
Java programs
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Java
Java Java
Java
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
JAVA_BASICS.ppt
JAVA_BASICS.pptJAVA_BASICS.ppt
JAVA_BASICS.ppt
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 

Plus de Shalabh Chaudhary

Plus de Shalabh Chaudhary (14)

Everything about Zoho Workplace
Everything about Zoho WorkplaceEverything about Zoho Workplace
Everything about Zoho Workplace
 
C Pointers & File Handling
C Pointers & File HandlingC Pointers & File Handling
C Pointers & File Handling
 
C MCQ & Basic Coding
C MCQ & Basic CodingC MCQ & Basic Coding
C MCQ & Basic Coding
 
Database Management System [DBMS]
Database Management System [DBMS]Database Management System [DBMS]
Database Management System [DBMS]
 
PL-SQL, Cursors & Triggers
PL-SQL, Cursors & TriggersPL-SQL, Cursors & Triggers
PL-SQL, Cursors & Triggers
 
Soft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] NotesSoft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] Notes
 
Software Engineering (SE) Notes
Software Engineering (SE) NotesSoftware Engineering (SE) Notes
Software Engineering (SE) Notes
 
Operating System (OS) Notes
Operating System (OS) NotesOperating System (OS) Notes
Operating System (OS) Notes
 
Data Communication & Networking Notes
Data Communication & Networking NotesData Communication & Networking Notes
Data Communication & Networking Notes
 
Java Basics for Interview
Java Basics for InterviewJava Basics for Interview
Java Basics for Interview
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Unified Modeling Language(UML) Notes
Unified Modeling Language(UML) NotesUnified Modeling Language(UML) Notes
Unified Modeling Language(UML) Notes
 
Advanced JAVA Notes
Advanced JAVA NotesAdvanced JAVA Notes
Advanced JAVA Notes
 
Core JAVA Notes
Core JAVA NotesCore JAVA Notes
Core JAVA Notes
 

Dernier

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 

Dernier (20)

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 

Java Fundamentals

  • 1. JAVA FUNDAMENTALS…….. By- Shalabh Chaudhary [GLAU] Initially Called Oak, Renamed as Java in 1995. Java Bytecode(portable code or p-code) file (.class ) <- LISP lang(AI) JVM reads byte codes and translates into machine code for execution. Java is a compiled programming language. Compiler - create .class file[contain bytecodes - is in binary form] Compiler translate Java prog into intermed lang called bytecodes, understood by Java interpreter Class loader - To read bytecodes from .class file into memory. JVM uses a combination of interpretation and just-in-time compilation to translate bytecodes into machine language. Interpreted code runs much slower compared to executable code. Bytecode enables Java run time system to execute programs much faster. Java class file is designed for   Platform independence  Network mobility Compilation & Execution Order  1. Java Source Code 2. Compilation 3. Class Loader 4. Byte Code Verification 5. Interpretation 6. Execution JRE: Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution. JDK: It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs. JDK used to compile servlets also in JSP.  Running Java programs => JRE  For Java programming => JDK PATH tells OS which directories(folders) to search for executable files. [Till /JDK/bin] CLASSPATH is a parameter which tells the JVM or the Compiler, where to locate classes that are not part of JDKS. [For Temporary setting <- In Environment Var] The Java API   An Application Programming Interface, in the framework of java, is collection of prewritten packages ,classes, and interfaces with the irrespective methods, fields and constructors.  The Java API, included with the JDK, describes the function of each of its components.
  • 2. By- Shalabh Chaudhary [GLAU] Java Keywords  abstract break catch const continue double extends float for implements int native new protected short super switch throw try while assert byte char default else final goto import interface package public static synchronized throws void boolean case class do enum finally if instanceof long private return strictfp this transient volatile Primitive DataTypes(8)  DataType Size Default Value 1. Boolean 1 Bit false 2. Byte 1 Byte 0 3. Char 2 Bytes ‘u0000’ 4. Short 2 Bytes 0 5. Int 4 Bytes 0 6. Float 4 Bytes 0.0f 7. Long 8 Bytes 0L 8. Double 8 Bytes 0.0d  class Main { public static void main(String ar[]) { float f=1.2; // float f=(float)1.2; ‘or’ float f = 1.2f; boolean b=1; // boolean b=true; System.out.println(f); System.out.println(b); } }  class Test { public static void main(String ar[]) { double d=1.2D; // ‘or’ double d=1.2d; <= Both Correct. System.out.println(d); } }
  • 3. By- Shalabh Chaudhary [GLAU]  class Test { public static void main(String [ ] ar) { int a=10,b=017,c=0X3A; System.out.println(a+","+b+","+c); // >> 10,15,58 } }  Variable name can’t start with digits(0-9).  class Test { public static void main(String [] args) { int x; System.out.println(x); // >> = Error Variable initialization necessary } } Types of Variables  1. Local Variables:  Tied to a method  Scope of a local variable is within the method 2. Instance Variables (Non-Static):  Tied to an object  Scope of an instance variable is the whole class 3. Static Variables  Tied to a class  Shared by all instances of a class Comparing Strings  class Test { public static void main(String [ ] args) { String s1="Wipro"; String s2="Wipro"; System.out.println(s1.equals(s2)); // >> true } } Logical Operators  [ Logical AND(&&) + OR(||) + NOT(!) ] class Test{ public static void main(String[] args){ boolean a = true; boolean b = false; System.out.println(a&&b); // >> false <= Both true  true
  • 4. By- Shalabh Chaudhary [GLAU] System.out.println(a||b); // >> true <= Either/Both true  true System.out.println(!(a && b)); // >> true <= Reverse value of bool expr } } Shift Operators  [ Right(>>) + Left(<<) Shift ] 1. (>>) operator = To divide no. in multiples of 2. Eg: int x = 16; x = x>>3; Output: 16/2^3  16/8  2 2. (<<) operator = To multiply no. in multiples of 2. Eg: int y = 8; y = y<<4; Output: 8*2^4  8*16  128 Bitwise Operator [ Bitwise AND(&) + Inclusive OR(|) + Exclusive OR(^) ] First Convert in Binary Form then, 1. & = Both bits are 1 => 1 2. | = EitherBoth bits 1 => 1 3. ^ = Different bits => 1 Passing command line arguments  #1. Write a Program that accepts two Strings as command line arguments and generate the output in a specific way as given below. Example: If the two command line arguments are Wipro and Bangalore then the output generated should be Wipro Technologies Bangalore. If the command line arguments are ABC and Mumbai then the output generated should be ABC Technologies Mumbai [Note: It is mandatory to pass two arguments in command line] >> public class CmdLineString { public static void main(String[] args) { System.out.println(args[0]+" Technologies "+args[1]); } }
  • 5. By- Shalabh Chaudhary [GLAU] #2. Write a Program to accept a String as a Command line argument and the program should print a Welcome message. Example : C:> java Sample John O/P Expected : Welcome John >> public class WelcomeMsg { public static void main(String[] args) { System.out.println("Welcome "+args[0]); } } #3. Write a Program to accept two integers through the command line argument and print the sum of the two numbers Example: C:>java Sample 10 20 O/P Expected : The sum of 10 and 20 is 30 Write a Program to accept two integers through the command line argument and print the sum of the two numbers Example: C:>java Sample 10 20 O/P Expected : The sum of 10 and 20 is 30 >> public class CmdLineValue { public static void main(String[] args) { int n1 = Integer.parseInt(args[0]); int n2 = Integer.parseInt(args[1]); System.out.println("The sum of 10 and 20 is "+(n1+n2)); } }
  • 6. By- Shalabh Chaudhary [GLAU] Flow Control  1. Selection stmt. [ if + if..else + switch ] 2. Iteration stmt. [ for + while + do..while ] 3. Jumping stmt. [ break + continue + return ]  public class DoWhile { public static void main(String[]args){ int i=5; do{ System.out.println("i:"+i); // >> 5 i++; // i=6 }while(i<5); // cond. False 6<5 } }  class BreakContinue { public static void main(String args[]){ for(int i=1;i<=5;i++) { if(i==4) break; // execution stops when i becomes 4 System.out.println(i); // >> 1 2 3 } for(int i=1;i<=5;i++) { if(i==1) continue; // execution skip when i becomes 1 System.out.println(i); // >> 2 3 4 5 } } }  class Sample { public static void main(String[]args) { while(false) // while(true) then Infinite looping System.out.print("whileloop"); // >> Error - Unreachable stmt. } }  public class Sample { public static void main(String[]args) { for( ; ; ) System.out.println("For Loop"); // Infinite Looping } }
  • 7. By- Shalabh Chaudhary [GLAU] #1. Write a program to check if the program has received command line arguments or not. If the program has not received the values then print "No Values", else print all the values in a single line separated by ,(comma). Eg1) java Example O/P: No values Eg2) java Example Mumbai Bangalore O/P: Mumbai,Bangalore [Note: You can use length property of an array to check its length >> public class CountCmdLineArg { public static void main(String[] args) { if(args.length==0) System.out.println("No Values"); else { for(int i=0;i<args.length;i++) // for(String values:args) System.out.print(args[i]+", "); // S.o.p(values+", "); } } } #2. Initialize two character variables in a program and display the characters in alphabetical order. Eg1) if first character is s and second is e O/P: e,s Eg2) if first character is a and second is e O/P:a,e >> import java.util.Scanner; public class AlphabetOrder { public static void main(String[] args) { Scanner scan=new Scanner(System.in);
  • 8. By- Shalabh Chaudhary [GLAU] char c1=scan.next().charAt(0); char c2=scan.next().charAt(0); if(c1>c2) System.out.print(c2+","+c1); else System.out.println(c1+","+c2); } }  next() function returns the next token/word in the input as a string and  charAt(0) function returns the first character in that string. #3. Initialize a character variable in a program and if the value is alphabet then print "Alphabet" if it’s a number then print "Digit" and for other characters print "Special Character" >> import java.util.Scanner; public class CheckAplhaDigSpec { public static void main(String[] args) { Scanner scan=new Scanner(System.in); char c=scan.next().charAt(0); if((c>='a' && c<='z') || (c>='A' && c<='Z')) System.out.println("Alphabet"); else if(c>='0' && c<='9') System.out.println("Digit"); else System.out.println("Special Sym"); } }
  • 9. By- Shalabh Chaudhary [GLAU] #4. WAP to accept gender ("Male" or "Female") & age (1-120) from command line arguments and print the percentage of interest based on the given conditions. Interest == 8.2% Gender ==> Female Age ==>1 to 58 Interest == 7.6% Gender ==> Female Age ==>59 -120 Interest == 9.2% Gender ==> Male Age ==>1-60 Interest == 8.3% Gender ==> Male Age ==>61-120 >> public class GenderInterest { public static void main(String[] args) { String gender=args[0]; int age=Integer.parseInt(args[1]); if(gender.equalsIgnoreCase("Female")) { // Compare Strings if(age>=1 && age<=58) System.out.println("Interest= 8.2%"); else if(age>58 && age<=120) System.out.println("Interest= 7.6%"); } else { if(age>=1 && age<=60) System.out.println("Interest= 9.2%"); else if(age>60 && age<=120) System.out.println("Interest= 8.3%"); } } }
  • 10. By- Shalabh Chaudhary [GLAU] #5. Write a program to convert from upper case to lower case and vice versa of an alphabet and print the old character and new character as shown in example (Ex: a->A, M->m). >> import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner scan=new Scanner(System.in); char c=scan.next().charAt(0); int temp; /*if (Character.isLowerCase(c)) System.out.println(c+"->"+Character.toUpperCase(c)); else System.out.println(c+"->"+Character.toLowerCase(c)); */ if(c>='a' && c<='z') { System.out.print(c+"->"); temp=(int)c; c=(char)(temp-32); System.out.println(c); } else { System.out.print(c+"->"); temp=(int)c; c=(char)(temp+32); System.out.println(c); } } }
  • 11. By- Shalabh Chaudhary [GLAU] #6. Write a program to print the color name, based on color code. If color code in not valid then print "Invalid Code". R->Red, B->Blue, G- >Green, O->Orange, Y->Yellow, W->White. >> public class ColorCode { public static void main(String[] args) { char ch=args[0].charAt(0); // Input character using Cmd Line switch(ch) { case 'R': System.out.println("R->Red"); break; case 'B': System.out.println("B->Blue"); break; case 'G': System.out.println("G->Green"); break; case 'O': System.out.println("O->Orange"); break; case 'Y': System.out.println("Y->Yellow"); break; case 'W': System.out.println("W->White"); break; default: System.out.println("Invalid"); } } }
  • 12. By- Shalabh Chaudhary [GLAU] #7. Write a program to check if a given number is prime or not >> public class CheckPrime { public static void main(String[]args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int count=0; for(int i=1;i<=n;i++) { if(n%i==0) count++; } scan.close(); if(count==2) System.out.println("prime"); else System.out.println("Not prime"); } } #8. Write a Java program to find if the given number is prime or not. Example1: C:>java Sample O/P Expected : Please enter an integer number Example2: C:>java Sample 1 O/P Expected : 1 is neither prime nor composite Example3: C:>java Sample 0 O/P Expected : 0 is neither prime nor composite Example4:
  • 13. By- Shalabh Chaudhary [GLAU] C:>java Sample 10 O/P Expected : 10 is not a prime number Example5: C:>java Sample 7 O/P Expected : 7 is a prime number >> public class CheckPrimeComp { public static void main(String[]args) { int n=Integer.parseInt(args[0]); int c=0; if(args.length==0) System.out.println("Please Enter int number"); else if(n==0 || n==1) System.out.println(n+" is neither prime nor composite"); else { for(int i=1;i<=n;i++) { if(n%i==0) c++; } } if(c==2) System.out.println(n+" is a Prime number"); else System.out.println(n+" is not a Prime number"); } }
  • 14. By- Shalabh Chaudhary [GLAU] #9. Write a program to print prime numbers between 10 and 99. >> public class PrimeBetween { public static void main(String[]args) { int temp,i; for(i=10;i<=99;i++) { temp=0; for(int j=2;j<i;j++) { if(i%j==0) { temp=1; break; } } if(temp==0) System.out.println(i); } } } #10. Write a program to add all the values in a given number and print. Ex: 1234->10 >> public class AddDigitNum { public static void main(String[] args) { int n=12345; int rem,val=0; while(n!=0) { rem=n%10; val=val+rem; n=n/10;
  • 15. By- Shalabh Chaudhary [GLAU] } System.out.println(val); } } #11. Write a program to print * in Floyds format (using for and while loop) * * * * * * Example1: C:>java Sample O/P Expected : Please enter an integer number Example1: C:>java Sample 3 O/P Expected : * * * * * * >> public class FloydsForm { public static void main(String[]args) { int n=Integer.parseInt(args[0]); for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { System.out.print("* "); } System.out.println(); } } }
  • 16. By- Shalabh Chaudhary [GLAU] #12. Write a program to reverse a given number and print Eg1) I/P: 1234 O/P:4321 Eg2) I/P:1004 O/P:4001 >> public class ReverseNum { public static void main(String[] args) { int n=12345; int rem; while(n!=0) { rem=n%10; System.out.print(rem); n=n/10; } } } #13. Write Java program to find if given number is palindrome or not Example1: C:>java Sample 110011 O/P Expected: 110011 is a palindrome Example2: C:>java Sample 1234 O/P Expected: 1234 is not a palindrome >> public class PalindromeNum { public static void main(String[] args) {
  • 17. By- Shalabh Chaudhary [GLAU] int n=Integer.parseInt(args[0]); int temp=n; int cur=0,rem; while(temp!=0) { rem=temp%10; cur=cur*10+rem; temp=temp/10; } if(n==cur) System.out.println(n+" is a Palindrome"); else System.out.println(n+" is not a Palindrome"); } } #14. Write a program to print first 5 values which are divisible by 2, 3, and 5. >> public class First5Div { public static void main(String[]args) { int count=0,i=1; while(count<5) { if(i%2==0 && i%3==0 && i%5==0) { System.out.println(i); count++; } i++; } } }
  • 18. By- Shalabh Chaudhary [GLAU] Handling Arrays  An array is a container object that holds a fixed number of values of a single type. Syntax: int[] ar = new int[ar_size]; // new allocates mem. for all ar int  Example using foreach Loops : public class UseForEach { public static void main(String[] args) { double[] ar = {1.9, 2.9, 3.4, 3.5}; for (double ele:ar) System.out.println(ele); // Print all elements } }  Passing Arrays to Methods : mthdName(new int[]{3, 1, 2, 6, 4, 2});  To Find Array Size : int ar_len = ar.length; Array Copy  arraycopy static method from System class -To copy arr ele from one arr to another array. Syntax : public static void arraycopy(obj src, int srcIndx, obj dest, int destIndx, src.length)  Eg: int[] src = {1,2,3,4,5,6}; int[] dest = newint[10]; System.arraycopy(src,0,dest,0,src.length); Two-Dimensional Arrays  Two-dimensional arrays are arrays of arrays.  Initialization : int[][] ar = new int[row_size][col_size];  row_size is mandatory, col_size can be empty else get err.  Eg: 1. int[][] y = { {1,2,3}, {4,5,6}, {7,8,9} }; 2. int[][] y = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
  • 19. By- Shalabh Chaudhary [GLAU] OUTPUT BASED - int[] a = new int[5]{1,2,3,4}; // INVALID - Highlighted wrong int a[5] = new int[5]; // INVALID - Highlighted wrong  class Test { public static void main(String[] args) { while(false) System.out.println("while loop"); // Err – Unreachable stmt. } }  class Test { public static void main(String[] args) { int[] x=new int[10]; System.out.println(x[4]); // Output- 0 {Every ele of arr=0} } }  class Test { public static void main(String [ ] args) { int x[][]=new int[10] [ ]; System.out.println(x[4][0]); // Output- Run Time Error NullPtrExcp } } #1. Write a program to initialize an integer array and print the sum and average of the array >> public class ArraySumAvg { public static void main(String [ ] args) { int ar[]=new int[]{1,2,3,4,5}; int sum=0; float avg=0.0f; for(int ele:ar) sum=sum+ele; avg=(float)sum/ar.length; System.out.println(sum+" "+avg); } }
  • 20. By- Shalabh Chaudhary [GLAU] #2. Write a program to initialize an integer array & find the maximum and minimum value of an array >> Import java.util.Scanner; public class MaxMin { public static void main(String [] args) { Scanner scan=new Scanner(System.in); //System.out.println("Enter Size of Array"); int n=scan.nextInt(); int ar[]=new int[n]; //System.out.println("Enter Array Ele"); for(int i=0;i<n;i++) ar[i]=scan.nextInt(); int max=ar[0]; int min=ar[0]; for(int i:ar) if(i>max) max=i; else if(i<min) min=i; System.out.println("Max "+max); System.out.println("Min "+min); } }
  • 21. By- Shalabh Chaudhary [GLAU] #3. WAP to initialize integer array with values & check if given no is present in the array or not. If the number is not found, it will print -1 else it will print the index value of the given number in array. Ex1) Array elements are {1,4,34,56,7} and the search element is 90 O/P: -1 Ex2) Array elements are {1,4,34,56,7} and the search element is 56 O/P: 4 >> import java.util.Scanner; public class FindEle { public static void main(String [ ] args) { Scanner scan=new Scanner(System.in); //System.out.println("Enter no. of Ele in Array"); int n=scan.nextInt(); int ar[]=new int[n]; //System.out.println("Enter Array Ele"); for(int i=0;i<n;i++) ar[i]=scan.nextInt(); System.out.println("Enter ele to Search"); int ele=scan.nextInt(); int flag=0,i; for(i=0;i<n;i++) if(ar[i]==ele) { flag=1; break; } if(flag==1) System.out.println(ele+" at pos "+(i+1)); else System.out.println(-1); } }
  • 22. By- Shalabh Chaudhary [GLAU] #4. Initialize an integer array with ascii values and print the corresponding character values in a single row. >> import java.util.Scanner; public class ASCII2Symb { public static void main(String [] args) { Scanner scan=new Scanner(System.in); //System.out.println("Enter no. of Ele in Array"); int n=scan.nextInt(); int ar[]=new int[n]; //System.out.println("Enter Array Ele"); for(int i=0;i<n;i++) ar[i]=scan.nextInt(); char ch=0; int i; for(i=0;i<n;i++) { ch=(char)ar[i]; System.out.print(ar[i]+"->"+ch+", "); } } } #5. Write a program to find the largest 2 numbers and the smallest 2 numbers in the given array >> import java.util.Scanner; public class Larget2Smallest { public static void main(String [] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int ar[]=new int[n];
  • 23. By- Shalabh Chaudhary [GLAU] for(int i=0;i<n;i++) ar[i]=scan.nextInt(); int max1,max2,min1,min2; max1=max2=Integer.MIN_VALUE; min1=min2=Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(ar[i]>max1) { max2=max1; max1=ar[i]; } else if(ar[i]>max2) max2=ar[i]; } System.out.println("Largest: "+max1+" & "+max2); for(int i=0;i<n;i++) { if(ar[i]<min1) { min2=min1; min1=ar[i]; } else if(ar[i]<min2) min2=ar[i]; } System.out.println("Smallest: "+min1+" & "+min2); } }  Integer.MIN_VALUE specifies - Integer variable can’t store any value below this limit i.e., limit of int.  Integer.MAX_VALUE – Max value a variable can hold.
  • 24. By- Shalabh Chaudhary [GLAU] Bubble Sort Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Eg: I-Pass: ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Compares first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), No swap. II-Pass: Second Pass: ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. III-Pass: ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )  Algorithm: for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(ar[j]>ar[j+1]) { int temp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=temp; } #6. Write a program to initialize an array and print them in a sorted fashion. >> import java.util.Scanner; public class ArraySort { public static void main(String [] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt();
  • 25. By- Shalabh Chaudhary [GLAU] int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=scan.nextInt(); for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(ar[j]>ar[j+1]) { int temp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=temp; } for(int i=0;i<n;i++) System.out.print(ar[i]+" "); } }  Arrays.sort(ar); ==> To sort any Array. ar-Array to sort. 7 Write a program to remove the duplicate elements in an array and print Eg) Array Elements--12,34,12,45,67,89 O/P: 12,34,45,67,89 >> import java.util.Scanner; public class RemoveDuplictes { public static void main(String [] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=scan.nextInt();
  • 26. By- Shalabh Chaudhary [GLAU] for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(ar[j]>ar[j+1]) { int temp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=temp; } System.out.println("Sorted Array:"); for (int i=0; i<n; i++) System.out.print(ar[i]+" "); int[] temp = new int[n]; int j = 0; for (int i=0; i<n-1; i++) if (ar[i] != ar[i+1]) temp[j++] = ar[i]; // Store ele if curr_ele!=next_ele temp[j++] = ar[n-1]; // Store last_ele unique/repeated, not stored prev // Modify original array for (int i=0; i<j; i++) ar[i] = temp[i]; System.out.println("nArray without Duplicates:"); for (int i=0; i<j; i++) System.out.print(ar[i]+" "); } }
  • 27. By- Shalabh Chaudhary [GLAU] 8 Write a program to print the element of an array that has occurred the highest number of times Eg) Array -> 10,20,10,30,40,100,99 O/P:10 >> import java.util.Arrays; import java.util.Scanner; public class HighestFrequency { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=scan.nextInt(); Arrays.sort(ar); int max_count=1,cur_count=1; int res=ar[0]; for(int i=1;i<n;i++) if(ar[i]==ar[i-1]) cur_count++; else { if(cur_count>max_count) { max_count=cur_count; res=ar[i-1]; } cur_count=1; } if(cur_count>max_count) { max_count=cur_count;
  • 28. By- Shalabh Chaudhary [GLAU] res=ar[n-1]; } System.out.println("Max Occured ele: "+res); } }  Efficient solution – If Use Hashing - O(n). [For Above Q.] 9 Write a program to print the sum of the elements of the array with the given below condition. If the array has 6 and 7 in succeeding orders, ignore 6 and 7 and the numbers between them for the calculation of sum. Eg1) Array Elements - 10,3,6,1,2,7,9 O/P: 22 [i.e 10+3+9] Eg2) Array Elements - 7,1,2,3,6 O/P:19 Eg3) Array Elements - 1,6,4,7,9 O/P:10 >> import java.util.Scanner; public class SumExceptBetween67 { public static void main(String [] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=scan.nextInt(); int flag=0; int sum=0; for(int i:ar) {
  • 29. By- Shalabh Chaudhary [GLAU] if(i==6) flag=1; if(flag==1) { if(i==7) flag=0; continue; // Above code to skip val b/w 6 to 7 } else { // If first get 7 then add 6, next time 6 come then skipped from above code if(i==7) sum+=i+6; else sum+=i; } } System.out.println("Total: "+sum); } } #10. Write a program to reverse the elements of a given 2*2 array. Four integer numbers needs to be passed as Command Line arguments. Example1: C:>java Sample 1 2 3 O/P Expected : Please enter 4 integer numbers Example2: C:>java Sample 1 2 3 4 O/P Expected : The given array is : 1 2
  • 30. By- Shalabh Chaudhary [GLAU] 3 4 The reverse of the array is : 4 3 2 1 1 2 3 4 5 6 7 8 9 10 11 12 >> #11. Write a program to find greatest number in a 3*3 array. The program is supposed to receive 9 integer numbers as command line arguments. Example1: C:>java Sample 1 2 3 O/P Expected : Please enter 9 integer numbers Example2: C:>java Sample 1 23 45 55 121 222 56 77 89 O/P Expected : The given array is : 1 23 45 55 121 222 56 77 89 The biggest number in the given array is 222 >> Self
  • 31. By- Shalabh Chaudhary [GLAU] IMPORTANT QUESTIONS  1. What is JIT compiler? 2. What is Adaptive optimizer? 3. What is Byte Code Verifier? 4. What is the difference between a Compiler and Interpreter? 5. What are the components of JVM? 6. How do you assign values for PATH and CLASSPATH Variable? 7. What are all the characteristic features of Java Programming language?