Sie sind auf Seite 1von 46

Example2.

java
class Example2 {
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}

Example 3. Java
class IfSample
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
Example4. Java
class Ladder {
public static void main(String[] args)
{
int number = 0;
if (number > 0)
{
System.out.println("Number is positive.");
}
else if (number < 0)
{
System.out.println("Number is negative.");
}
Else
{
System.out.println("Number is 0.");
}
}
}

Nested if
class Number
{
public static void main(String[] args)
{
Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
if (n1 >= n2)
{
if (n1 >= n3)
{
largestNumber = n1;
}
else {
largestNumber = n3;
}
}
else {
if (n2 >= n3)
{
largestNumber = n2;
}
else {
largestNumber = n3;
}
}
System.out.println("Largest number is " + largestNumber);
}
}

Example 5.java
import java.util.Scanner;
class Calculator {
public static void main(String[] args)
{
char operator;
Double number1, number2, result;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter operator (either +, -, * or /): ");
operator = scanner.next().charAt(0);
System.out.print("Enter number1 and number2 respectively: ");
number1 = scanner.nextDouble();
number2 = scanner.nextDouble();
switch (operator) {
case '+': result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;
case '-': result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break;
case '*': result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;
case '/': result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;
default: System.out.println("Invalid operator!");
break;
}
}
}

Example 6.java
class Number {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; ++i) {
sum += i; // sum = sum + i
}
System.out.println("Sum = " + sum);
}}
Infinite loop
class Infinite {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; --i) {
System.out.println("Hello");
}
}
}

Example 7.java
class ForLoop {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < vowels.length; ++ i) {
System.out.println(vowels[i]);
}
}
}
You can perform the same task using for-each loop as follows:
class AssignmentOperator {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// foreach loop
for (char item: vowels) {
System.out.println(item);
}
}}
Enhancedforloop.java
class EnhancedForLoop {
public static void main(String[] args) {
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}

// Use for-each style for on a two-dimensional array.


class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the values
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
The output from this program is shown here:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
Named loops :
// A Java program to demonstrate working of named loops.
public class Testing
{
public static void main(String[] args)
{
loop1:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (i == 3)
break loop1;
System.out.println("i = " + i + " j = " + j);
}
}
}
}

While.java
class Loop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println("Line " + i);
++i;
}
}
}
Dowhile.java
import java.util.Scanner;
class Sum {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0);
System.out.println("Sum = " + sum);
}
}

Do while using menu driven


Dowhilemenu.java
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4': System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for

Scanner.java
import java.util.Scanner;
public class ScannerDemo1
{
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);

// Numerical data input


// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();

// Print the values to check if input was correctly obtained.


System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}

Sacnnerfromfile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class insertionSort {

public static void main(String[] args) {

File file = new File("10_Random");

try {

Scanner sc = new Scanner(file);

while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Scannerforfileread.java
package org.learn.io.scan;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ReadFileUsingScanner {

public static void main(String[] args) throws IOException {


//Write content to file
writeFileContents();
//Reading content of file using Scanner class
readFileContents();
}

private static void writeFileContents() throws IOException {

try (FileWriter fileWriter = new FileWriter("info.txt")) {


fileWriter.write("10 ");
fileWriter.write("20.5 ");
fileWriter.write("Employee ");
fileWriter.write("50.00 ");
fileWriter.write("Coffee");
}
}

private static void readFileContents() throws IOException {


System.out.println("Reading contents of file using Scanner class:");
try (FileReader fileReader = new FileReader("info.txt");
Scanner scanner=new Scanner(fileReader)){
while (scanner.hasNext()) {
if(scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
} else if(scanner.hasNextDouble()) {
System.out.println(scanner.nextDouble());
} else if(scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
}
}

bufferReader.java
// Code using Buffer Class
import java.io.*;
class Differ
{
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a +
" and name as " + b);
}
}

Bufferereaderfromfile.java
package com.mkyong;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 {

private static final String FILENAME = "E:\\test\\filename.txt";

public static void main(String[] args) {

BufferedReader br = null;
FileReader fr = null;
try {

//br = new BufferedReader(new FileReader(FILENAME));


fr = new FileReader(FILENAME);
br = new BufferedReader(fr);

String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {


System.out.println(sCurrentLine);
}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (br != null)
br.close();

if (fr != null)
fr.close();

} catch (IOException ex) {

ex.printStackTrace();

Singleton.java
package com.java2novice.algos;

public class MySingleton {

private static MySingleton myObj;


static{
myObj = new MySingleton();
}

private MySingleton(){

public static MySingleton getInstance(){


return myObj;
}

public void testMe(){


System.out.println("Hey.... it is working!!!");
}

public static void main(String a[]){


MySingleton ms = getInstance();
ms.testMe();
}
}

Scope.java
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
- 46 -
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}

class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Conversion.java
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

promote.java
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

Array.java
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

// An improved version of the previous program.


class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

Twod.java
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

ThreeD.java
// Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}

Basicmath.java
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}

Matrixarray.java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}

Passarray.java
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr);
}
public static void sum(int[] arr)
{
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}

Returnarray.java
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{
// returning array
return new int[]{1,2,3};
}
}

Clonearray.java
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
int cloneArray[] = intArray.clone();
// will print false as deep copy is created for one-dimensional array
System.out.println(intArray == cloneArray);
for (int i = 0; i < cloneArray.length; i++)
{
System.out.print(cloneArray[i]+" ");
}
}
}

