Beruflich Dokumente
Kultur Dokumente
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);
}
}
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);
}
}
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);
Sacnnerfromfile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
try {
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;
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;
BufferedReader br = null;
FileReader fr = null;
try {
String sCurrentLine;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
ex.printStackTrace();
Singleton.java
package com.java2novice.algos;
private MySingleton(){
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.");
}
}
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}};
}}
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);
}
}
class CopyArray {
public static void main(String[] args) {
import java.util.Arrays;
class ArraysCopy {
public static void main(String[] args) {
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};
Copyofrange.java
// To use toString() and copyOfRange() method
import java.util.Arrays;
class ArraysCopy {
public static void main(String[] args) {
class AssignmentOperator {
public static void main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
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];
}
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);
}
}
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 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);
}
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");
}
Thisreturn.java
class Test
{
int a;
int b;
//Default constructor
Test()
{
a = 10;
b = 20;
}
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
class Test {
void display()
{
// calling fuction show()
this.show();
void show() {
System.out.println("Inside show funcion");
}
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;
class B
{
int x = 5;
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
{
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
}
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.*;
// 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);
out.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Singleton.java
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...");
}
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;
@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:
Beforefinalize.java
public class Test
{
public static void main(String[] args) throws InterruptedException
{
String str = new String("abdcs");
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();
System.out.println("end main");
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
System.out.println(10/0);
}
}
Output:
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
@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