Java Practice
Java Practice
Scanner;
input.nextLine();
System.out.print("Your favourite food : ");
String food = input.nextLine();
import javax.swing.JOptionPane;
double x = 67.573;
double y = 25;
// round gives an int val 4.4= 4, 5.65=6
// floor gives int val 6.7 =6
// ceil gives int val 5.4 =6
double z = Math.ceil(x);
System.out.println(z);
z = Math.floor(x);
System.out.println(z);
z = Math.round(x);
System.out.println(z);
import java.util.Random;
boolean z = random1.nextBoolean();
System.out.println(z);
// 2D Array
String[][] car = new String[][] {
{"Mustang", "BMW", "Camaro"},
{"Toyota", "Corvette", "Mercedes"},
{"Ranger","F-150","Ferrari"}
};
import java.util.*;
// 2D ArrayList
ArrayList<ArrayList<String>> groceryList = new ArrayList<>();
groceryList.add(bakeryList);
groceryList.add(produceList);
groceryList.add(drinksList);
System.out.println(groceryList.get(0));
System.out.println(groceryList.get(2).get(1));
import java.util.ArrayList;
food.set(3, "Hamburger");
food.remove("Hamburger");
//food.remove(3)
for (int i = 0; i < food.size(); i++) {
System.out.println(food.get(i));
}
}
}
for(String i : pet){
System.out.println(i);
}
// Method Overloading
public static void main(String[] args) {
int x = 5, y = 6, z = 7;
int sum = hello(x, y);
System.out.println("x + y = "+ sum);
sum = hello(x, y, z);
System.out.println("x + y + z = "+ sum);
double m = 3.14, n = 5.67;
double doubleSum = hello(m,n);
System.out.println("x + y = "+ doubleSum);
}
static int hello(int a, int b) {
return a + b;
}
static int hello(int a, int b, int c) {
return a + b + c;
}
static double hello(double a, double b) {
return a + b;
}
// printf() = an optional method to control, format, and display text to the
console window
// two arguments = format string + (object/variable/value)
// % [flags] [precision] [width] [conversion-character]
boolean myBoolean = true;
char myChar = '@';
String myString = "Minju";
int myInt = 50;
double myDouble = -12832.36762;
// [conversion-character]
//System.out.printf("%b",myBoolean);
//System.out.printf("%c",myChar);
//System.out.printf("%s",myString);
//System.out.printf("%d",myInt);
//System.out.printf("%f",myDouble);
//[width]
// minimum number of characters to be written as output
//System.out.printf("Hello %10s",myString);
//[precision]
// sets number of digits of precision when outputting floating-point values
//System.out.printf("You have this much money %.1f",myDouble);
// [flags]
// adds an effect to output based on the flag added to format specifier
// - : left-justify
// + : output a plus ( + ) or minus ( - ) sign for a numeric value
// 0 : numeric values are zero-padded
// , : comma grouping separator if numbers > 1000
public Class1() {
Random random = new Random();
int number = 0;
// local var of constructor
// so pass as args
roll(random, number);
}
public void roll(Random random, int number) {
number = random.nextInt(6)+1;
System.out.println(number);
}
System.out.println(foods[i].foodName);
}
// for (Class1 i: foods) {
//
// System.out.println(i.foodName);
// }
---------
public class Class1 {
package Package1;
import Package2.*;
public class A {
public static void main(String[] args) {
// Here A,C cls is in package1, Asub, B is in package2
// package is a collection of classes
//default- can be accessed by classes in the same package
//public- can be accessed by classes every package
//protected- can be accessed by classes in the same package and
subclasses in other package
//private- can be accessed by classes in the same package
package Package1;
import Package2.*;
public class C {
String defaultMessage1 = "I am learning Java.";
}
public class A {
public static void main(String[] args) {
// using getter/setter to access private attributes
C c1 = new C("Chervolet","Camaro", 2021);
c1.setYear(2022);
System.out.println(c1.getMake());
System.out.println(c1.getModel());
System.out.println(c1.getYear());
}
}
--------------------------
public class C extends A {
private String make;
private String model;
private int year;
System.out.println(stu1.getName());
System.out.println(stu1.getDept());
System.out.println(stu1.getID());
System.out.println();
// copy stu1 and paste it to stu2
//stu2.copy(stu1);
System.out.println(stu2.getName());
System.out.println(stu2.getDept());
System.out.println(stu2.getID());
}
}
----------------------
public class C extends A {
private String name ;
private String dept;
private int ID ;
}
----------------------
public class Fish implements Prey, Predator {
@Override
public void hunt() {
System.out.println("*The fish hunting a small fish.*");
}
// implementing Prey interface and overriding pre-defined methods
// classes can implement multiple interfaces
@Override
public void flee() {
System.out.println("*The fish fleeing from the shark.*");
}
}
------------------------
//This is an interface
public interface Prey {
void flee();
}
-----------------------------
//This is an interface
public interface Predator {
void hunt();
}
---------------------------------
public class Rabbit extends Animals {
@Override
public void eats() {
System.out.println("*Rabbits eats.*");
}
}
if(choice == 1) {
Animal = new Cat();
Animal.speaks();
} else if ( choice == 0 ) {
Animal = new Fish();
Animal.speaks();
} else {
Animal = new Animals();
System.out.println("Invalid choice.");
Animal.speaks();
}
-----------------------------------
public class Animals {
public void speaks() {
System.out.println("*Mara Kha* in animal language!!!");
}
}
public class Fish extends Animals {
@Override
public void speaks() {
System.out.println("Fish goes *Wiggle*");
}
}
public class Cat extends Animals {
@Override
public void speaks() {
System.out.println("Cat goes *Meow*");
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
try {
System.out.print("Enter an integar number : ");
int x = input.nextInt();
System.out.print("Enter an integar number : ");
int y = input.nextInt();
int z = x/y ;
System.out.println("z : "+ z);
}
catch(ArithmeticException i) {
System.out.println("It's an ArithmeticException");
}
catch (InputMismatchException e) {
System.out.println("It's an InputMismatchException");
}
catch(Exception e) {
System.out.println("Invalid Input.Check again.");
}
finally {
input.close();
}
}
}
if(file1.exists()) {
System.out.println("That file exists.");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
file1.delete();
}
else {
System.out.println("That file doesn't exist.");
}
}
}
// File writing
import java.io.FileWriter;
import java.io.IOException;
try {
FileWriter writer = new FileWriter("poem.txt");
writer.write("Hello, My name is Fatema Islam\n");
writer.write("I am in CSE dept.\n");
writer.append("I am in Dhaka.");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
FileReader reader;
try {
reader = new FileReader("art.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
}
}
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.*;
import java.io.File;
// Java Audio
import java.util.Scanner;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
AudioInputStream audiostream =
AudioSystem.getAudioInputStream(file);
clip.open(audiostream);
switch(choice) {
case "P" : clip.start();
break;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Color;
// init, visibility, size, title, resize,image, close, backgrnd, color
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(420, 500);
frame.setResizable(false);
frame.setTitle("GUI Practice");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("maki 8.jpg");
frame.setIconImage(icon.getImage());
//frame.getContentPane().setBackground(Color.pink);
frame.getContentPane().setBackground(new Color(0xFFFFFF));
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import javax.swing.border.Border;
label.setText("Hello");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setIconTextGap(10);
label.setForeground(Color.GREEN);
label.setBackground(Color.DARK_GRAY);
label.setOpaque(true);
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
//label.setBounds(185,115, 630, 420);// border within frame backgrnd
//Label
public static void main(String[] args) {
JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("maki 8.jpg");
ImageIcon imageIcon = new ImageIcon("download 1.png");
Border border = BorderFactory.createLineBorder(Color.CYAN, 4); // border color,
thickness
label.setBorder(border);
frame.add(label);
frame.setTitle("Hello");
frame.setIconImage(image.getImage());
frame.setSize(528,528);
frame.setLayout(null);
//if set layout to null then have to set bounds
frame.getContentPane().setBackground(Color.BLACK);
// if pack is used default layout is used by default, frame sie, bound not needed
//frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
frame.add(cyanPanel);
frame.add(pinkPanel);
bluePanel.add(label);
frame.add(bluePanel);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
JButton button;
GUI () {
button =new JButton();
button.setBounds(200,100,100,50);
button.setText("Start music");
button.addActionListener(this);
this.setTitle("GUI Window");
ImageIcon image = new ImageIcon("maki 8.jpg");
this.setIconImage(image.getImage());
this.setLayout(null);
this.setSize(750, 630);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
System.out.println(“Hello”);
}
}
}
label.setBounds(200,0,750,650);
label.setIcon(image1);
label.setVisible(false);
this.setTitle("GUI Window");
ImageIcon image2 = new ImageIcon("maki 8.jpg");
this.setIconImage(image2.getImage());
this.setLayout(null);
this.setSize(750, 650);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(button);
this.add(label);
this.setResizable(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
label.setVisible(true);
}
}
}
panel1.setBackground(Color.GRAY);
panel2.setBackground(Color.LIGHT_GRAY);
panel3.setBackground(Color.DARK_GRAY);
panel4.setBackground(Color.CYAN);
panel5.setBackground(Color.PINK);
panel2.setLayout(new BorderLayout());
panel1.setPreferredSize(new Dimension(50,50));
panel2.setPreferredSize(new Dimension(50,50));
panel3.setPreferredSize(new Dimension(50,50));
panel4.setPreferredSize(new Dimension(50,50));
panel5.setPreferredSize(new Dimension(50,50));
// --------------------------sub panels-----------------------
panel6.setBackground(Color.BLUE);
panel7.setBackground(Color.ORANGE);
panel8.setBackground(Color.RED);
panel9.setBackground(Color.BLACK);
panel10.setBackground(Color.YELLOW);
panel6.setPreferredSize(new Dimension(50,50));
panel7.setPreferredSize(new Dimension(50,50));
panel8.setPreferredSize(new Dimension(50,50));
panel9.setPreferredSize(new Dimension(50,50));
panel10.setPreferredSize(new Dimension(50,50));
panel2.add(panel6, BorderLayout.EAST);
panel2.add(panel7, BorderLayout.WEST);
panel2.add(panel8, BorderLayout.CENTER);
panel2.add(panel9, BorderLayout.NORTH);
panel2.add(panel10, BorderLayout.SOUTH);
frame.add(panel4, BorderLayout.EAST);
frame.add(panel5, BorderLayout.WEST);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel3, BorderLayout.SOUTH);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
frame.add(new JButton("1"));
frame.add(new JButton("2"));
frame.add(new JButton("3"));
frame.add(new JButton("4"));
frame.add(new JButton("5"));
frame.add(new JButton("6"));
frame.add(new JButton("7"));
frame.add(new JButton("8"));
frame.add(new JButton("9"));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
launchPage() {
button.setBounds(100, 160, 200, 40);
button.setFocusable(false);
button.addActionListener(this);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(420, 420);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
frame.dispose();
NewWindow myWindow = new NewWindow();
}
}
}
-------------------------------------
import javax.swing.*;
import java.awt.*;
NewWindow() {
imageIcon = new ImageIcon(n);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setIcon(imageIcon);
label.setBounds(110,85,200,250);
label.setFont(new Font(null, Font.PLAIN, 25));
frame.add(label);
frame.setLayout(null);
frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
frame1.setSize(420, 420);
frame1.setResizable(false);
frame1.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
JOptionPane.showOptionDialog(null,
"Maki Zenin?",
"Message",JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,image,
responses,0);
}
}
JButton button;
JTextField textField;
NewWindow() {
button = new JButton("submit");
button.addActionListener(this);
button.setFocusable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
textField = new JTextField();
textField.setPreferredSize(new Dimension(250,50));
textField.setFont(new Font("Comic Sans MS", Font.PLAIN, 35));
textField.setForeground(Color.MAGENTA);
textField.setBackground(Color.PINK);
textField.setCaretColor(Color.PINK);
this.add(button);
this.add(textField);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(textField.getText());
}
launchPage() {
button.setBounds(100,160,200,40);
button.setFocusable(false);
button.addActionListener(this);
frame.add(button);
frame.setLayout(null);
frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== button) {
frame.dispose();
NewWindow myWindow = new NewWindow();
}
}
------------------------------------
public class NewWindow extends JFrame implements ActionListener{
JButton button ;
JCheckBox checkBox;
ImageIcon icon1 = new ImageIcon("maki 8.jpg");
ImageIcon icon2 = new ImageIcon("maki 1.jpg");
Image n1 = icon1.getImage().getScaledInstance(65,80,Image.SCALE_DEFAULT);
Image n2 = icon2.getImage().getScaledInstance(55,80,Image.SCALE_DEFAULT);
NewWindow() {
icon1 = new ImageIcon(n1);
icon2 = new ImageIcon(n2);
this.add(button);
this.add(checkBox);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(checkBox.isSelected());
}
}