Clonemultidarray.java
class Test
{
public static void main(String args[])
{
int intArray[][] = {{1,2,3},{4,5}};
int cloneArray[][] = intArray.clone();
// will print false
System.out.println(intArray == cloneArray);
// will print true as shallow copy is created i.e. sub-arrays are shared
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}

Objectarray.java
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
public class GFG
{
public static void main (String[] args)
{
Student[] arr;
arr = new Student[5];
arr[0] = new Student(1,"ayushi");
arr[1] = new Student(2,"nainsih");
arr[2] = new Student(3,"mohnish");
arr[3] = new Student(4,"anshul");
arr[4] = new Student(5,"Aparna");
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}

Copying Arrays Using Assignment Operator


Let's take an example,

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

int [] numbers = {1, 2, 3, 4, 5, 6};


int [] positiveNumbers = numbers; // copying arrays

for (int number: positiveNumbers) {


System.out.print(number + ", ");
}
}
}

Using Looping Construct to Copy Arrays


Let's take an example:

import java.util.Arrays;

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

int [] source = {1, 2, 3, 4, 5, 6};


int [] destination = new int[6];

for (int i = 0; i < source.length; ++i) {


destination[i] = source[i];
}
// converting array to string
System.out.println(Arrays.toString(destination));
}
}

Arraycopy.java
// To use Arrays.toString() method
import java.util.Arrays;

class ArraysCopy {
public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2};

int[] n3 = new int[5];

// Creating n2 array of having length of n1 array


int[] n2 = new int[n1.length];

// copying entire n1 array to n2


System.arraycopy(n1, 0, n2, 0, n1.length);
System.out.println("n2 = " + Arrays.toString(n2));

// copying elements from index 2 on n1 array


// copying element to index 1 of n3 array
// 2 elements will be copied
System.arraycopy(n1, 2, n3, 1, 2);
System.out.println("n3 = " + Arrays.toString(n3));
}
}

Copyofrange.java
// To use toString() and copyOfRange() method
import java.util.Arrays;

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

int[] source = {2, 3, 12, 4, 12, -2};

// copying entire source array to destination


int[] destination1 = Arrays.copyOfRange(source, 0, source.length);
System.out.println("destination1 = " + Arrays.toString(destination1));

// copying from index 2 to 5 (5 is not included)


int[] destination2 = Arrays.copyOfRange(source, 2, 5);
System.out.println("destination2 = " + Arrays.toString(destination2));
}
}
import java.util.Arrays;

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

int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new int[source.length][];

for (int i = 0; i < source.length; ++i) {


// allocating space for each row of destination array
destination[i] = new int[source[i].length];
System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);
}

// displaying destination array


System.out.println(Arrays.deepToString(destination));
}
}
Conversionofonedtotwod.java

class TwoDArray
{
public static void main(String args[])
{
int a[][]=new int[4][3];
int d[]={10,20,30,40,50,60,70,80,90,100,110,120};

int count=0;

for(int i=0;i<4;i++)
{
for(int j=0;j<3;j++)
{
if(count==d.length) break;
a[i][j]=d[count];
System.out.printf("a[%d][%d]= %d\n",i,j,a[i][j]);
count++;
}
}

System.out.println("Count is "+count);
}
}

copytwodtoonedarray.java
public class Matrix2Array {

int r, c;
int array[];
int matrix[][];

public Matrix2Array() {
Scanner input = new Scanner(System.in);
System.out.println("This program is Matrix(2D) "
+ "elements will convert to (1D)array");
System.out.println("Enter the value of row =");
r = input.nextInt();
System.out.println("Enter the value of coloum =");
c = input.nextInt();
array = new int[r * c];
matrix = new int[r][c];
}

public void put(int i, int j, int e) {


array[(i) * c + j] = e;
}

public int get(int i, int j) {


return array[(i) * c + j];
}

public void StoreMatrix() {


for (int rr = 0; rr < r; rr++) {
for (int cc = 0; cc < c; cc++) {
int ee=(int) Math.round(Math.random()*89+10);
matrix[rr][cc] =ee ;;
put(rr, cc, ee);
}
}
}

public void PrintMatrix() {


System.out.println("Element are Store in "
+ "Matrix in row " + r + " Coloum " + c);
for (int rr = 0; rr < r; rr++) {
for (int cc = 0; cc < c; cc++) {
System.out.print(matrix[rr][cc] + "\t ");
}
System.out.println();
}
}

public void PrintArray() {


System.out.println("Element converted to array &"
+ " Array length=" + array.length);
for (int rr = 0; rr < r; rr++) {
for (int cc = 0; cc < c; cc++) {
System.out.print(get(rr, cc) + " ");
}
}
}

public static void main(String args[]) {


Matrix2Array M = new Matrix2Array();
M.StoreMatrix();
M.PrintMatrix();
M.PrintArray();
}
}

OpEquals.java
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

IncDec.java
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

Using the Bitwise Logical Operators


The following program demonstrates the bitwise logical operators:
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Byteshift.java
// Left shifting a byte value.
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
The output generated by this program is shown here:
Original value of a: 64
i and b: 256 0

quickmulity.java
// Left shifting as a quick way to multiply by 2.
class MultByTwo {
public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++) {
num = num << 1;
System.out.println(num);
}
}
}

Boollogicop.java
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

Ternary.java
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Absolute value of 10 is 10
Absolute value of -10 is 10

Break.java
// Using break to exit a while loop.
class BreakLoop2 {
public static void main(String args[]) {
int i = 0;
while(i < 100) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}

Breakgoto.java
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Running this program generates the following output:
Before the break.
This is after second block.

Nestedbreak.java
// Using break to exit from nested loops
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
This program generates the following output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

Continue.java
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}

Continuelabel.java
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}

Return.java
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

Box.java
class Box {
double width;
double height;
double depth;
}

Boxdemo.java
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

Class with methods


class Box {
double width;
double height;
double depth;
// display volume of a box
double volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}

class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
Double a=mybox1.volume();
// display volume of second box
Double b= mybox2.volume();
SOP(a);
SOP(b);
}
}

This.java
class Test
{
int a;
int b;

// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test(10, 20);
object.display();
}
}

Thisconstructor.java

class Test
{
int a;
int b;

//Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}
//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test();
}
}

Thisreturn.java

class Test
{
int a;
int b;

//Default constructor
Test()
{
a = 10;
b = 20;
}

//Method that returns current class instance


Test get()
{
return this;
}

//Displaying value of variables a and b


void display()
{
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test();
object.get().display();
}
}

Thismethodpara.java

class Test
{
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + a + " b = " + b);
}

Thisinvokecurrentmethod.java

// Method that returns current class instance


void get()
{
display(this);
}

public static void main(String[] args)


{
Test object = new Test();
object.get();
}
}

class Test {

void display()
{
// calling fuction show()
this.show();

System.out.println("Inside display function");


}

void show() {
System.out.println("Inside show funcion");
}

public static void main(String args[]) {


Test t1 = new Test();
t1.display();
}
}

Thisargurmetnconst.java
// Java code for using this as an argument in constructor call
// Class with object of Class B as its data member
class A
{
B obj;

// Parameterized constructor with object of B


// as a parameter
A(B obj)
{
this.obj = obj;

// calling display method of class B


obj.display();
}

class B
{
int x = 5;

// Default Contructor that create a object of A


// with passing this as an argument in the
// constructor
B()
{
A obj = new A(this);
}

// method to show value of x


void display()
{
System.out.println("Value of x in Class B : " + x);
}

public static void main(String[] args) {


B obj = new B();
}
}

Chainthis.java
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}

Anonymous.java
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}

Classforname.java
public class Demo
{
int x = 10;
public static void main(String args[]) throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
Class myClass = Class.forName("Demo");
Object obj = myClass.newInstance();
Demo d1 = (Demo) obj;
d1.x = 10;
System.out.println("Object created and value is " + d1.x); // prints 10
}
}

Constructorfornameinstance.java
public class Employee
{

private int empId;


private String empName;
private int empSalary;
public Employee(int empId, String empName, int empSalary) {
this.empId = empId;
this.empName = empName;
this.empSalary = empSalary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpSalary() {
return empSalary;
}
public void setEmpSalary(int empSalary) {
this.empSalary = empSalary;
}
}
ConstructorNewInstanceExample.java

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorNewInstanceExample


{
public static void main(String args[])
{
try
{
Class clasz = Class.forName("com.javainterviewpoint.Employee");
Constructor constructor = clasz.getConstructor(new
Class[]{int.class,String.class,int.class});
Employee employee =
(Employee)constructor.newInstance(1,"JavaInterviewPoint",45000);
System.out.println("Employee Id : "+employee.getEmpId());
System.out.println("Employee Name : "+employee.getEmpName());
System.out.println("Employee Salary : "+employee.getEmpSalary());

}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
}

Serialization.java
import java.io.*;

class Demo implements java.io.Serializable


{
public int a;
public String b;

// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}

class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, "geeksforgeeks");
String filename = "file.ser";

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object


out.writeObject(object);

out.close();
file.close();

System.out.println("Object has been serialized");

catch(IOException ex)
{
System.out.println("IOException is caught");
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}

catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}

}
}

Singleton.java

public class MySingleTon {

private static MySingleTon myObj;


private MySingleTon(){

public static MySingleTon getInstance(){


if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}

public void getSomeThing(){


// do something here
System.out.println("I am here....");
}

public static void main(String a[]){


MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}

Constructorchain.java
public class MyChaining {

public MyChaining(){
System.out.println("In default constructor...");
}
public MyChaining(int i){
this();
System.out.println("In single parameter constructor...");
}
public MyChaining(int i,int j){
this(j);
System.out.println("In double parameter constructor...");
}

public static void main(String a[]){


MyChaining ch = new MyChaining(10,20);
}
}

Garbage.java
// Java program to demonstrate requesting
// JVM to run Garbage Collector
public class Test
{
Test i;
public static void main(String[] args) throws InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();
t1.i=t2;
t2.i=t1;
// both are pointing to each other. Neither Object 1 nor Object 2 is referenced by any other
object. That’s an island of isolation.
// Nullifying the reference variable
t1 = null;

// requesting JVM for running Garbage Collector


System.gc();

// Nullifying the reference variable


t2 = null;

// requesting JVM for running Garbage Collector


Runtime.getRuntime().gc();

@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}

Output:

Garbage collector called


Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8

Beforefinalize.java
public class Test
{
public static void main(String[] args) throws InterruptedException
{
String str = new String("abdcs");

// making str eligible for gc


str = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("end of main");
}

@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}

Output:
end of main

finalize.java
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();

// making t eligible for garbage collection


t = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("end main");
}

@Override
protected void finalize()
{
System.out.println("finalize method called");
System.out.println(10/0);
}

}
Output:

finalize method called


end main

Questiononfinalize.java
public class Test
{
static Test t ;
static int count =0;
public static void main(String[] args) throws InterruptedException
{
Test t1 = new Test();
// making t1 eligible for garbage collection
t1 = null; // line 12

// calling garbage collector


System.gc(); // line 15

// waiting for gc to complete


Thread.sleep(1000);

// making t eligible for garbage collection,


t = null; // line 21

// calling garbage collector


System.gc(); // line 24

// waiting for gc to complete


Thread.sleep(1000);
System.out.println("finalize method called "+count+" times");

@Override
protected void finalize()
{
count++;

t = this; // line 38

Output:
finalize method called 1 times

Question2.java
public class Test
{
public static void main(String[] args)
{
// How many objects are eligible for
// garbage collection after this line?
m1(); // Line 5
}
static void m1()
{
Test t1 = new Test();
Test t2 = new Test();
}
}
Question :
How many objects are eligible for garbage collection after execution of line 5 ?

Question3.java

public class Test


{
public static void main(String [] args)
{
Test t1 = new Test();
Test t2 = m1(t1); // line 6
Test t3 = new Test();
t2 = t3; // line 8

static Test m1(Test temp)


{
temp = new Test();
return temp;
}
}
Question :
How many objects are eligible for garbage collection after execution of line 8?

Das könnte Ihnen auch gefallen